@genex-ai/multiplayer 0.17.9 → 0.17.10
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 +1 -0
- package/README.md +1 -1
- package/dist/authority/fast-webtransport.js +2 -2
- package/dist/authority/index.d.ts +57 -1
- package/dist/authority/index.js +16 -4
- package/dist/bridge-authority.global.js +8 -8
- package/dist/bridge-authority.js +4 -4
- package/dist/bridge.js +3 -3
- package/dist/{chunk-TEHGMFAG.js → chunk-42R7NREA.js} +1 -1
- package/dist/{chunk-WEMRRIHH.js → chunk-7J3YWPCA.js} +1 -1
- package/dist/{chunk-ZDGSUR6E.js → chunk-HHETHPGL.js} +2 -2
- package/dist/{chunk-DJ2XYETS.js → chunk-NSQQCLMA.js} +2 -2
- package/dist/{chunk-MQYARUGU.js → chunk-SQC6WTMF.js} +75 -11
- package/dist/index.js +3 -3
- package/dist/protocol.d.ts +1 -1
- package/dist/protocol.js +1 -1
- package/package.json +1 -1
|
@@ -1,15 +1,15 @@
|
|
|
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 ->
|
|
1
|
+
"use strict";(()=>{var oE=Object.create;var uu=Object.defineProperty;var iE=Object.getOwnPropertyDescriptor;var aE=Object.getOwnPropertyNames;var cE=Object.getPrototypeOf,uE=Object.prototype.hasOwnProperty;var qm=t=>{throw TypeError(t)};var lE=(t,e,n)=>e in t?uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var ht=(t,e)=>()=>(t&&(e=t(t=0)),e);var dE=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),af=(t,e)=>{for(var n in e)uu(t,n,{get:e[n],enumerable:!0})},fE=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of aE(e))!uE.call(t,s)&&s!==n&&uu(t,s,{get:()=>e[s],enumerable:!(r=iE(e,s))||r.enumerable});return t};var pE=(t,e,n)=>(n=t!=null?oE(cE(t)):{},fE(e||!t||!t.__esModule?uu(n,"default",{value:t,enumerable:!0}):n,t));var m=(t,e,n)=>lE(t,typeof e!="symbol"?e+"":e,n),cf=(t,e,n)=>e.has(t)||qm("Cannot "+n);var de=(t,e,n)=>(cf(t,e,"read from private field"),n?n.call(t):e.get(t)),He=(t,e,n)=>e.has(t)?qm("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),$e=(t,e,n,r)=>(cf(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Us=(t,e,n)=>(cf(t,e,"access private method"),n);var Ke,Qo,$f,Ou,Iu,js,St,Qy=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},Qo={TIMED:128,UNRELIABLE:64},$f=31,Ou={OK:0,REJECTED:1,ERROR:2},Iu={INPUT_REFLECTION:1,INPUT_OPTIONS:2},js={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 Tr=ht(()=>{"use strict";Qy()});function $g(t){Object.defineProperty(t,Symbol.metadata,{value:void 0,writable:!0,configurable:!0,enumerable:!1})}function Gg(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 Yg(t,e,n){t[n.offset++]=e&255}function Jk(t,e,n){t[n.offset++]=e&255}function Kg(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255}function tp(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255}function Or(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 Gs(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 Xg(t,e,n){let r=Math.floor(e/Math.pow(2,32)),s=e>>>0;Gs(t,s,n),Gs(t,r,n)}function Jg(t,e,n){let r=e/Math.pow(2,32)>>0,s=e>>>0;Gs(t,s,n),Gs(t,r,n)}function Zk(t,e,n){Wg[0]=BigInt.asIntN(64,e),Or(t,qs[0],n),Or(t,qs[1],n)}function Qk(t,e,n){Wg[0]=BigInt.asIntN(64,e),Or(t,qs[0],n),Or(t,qs[1],n)}function Zg(t,e,n){Yf[0]=e,Or(t,qs[0],n)}function Qg(t,e,n){Kk[0]=e,Or(t,qs[0],n),Or(t,qs[1],n)}function eA(t,e,n){t[n.offset++]=e?1:0}function tA(t,e,n){e||(e="");let r=qg(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,tp(t,r,n),s=3;else if(r<4294967296)t[n.offset++]=219,Gs(t,r,n),s=5;else throw new Error("String too long");return Gg(t,e,n),s+r}function Kf(t,e,n){if(isNaN(e))return Kf(t,0,n);if(isFinite(e)){if(e!==(e|0))return Math.abs(e)<=34028235e31&&(Yf[0]=e,Math.abs(Math.abs(Yf[0])-Math.abs(e))<1e-4)?(t[n.offset++]=202,Zg(t,e,n),5):(t[n.offset++]=203,Qg(t,e,n),9)}else return Kf(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,tp(t,e,n),3):e<4294967296?(t[n.offset++]=206,Gs(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,Yg(t,e,n),2):e>=-32768?(t[n.offset++]=209,Kg(t,e,n),3):e>=-2147483648?(t[n.offset++]=210,Or(t,e,n),5):(t[n.offset++]=211,Xg(t,e,n),9)}function eb(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 tb(t,e){return Ma(t,e)<<24>>24}function Ma(t,e){return t[e.offset++]}function nb(t,e){return Ju(t,e)<<16>>16}function Ju(t,e){return t[e.offset++]|t[e.offset++]<<8}function Fn(t,e){return t[e.offset++]|t[e.offset++]<<8|t[e.offset++]<<16|t[e.offset++]<<24}function ni(t,e){return Fn(t,e)>>>0}function rb(t,e){return Ys[0]=Fn(t,e),nA[0]}function sb(t,e){return Ys[0]=Fn(t,e),Ys[1]=Fn(t,e),rA[0]}function ob(t,e){let n=ni(t,e);return Fn(t,e)*Math.pow(2,32)+n}function ib(t,e){let n=ni(t,e);return ni(t,e)*Math.pow(2,32)+n}function iA(t,e){return Ys[0]=Fn(t,e),Ys[1]=Fn(t,e),oA[0]}function aA(t,e){return Ys[0]=Fn(t,e),Ys[1]=Fn(t,e),sA[0]}function cA(t,e){return Ma(t,e)>0}function uA(t,e){let n=t[e.offset++],r;return n<192?r=n&31:n===217?r=Ma(t,e):n===218?r=Ju(t,e):n===219&&(r=ni(t,e)),eb(t,e,r)}function lA(t,e){let n=t[e.offset++];if(n<128)return n;if(n===202)return rb(t,e);if(n===203)return sb(t,e);if(n===204)return Ma(t,e);if(n===205)return Ju(t,e);if(n===206)return ni(t,e);if(n===207)return ib(t,e);if(n===208)return tb(t,e);if(n===209)return nb(t,e);if(n===210)return Fn(t,e);if(n===211)return ob(t,e);if(n>223)return(255-n+1)*-1}function dA(t,e){let n=t[e.offset];return n<192&&n>160||n===217||n===218||n===219}function Dr(t,e){e.constructor&&(Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor[Symbol.metadata]==null&&$g(e.constructor),fA.set(e.constructor,t),np[t]=e),e.encode&&(Se[t]=e.encode),e.decode&&(Pe[t]=e.decode)}function ab(t){return np[t]}function Ir(){return{pendingByView:new Map,sentByView:new Map,broadcastPending:new Set,sentBroadcast:new Set,broadcastDeletes:new Set,maxPerTick:32}}function rp(t){return t._stream??(t._stream=Ir())}function Zu(t,e,n){e.activeViews.size===0&&rp(t).broadcastPending.add(n)}function Qu(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 pA(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 hA(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 mA(t){let e=t._stream;return e!==void 0&&(e.broadcastPending.size>0||e.broadcastDeletes.size>0)}function yA(t,e,n){let r=rp(t),s=r.pendingByView.get(e);s===void 0&&(s=new Set,r.pendingByView.set(e,s)),s.add(n)}function el(t,e){let n=t._stream;n!==void 0&&(n.pendingByView.delete(e),n.sentByView.delete(e),n.priorityByView?.delete(e))}function sp(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:gA[r],range:n-e,span:o?i:e===-n?i-2:i-1}}function Ks(t){return t!==null&&typeof t=="object"&&t.quantized!==void 0}function ub(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 lb(t,e){return t.min+e/t.span*t.range}function bA(t){let e=Se[t.wire];return(n,r,s)=>e(n,ub(t,r),s)}function wA(t,e,n){let r=Pe[t.wire];return lb(t,r(e,n))}function SA(t){let e=typeof Object.keys(t)[0]=="string"&&ab(Object.keys(t)[0]);return{complexTypeKlass:e,childType:e?Object.values(t)[0]:t}}function ri(t){if(Array.isArray(t))return{array:ri(t[0])};if(Ks(t))return typeof t.quantized.wire=="string"?t:{quantized:sp(t.quantized)};if(typeof t.type<"u")return t.type;if(xA(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=>np[n]!==void 0);if(e)return t[e]=ri(t[e]),t}return t}function xA(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 Nu(t,e,n){t[e]||Object.defineProperty(t,e,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[e].push(n)}function Hu(t){return t=t-(t>>>1&1431655765),t=(t&858993459)+(t>>>2&858993459),(t+(t>>>4)&252645135)*16843009>>>24}function Bu(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 RA(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[Mr];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 op(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?.[In]?.length??0)>0,o=RA(n),i=r&&!s?void 0:e[Js],a={encoder:e[ur],filter:i,metadata:n,isSchema:r,filterBitmask:r?Bu(n?.[In]):0,hasAnyFullStateOnly:(n?.[ti]?.length??0)>0,hasAnyUnreliable:(n?.[Ws]?.length??0)>0,hasAnyStream:(n?.[ln]?.length??0)>0,hasAnyView:s,fullStateOnlyBitmask:Bu(n?.[ti]),unreliableBitmask:Bu(n?.[Ws]),streamBitmask:Bu(n?.[ln]),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 EA(t,e,n){if(t.parentRef){if(t.parentRef[I]===e[I]){t._parentIndex=n;return}if(fb(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 kA(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 AA(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 PA(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 fb(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 TA(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 vA(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 MA(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 OA(t,e){ip(t,e,CA)}function ip(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[Vu],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 hb(t,e,n,r){IA(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 IA(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?.[ti]?.includes(n)?ei:0),a=r.flags&WA|i,c=t.flags;if(t.flags=c|a,a&~c&ei&&(t.reset(),t.unreliableRecorder?.reset()),!t.root?.types?.hasFilters)return;let d=o?.[In]?.includes(n)??!1,f=o?.[ln]?.includes(n)??!1,h=r.isFiltered||d||f;if(t.isFiltered=h,f&&!s){t.isStreamCollection=!0;let p=rp(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=mb(t);t.isVisibilitySharedWithParent=r.isFiltered&&p&&!f&&(!d||s&&o[n].tag!==sl)}}function ng(t){let e=t.pendingFilterRefresh;for(let n=0;n<e.length;n++){let r=e[n];(r.flags&Ea)!==0&&ap(r)}e.length=0}function mb(t){return t._isSchema||typeof t.refTarget[be]!="string"}function ap(t){t.flags&=~Ea;let e=t.root;if(e===void 0||t.parentRef===void 0)return;let n=mb(t),r=rg(t,t.parentRef,t._parentIndex,n);for(let o=t.extraParents;o!==void 0&&r!==DA;o=o.next)r|=rg(t,o.ref,o.index,n);if(r===0)return;t.isVisibilitySharedWithParent=(r&ju)!==0;let s=(r&$u)===0;s!==t.isFiltered&&(t.isFiltered=s,!s&&!t.isFullStateOnly&&(t.forEachLiveWithCtx(t,pb),t.has()&&e.enqueueChangeTree(t),t.unreliableRecorder?.has()&&e.enqueueUnreliable(t)),t.forEachChildWithCtx(t,NA))}function rg(t,e,n,r){let s=e[I];if(s.root!==t.root||!MA(t,s,n))return 0;s.flags&Ea&&ap(s);let o=yb;if(s._isSchema)s.encDescriptor.tags[n]!==void 0||s.isFieldStream(n)||(s.isFiltered?r&&(o|=ju):o|=$u);else if(!s.isFiltered)o|=$u;else if(r&&!s.isStreamCollection){let i=s.parent?.[I];(i?._isSchema?i.encDescriptor.tags[s.parentIndex]:void 0)!==sl&&(o|=ju)}return o}function BA(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?yA(i,f,e):a!==void 0&&p.markVisible(a)}}}function LA(t,e){t.root=e;let n=e.add(t);hb(t,t.parent,t.parentIndex),n&&Ca(t,e,VA)}function FA(t,e,n,r){if(t.addParent(e,r),!n)return;let s=n.add(t);n!==t.root&&(t.root=n,hb(t,e,r));let o=e?.[I];if(o!==void 0&&o.subscribedViews!==void 0&&e[be]!==void 0&&BA(o,r,t.ref,n),s){let i=sg[Lu];i===void 0&&(i={parentRef:void 0,root:void 0},sg[Lu]=i),i.parentRef=t.ref,i.root=n,Lu++,Ca(t,i,HA),Lu--}}function zA(t,e){Ca(t,e,UA)}function UA(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 VA(t,e,n){e.root!==t?e.setRoot(t):t.add(e)}function HA(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 $A(t,e,n){let r=(n&3)<<3;return n<4?t>>>r&255:e>>>r&255}function og(){return{next:void 0,tail:void 0,nextPosition:0}}function qA(t){return new Zf(t)}function oi(t,e=t){Object.defineProperty(t,I,{value:qA(e),enumerable:!1,writable:!0})}function tl(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 gb(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 XA(t,e){let n=t.resyncVisited;n.has(e)||n.set(e,new Set)}function JA(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}lp(t,t.state,new Set,e)}function lp(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)?lp(t,d,n,r):ZA(t,d,n,r))}}function ZA(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[si](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)&&lp(t,c,n,r)})}function dp(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[Ln](r),l=void 0}if(e!==N.DELETE)if(typeof o=="string")l=Pe[o](i,a);else if(Ks(o))l=wA(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=ab(Object.keys(o)[0]),f=Pe.number(i,a);t.resyncVisited!==null&&XA(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 rl(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 wb(t){return t!=null&&t[jg]===!0}function Ft(t){return(()=>new lr(t))}function Oa(t){if(wb(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 ag(t){return new lr({quantized:sp(t)})}function cP(t=sl){return function(e,n){let r=De.initialize(e.constructor);De.setTag(r,n,t)}}function uP(t,e){let n=De.initialize(t.constructor);De.setUnreliable(n,e)}function lP(t,e){let n=De.initialize(t.constructor);De.setPatchOnly(n,e)}function fP(t,e,n){let r=dP[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[cr](this[I],e,N.ADD)}else c!=null&&this[I].delete(e);a[e]=i}}}function pP(t,e,n){return function(r){let s=this[Mt],o=s[e];if(r!==o){if(r!=null){rl(r,n,this,t);let i=this[I],a=this.constructor;o!=null&&o[I]?(i.root?.remove(o[I]),a[cr](i,e,N.DELETE_AND_ADD)):a[cr](i,e,N.ADD),r[I]?.setParent(this,i.root,e)}else o!=null&&this[I].delete(e);s[e]=r}}}function hP(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[cr](u,e,N.DELETE_AND_ADD)):l[cr](u,e,N.ADD),i[I]?.setParent(this,u.root,e)}else c!=null&&this[I].delete(e);a[e]=i}}}function mP(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=lb(n,ub(n,r)),r===o)return;this.constructor[cr](this[I],e,N.ADD)}else{if(r===o)return;o!=null&&this[I].delete(e)}s[e]=r}}function yP(t,e,n,r){let s;return r?s=hP(t,e,n,r):typeof n=="string"?s=fP(t,e,n):Ks(n)?s=mP(t,e,n.quantized):s=pP(t,e,n),{get:function(){return this[Mt][e]},set:s,enumerable:!0,configurable:!0}}function gP(t=!0){return function(e,n){let r=De.initialize(e.constructor);De.setDeprecated(r,n),t&&(r[un]??(r[un]={}),r[un][n]={get:function(){throw new Error(`${n} is deprecated.`)},set:function(s){},enumerable:!1,configurable:!0},Object.defineProperty(e,n,r[un][n]))}}function bP(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 qu}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=bP(M.type);B&&(i[k]=B)}},u={},l=[],d=[],f={},h=[],p=[],y={},S=[];for(let k in t){let M=t[k];if(wb(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=ri(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]=ri(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)cP(u[k])(P.prototype,k);for(let k of l)uP(P.prototype,k);for(let k of d)lP(P.prototype,k);for(let k in f)gP(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 wP(t){return new Array(t).fill(0).map((e,n)=>n===t-1?"\u2514\u2500 ":" ").join("")}function SP(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 xP(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 ug(t){t.structSwitchEmitted||(t.shouldEmitSwitch&&(t.buffer[t.it.offset++]=255,Se.number(t.buffer,t.ref[Q],t.it)),t.structSwitchEmitted=!0)}function RP(t,e){xb(t,e,N.ADD)}function Sb(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|=cp),ip(e,t,RP)}Ca(e,t,EP)}function EP(t,e,n){Sb(t,e)}function xb(t,e,n){if(e<0){if(t.treeIsFiltered!==t.emitFiltered)return;ug(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)||(ug(t),t.encoder(t.self,t.buffer,t.changeTree,e,s,t.it,t.isEncodeAll,t.hasView,t.metadata)))}function Gf(t,e){let n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function Yu(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 kP(t,e){t.triggerChanges=e}var N,eg,Q,cr,ur,Nn,Js,st,Ln,si,I,be,lt,us,Bn,Uu,Mt,jg,un,xa,Mr,At,ls,In,vr,Ws,Ra,Vu,ti,ln,Du,Yk,Xu,qs,Yf,Kk,Wg,Xk,qg,Se,va,Ys,nA,rA,sA,oA,Pe,np,fA,cb,gA,or,Xs,tg,_A,De,db,Xf,Jf,pb,CA,yb,$u,ju,DA,NA,sg,Lu,jA,jf,Wf,Sa,qf,_a,ei,zu,Fu,Ea,cp,WA,ps,Zf,GA,YA,up,KA,bb,Dn,QA,nl,eP,ka,tP,ig,dg,fg,pg,hg,mg,yg,gg,cn,ds,Wu,bg,wg,Sg,xg,_g,ir,fs,Rg,Eg,kg,Ag,Pg,as,Aa,Tg,vg,Mg,Cg,Og,cs,Pa,Ig,Dg,Ng,Bg,Lg,Cr,qu,Fg,lr,nP,rP,sP,oP,iP,aP,Y,sl,dP,zg,Ug,Vg,Hg,On,Xe,cg,Qf,KB,_P,ar,Ta,Gu,lg,ep,zn,_b,Rb,Eb,Un,Ku,fp,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"));eg=(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=eg[t]||(eg[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"),cr="~track",ur="~encoder",Nn="~decoder",Js="~filter",st="~getByIndex",Ln="~deleteByIndex",si="~resyncPrune",I=Symbol.for("$changes"),be=Symbol.for("$childType"),lt=Symbol.for("$proxyTarget"),us="~onEncodeEnd",Bn="~reset",Uu="~onDecodeEnd",Mt=Symbol.for("$values"),jg="~builder",un="~descriptors",xa="~__encodeDescriptor",Mr="~encoders",At="~__numFields",ls="~__refTypeFieldIndexes",In="~__viewFieldIndexes",vr="$__fieldIndexesByViewTag",Ws="~__unreliableFieldIndexes",Ra="~__patchOnlyFieldIndexes",Vu="~__fullSyncSkipIndexes",ti="~__fullStateOnlyFieldIndexes",ln="~__streamFieldIndexes",Du="~__streamPriorities";try{Yk=new TextEncoder}catch{}Xu=new ArrayBuffer(8),qs=new Int32Array(Xu),Yf=new Float32Array(Xu),Kk=new Float64Array(Xu),Wg=new BigInt64Array(Xu),Xk=typeof Buffer<"u"&&Buffer.byteLength,qg=Xk?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:Yg,uint8:Jk,int16:Kg,uint16:tp,int32:Or,uint32:Gs,int64:Xg,uint64:Jg,bigint64:Zk,biguint64:Qk,float32:Zg,float64:Qg,boolean:eA,string:tA,number:Kf,utf8Write:Gg,utf8Length:qg},va=new ArrayBuffer(8),Ys=new Int32Array(va),nA=new Float32Array(va),rA=new Float64Array(va),sA=new BigUint64Array(va),oA=new BigInt64Array(va);Pe={utf8Read:eb,int8:tb,uint8:Ma,int16:nb,uint16:Ju,int32:Fn,uint32:ni,float32:rb,float64:sb,int64:ob,uint64:ib,bigint64:iA,biguint64:aA,boolean:cA,string:uA,number:lA,stringCheck:dA},np={},fA=new Map;cb="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.";gA={8:"uint8",16:"uint16",32:"uint32"};or=class or{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=or.inheritedTypes.get(n);r||(r=new Set,or.inheritedTypes.set(n,r)),r.add(e)}}static cache(e){let n=or.cachedContexts.get(e);return n||(n=new or(e),or.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;or.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[In]||r[ln])&&(this.hasFilters=!0);for(let s in r){let i=r[s].type;if(typeof i!="string"&&!Ks(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 ${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}
|
|
3
|
+
hasFilters: ${this.hasFilters}`}};m(or,"inheritedTypes",new WeakMap),m(or,"cachedContexts",new WeakMap);Xs=or,tg=63;_A=[ls,Ws,Ra,Vu,ti,ln,Mr];De={addField(t,e,n,r,s){if(e>=tg)throw new Error(`Can't define field '${n}'.
|
|
4
|
+
Schema instances may only have up to ${tg} fields.`);t[e]=Object.assign(t[e]||{},{type:ri(r),index:e,name:n}),Object.defineProperty(t,un,{value:t[un]||{},enumerable:!1,configurable:!0}),s?t[un][n]=s:t[un][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"&&!Ks(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(cb);t[e].stream=!0,t[ln]||Object.defineProperty(t,ln,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[ln].includes(e)||t[ln].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[In]||(Object.defineProperty(t,In,{value:[],enumerable:!1,configurable:!0}),Object.defineProperty(t,vr,{value:{},enumerable:!1,configurable:!0})),t[In].push(r),n<0)t[vr][n]||(t[vr][n]=[]),t[vr][n].push(r);else for(let o=n;o>0;o&=o-1){let i=o&-o;t[vr][i]||(t[vr][i]=[]),t[vr][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[Ws]||Object.defineProperty(t,Ws,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[Ws].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,Nu(t,Ra,n),Nu(t,Vu,n)},setDeprecated(t,e){let n=t[e];t[n].deprecated=!0,Nu(t,Vu,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,Nu(t,ti,n)},setStream(t,e){let n=t[e];t[n].stream=!0,t[ln]||Object.defineProperty(t,ln,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[ln].push(n)},setStreamPriority(t,e,n){let r=t[e];t[Du]||Object.defineProperty(t,Du,{value:{},enumerable:!1,configurable:!0,writable:!0}),t[Du][r]=n},getStreamPriority(t,e){return t?.[Du]?.[e]},defineField(t,e,n,r,s){let o=ri(s),{complexTypeKlass:i,childType:a}=SA(o);De.addField(e,n,r,o,yP(r,n,a,i)),e[un][r]&&Object.defineProperty(t.prototype,r,e[un][r]),(typeof o=="string"||Ks(o))&&(e[Mr]||Object.defineProperty(e,Mr,{value:[],enumerable:!1,configurable:!0,writable:!0}),e[Mr][n]=typeof o=="string"?Se[o]:bA(o.quantized))},setFields(t,e){let n=t.prototype.constructor;Xs.register(n);let r=Object.getPrototypeOf(n),s=r&&r[Symbol.metadata],o=De.initialize(n);n[cr]||(n[cr]=Xe[cr]),n[ur]||(n[ur]=Xe[ur]),n[Nn]||(n[Nn]=Xe[Nn]),n.prototype.toJSON||(n.prototype.toJSON=Xe.prototype.toJSON);let i=o[At]??(s&&s[At])??-1;i++,o[Mr]||Object.defineProperty(o,Mr,{value:s?.[Mr]?[...s[Mr]]:[],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[In]!==void 0&&(Object.defineProperty(r,In,{value:[...n[In]],enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(r,vr,{value:{...n[vr]},enumerable:!1,configurable:!0,writable:!0}));for(let s of _A){let o=n[s];o!==void 0&&Object.defineProperty(r,s,{value:[...o],enumerable:!1,configurable:!0,writable:!0})}Object.defineProperty(r,un,{value:{...n[un]},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?.[In]?.includes(e)},hasUnreliableAtIndex(t,e){return t?.[Ws]?.includes(e)},hasPatchOnlyAtIndex(t,e){return t?.[Ra]?.includes(e)},hasFullStateOnlyAtIndex(t,e){return t?.[ti]?.includes(e)},hasStreamAtIndex(t,e){return t?.[ln]?.includes(e)}},db=(t,e,n)=>t(e,n),Xf=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,db)}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 Hu(this.dirtyLow)+Hu(this.dirtyHigh)}has(){return(this.dirtyLow|this.dirtyHigh)!==0}reset(){this.dirtyLow=0,this.dirtyHigh=0,this.ops.fill(0)}},Jf=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,db)}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}};pb=(t,e)=>{t.isFieldUnreliable(e)?t.ensureUnreliableRecorder().record(e,N.ADD):t.record(e,N.ADD)},CA=(t,e)=>t(e);yb=1,$u=2,ju=4,DA=yb|$u|ju;NA=(t,e,n)=>{ap(e)};sg=[],Lu=0;jA=(t,e,n)=>t(e,n);jf=1,Wf=2,Sa=4,qf=8,_a=16,ei=32,zu=64,Fu=128,Ea=256,cp=512,WA=_a|ei,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=op(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&jf)!==0}set isFiltered(e){this.flags=e?this.flags|jf:this.flags&~jf}get isVisibilitySharedWithParent(){return(this.flags&Wf)!==0}set isVisibilitySharedWithParent(e){this.flags=e?this.flags|Wf:this.flags&~Wf}get isNew(){return(this.flags&Sa)!==0}set isNew(e){this.flags=e?this.flags|Sa:this.flags&~Sa}get isUnreliable(){return(this.flags&qf)!==0}set isUnreliable(e){this.flags=e?this.flags|qf:this.flags&~qf}get isPatchOnly(){return(this.flags&_a)!==0}set isPatchOnly(e){this.flags=e?this.flags|_a:this.flags&~_a}get isFullStateOnly(){return(this.flags&ei)!==0}set isFullStateOnly(e){this.flags=e?this.flags|ei:this.flags&~ei}get isStreamCollection(){return(this.flags&zu)!==0}set isStreamCollection(e){this.flags=e?this.flags|zu:this.flags&~zu}get needsRestage(){return(this.flags&Fu)!==0}set needsRestage(e){this.flags=e?this.flags|Fu:this.flags&~Fu}get hasFilteredFields(){return this.isFiltered||this.encDescriptor.hasAnyView}ensureUnreliableRecorder(){return this.unreliableRecorder===void 0&&(this.unreliableRecorder=this._isSchema?new Xf(this.metadata?.[At]??0):new Jf),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,jA)}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,$A(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?Hu(this.dirtyLow)+Hu(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&=~cp}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|Fu,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){LA(this,e)}setParent(e,n,r){FA(this,e,n,r)}forEachChild(e){zA(this,e)}forEachChildWithCtx(e,n){Ca(this,e,n)}forEachLive(e){OA(this,e)}forEachLiveWithCtx(e,n){ip(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){EA(this,e,n)}setParentIndex(e,n){kA(this,e,n)}removeParent(e=this.parent){return AA(this,e)}findParent(e){return PA(this,e)}hasParent(e){return fb(this,e)}indexInParent(e){return TA(this,e)}getAllParents(){return vA(this)}},Zf=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(){}};GA=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]];tl(t,e,c.types[r],l,s,o,c.encoders[r])},YA=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)}tl(t,e,i[be],i[st](r),s,o)},up=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;tl(t,e,i[be],i[st](r),s,o)},KA=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);tl(t,e,u,h,s,o)};bb=-1,Dn={Map:1,Array:2,Set:3,Collection:4,Stream:5};QA=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}),bb;let l=u.deprecated===!0,d=l?void 0:r[st](c),f=dp(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}))},nl=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===Dn.Map?(l=Pe.string(e,n),o.setIndex(a,l)):l=a:l=o.getIndex(a);let d=o[st](a),f=dp(t,i,r,a,d,c,e,n,s);if(t.resyncVisited!==null&&gb(t,r,i,l,d,f,s),f!=null)switch(u){case Dn.Map:o.$items.set(l,f);break;case Dn.Array:o.$setAt(a,f,t.resyncVisited!==null&&i===N.ADD?N.REPLACE:i);break;case Dn.Set:case Dn.Collection:case Dn.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})},eP=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[Ln](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=dp(t,i,r,a,l,c,e,n,s);t.resyncVisited!==null&&gb(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{};tP=(t,e)=>{let n=t.toString(),r=e.toString();return n<r?-1:n>r?1:0},ig={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]){rl(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)},cn=class cn{constructor(...e){m(this,gg);m(this,yg);m(this,mg);m(this,hg);m(this,"items",[]);m(this,"tmpItems",[]);m(this,"deletedIndexes",[]);m(this,"isMovingItems",!1);m(this,"_needsCompaction",!1);m(this,dg);this[be]=void 0,this[lt]=this;let n=new Proxy(this,ig);return Object.defineProperty(this,I,{value:new ps(n,this),enumerable:!1,writable:!0}),e.length>0&&this.push(...e),n}static[(gg=I,yg=Q,mg=lt,hg=be,pg=ur,fg=Nn,Js)](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 cn(...Array.from(e))}static initializeForDecoder(){let e=Object.create(cn.prototype);e.items=[],e.isMovingItems=!1,e._needsCompaction=!1,e[be]=void 0,e[lt]=e;let n=new Proxy(e,ig);return oi(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&&rl(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&(cp|zu))===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}[Bn](){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]?.[Bn]?.();e.items.length=0,e.tmpItems.length=0,e.deletedIndexes.length=0,n.recycle(),e[Q]=void 0}concat(...e){return new cn(...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 cn;return r.push(...this.items.slice(e,n)),r}sort(e=tP){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 cn}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 cn(...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}[(dg=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]}[Ln](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)}[Uu](){let e=this[lt]??this;e._needsCompaction&&(e._needsCompaction=!1,e.items=e.items.filter(n=>n!==void 0))}[si](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[Ln](a)}i&&s[Uu]()}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 cn,n.push(...this.items)):n=new cn(...this.map(r=>r[I]?r.clone():r)),n}};m(cn,pg,KA),m(cn,fg,eP),m(cn,"COLLECTION_KIND",Dn.Array);ds=cn;Dr("array",{constructor:ds});Wu=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}},ir=class ir{constructor(e){m(this,_g);m(this,xg);m(this,"childType");m(this,Sg);m(this,"$items",new Map);m(this,"journal",new Wu);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 ir)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=Ir())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Ir())).priority=e}get $indexes(){return this.journal.keyByIndex}get _collectionIndexes(){return this.journal.indexByKey}static[(_g=I,xg=Q,Sg=be,wg=ur,bg=Nn,Js)](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(ir.prototype);return e.$items=new Map,e.journal=new Wu,e[be]=void 0,oi(e),e}[Symbol.iterator](){return this.$items[Symbol.iterator]()}get[Symbol.toStringTag](){return this.$items[Symbol.toStringTag]}static get[Symbol.species](){return ir}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]&&rl(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&&Zu(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=Qu(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)}[Bn](){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?.[Bn]?.()),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}[Ln](e){let n=this.journal.keyOf(e);n!==void 0&&(this.$items.delete(n),this.journal.keyByIndex.delete(e))}[si](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){el(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 ir,this):(n=new ir,this.forEach((r,s)=>{r[I]?n.set(s,r.clone()):n.set(s,r)})),n}};m(ir,wg,YA),m(ir,bg,nl),m(ir,"COLLECTION_KIND",Dn.Map);fs=ir;Dr("map",{constructor:fs});as=class as{constructor(e){m(this,Pg);m(this,Ag);m(this,kg);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=Ir())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Ir())).priority=e}static[(Pg=I,Ag=Q,kg=be,Eg=ur,Rg=Nn,Js)](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,oi(e),e}add(e){let n=this.$refId++,r=this[I];return this.$items.set(n,e),r.isStreamCollection?r.root!==void 0&&Zu(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&&Qu(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)}[Bn](){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?.[Bn]?.()),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)}[Ln](e){this.$items.delete(e)}[si](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[Ln](s[o])}[us](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){el(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,Eg,up),m(as,Rg,nl),m(as,"COLLECTION_KIND",Dn.Collection);Aa=as;Dr("collection",{constructor:Aa});cs=class cs{constructor(e){m(this,Og);m(this,Cg);m(this,Mg);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=Ir())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Ir())).priority=e}static[(Og=I,Cg=Q,Mg=be,vg=ur,Tg=Nn,Js)](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,oi(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&&Zu(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&&Qu(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)}[Bn](){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?.[Bn]?.()),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)}[Ln](e){this.$items.delete(e)}[si](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[Ln](s[o])}[us](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){el(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,vg,up),m(cs,Tg,nl),m(cs,"COLLECTION_KIND",Dn.Set);Pa=cs;Dr("set",{constructor:Pa});Cr=class Cr{constructor(){m(this,Lg);m(this,Bg);m(this,Ng);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=Ir())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Ir())).priority=e}static[(Lg=I,Bg=Q,Ng=be,Dg=ur,Ig=Nn,Js)](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(Cr.prototype);return e.$items=new Map,e.$nextPosition=0,e._itemIndex=new Map,e[be]=void 0,oi(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&&Zu(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&&(Qu(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){pA(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)}[Ln](e){let n=this.$items.get(e);n!==void 0&&(this._itemIndex.delete(n),this.$items.delete(e))}[si](){}[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 Cr,this);let n=new Cr;return n.maxPerTick=this.maxPerTick,this.forEach(r=>{n.add(typeof r?.clone=="function"?r.clone():r)}),n}_dropView(e){el(this,e)}_unregister(){}};m(Cr,"$isStream",!0),m(Cr,Dg,up),m(Cr,Ig,nl),m(Cr,"COLLECTION_KIND",Dn.Stream);qu=Cr;Dr("stream",{constructor:qu});Fg=jg;lr=class{constructor(e){m(this,Fg,!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(cb);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}}};nP=(t=>new lr({array:Oa(t)})),rP=(t=>new lr({map:Oa(t)})),sP=(t=>new lr({set:Oa(t)})),oP=(t=>new lr({collection:Oa(t)})),iP=(t=>{let e=new lr({stream:Oa(t)});return e._stream=!0,e}),aP=(t=>new lr(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:aP,array:nP,map:rP,set:sP,collection:oP,stream:iP,quantized:ag,angle:t=>ag({min:0,max:Math.PI*2,mode:"wrap",bits:t?.bits??16})}),sl=-1;dP={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"};On=class On{constructor(e){m(this,Ug);m(this,zg);On.initialize(this),e&&On.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 oi(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[Bn]()}[(Hg=ur,Vg=Nn,Ug=Q,zg=Mt,Bn)](){let n=this.constructor[Symbol.metadata]?.[ls]??[],r=this[Mt];for(let s=0;s<n.length;s++)r[n[s]]?.[Bn]?.();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[cr](e,n,r=N.ADD){e.change(n,r)}static[Js](e,n,r){let o=e.constructor[Symbol.metadata][n]?.tag;return r===void 0?o===void 0:o===void 0?!0:o===sl?r.isChangeTreeVisible(e[I]):r.hasTagOnTree(e[I],o)}assign(e){return On.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(On.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(On.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(On.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);On.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]}[Ln](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=`${wP(r)}${o}${e.constructor.name} (refId: ${c})${l}${i}
|
|
5
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(On,Hg,GA),m(On,Vg,QA);Xe=On;$g(Xe);cg={value:0,enumerable:!1,writable:!0},Qf=class{constructor(e,n=0){m(this,"types");m(this,"nextUniqueId",0);m(this,"refCount",{});m(this,"changeTrees",{});m(this,"changes",og());m(this,"unreliableChanges",og());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&&(cg.value=this.nextUniqueId++,Object.defineProperty(n,Q,cg));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,pb)),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)}};KB=new FinalizationRegistry(({root:t,id:e,slot:n,bit:r})=>{xP(t,n,r),t.activeViews.delete(e);for(let s of t.streamTrees)s._dropView(e);t.releaseViewId(e)}),_P=-1;ar=class ar{constructor(e,n){m(this,"sharedBuffer",new Uint8Array(ar.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=Xs.cache(e.constructor),this.root=n??new Qf(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&&ng(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,xb)}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&&ng(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,Sb(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/ar.BUFFER_SIZE)*ar.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),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;})();
|
|
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),Gf(s.subarray(0,n),s.subarray(o,r.offset))}ensureCapacity(e,n){if(n+ar.BUFFER_SIZE<=e.byteLength)return e;let r=Math.ceil((n+ar.BUFFER_SIZE)/ar.BUFFER_SIZE)*ar.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===_P){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),Gf(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),Gf(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?mA(r):hA(r,e))return!0;return!1}get hasUnreliableChanges(){return this.root.unreliableChanges.next!==void 0}};m(ar,"BUFFER_SIZE",16*1024);Ta=ar,Gu=class extends Error{constructor(e){super(e),this.name="DecodingWarning"}},lg={value:0,enumerable:!1,writable:!0},ep=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?(lg.value=e,Object.defineProperty(n,Q,lg)):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 Gu("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 Gu(`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&&SP(this.callbacks[e][n],s)}},zn=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 Xs(e.constructor)}setState(e){this.state=e,this.root=new ep,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[Nn];for(this.currentRefId=0;n.offset<i;){if(e[n.offset]==255){n.offset++,r[Uu]?.();let u=Pe.number(e,n),l=o.refs.get(u);l?(r=l,a=r.constructor[Nn],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)===bb){console.warn("@colyseus/schema: definition mismatch"),this.skipCurrentStructure(e,n,i);continue}}return r[Uu]?.(),this.resyncVisited!==null&&JA(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])})}},_b=zt({min:Y.float64(),max:Y.float64(),bits:Y.uint8(),mode:Y.uint8()},"QuantizedDescriptor"),Rb=zt({name:Y.string(),type:Y.string(),referencedType:Y.number(),childPrimitive:Y.string(),quantized:Y.ref(_b).optional()},"ReflectionField"),Eb=zt({id:Y.number(),extendsId:Y.number(),fields:Y.array(Rb)},"ReflectionType"),Un=zt({types:Y.array(Eb),rootType:Y.number()},"Reflection");Un.encode=function(t,e={offset:0}){let n=t.context,r=new Un,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 Eb;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 Rb;R.name=x;let A;if(typeof b.type=="string")A=b.type;else if(Ks(b.type)){let E=b.type.quantized;A="quantized";let P=new _b;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)};Un.decode=function(t,e){let n=new Un;new zn(n).decode(t,e);let s=new Xs;n.types.forEach(a=>{let c=s.get(a.extendsId)??Xe,u=class extends c{};Xs.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:sp({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 zn(i,s)};Un.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};Ku=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}},fp={get(t){if(t instanceof zn)return new Ku(t);if("decoder"in t.serializer)return new Ku(t.serializer.decoder);throw new Error("Invalid room or decoder")},getLegacy(t){if(t instanceof zn)return Yu(t);if("decoder"in t.serializer)return Yu(t.serializer.decoder);throw new Error("Invalid room or decoder")},getRawChanges(t,e){return kP(t,e)}};Dr("map",{constructor:fs});Dr("array",{constructor:ds});Dr("set",{constructor:Pa});Dr("collection",{constructor:Aa})});function Ct(){return typeof performance<"u"?performance.now():Date.now()}var Ia=ht(()=>{"use strict"});function il(t,e){let n=globalThis,r=n.__colyseusDebug;if(!r){let s=[];r=n.__colyseusDebug={__buffer:s,publish(o,i){s.push([o,AP(i)]),s.length>PP&&s.shift()}}}r.publish(t,e)}function al(){if(typeof globalThis>"u")return!1;let t=globalThis.__colyseusDebug;return t!=null&&t.__buffer===void 0}var AP,PP,Da=ht(()=>{"use strict";AP=typeof WeakRef<"u"?t=>new WeakRef(t):t=>({deref:()=>t}),PP=64});function qt(t){return t[Q]}function dr(t){return t.constructor[TP]}function Na(t,e){let n=dr(t)?.[e];return typeof n=="number"?n:-1}function Ab(t){let e=dr(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=dr(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),vP[o.type]===void 0&&r.push(o.name))}return{fields:n,numeric:r}}function CP(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 Pb(t,e){let n=dr(t),r=n?.[e];switch((typeof r=="number"?n[r]:void 0)?.type){case"float32":return Math.fround;case"number":return CP;default:return MP}}function Tb(t){if(t.length>OP){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 TP,cl,vP,MP,OP,La=ht(()=>{"use strict";Pt();TP=Symbol.metadata??Symbol.for("Symbol.metadata"),cl=Mt;vP={string:!0,boolean:!0,bigint64:!0,biguint64:!0};MP=t=>t;OP=16});var hp,IP,DP,Gt,ii,mp=ht(()=>{"use strict";Pt();Tr();Ia();Da();La();hp=9,IP=hp,DP=(t,e)=>(e?2:1)*(hp+4+hp*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=dr(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;al()&&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?IP+(a?2:0):i?DP(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?Qo.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);ii=Gt});var ai,dt,ul,ll=ht(()=>{"use strict";Ia();ai=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);ul=dt});var e0=dE((eF,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 oT(t,e){return{now:()=>t?.serverNow()??performance.now(),ttlMs:typeof e=="function"?()=>e(t?.smoothedRtt()??0):e}}var rc,vl,Lp=ht(()=>{"use strict";rc=t=>Math.max(t*2,600),vl=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(oT(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 b0(){return{ema:0,peak:0}}function Fp(t,e){t.ema+=(e-t.ema)*.1,t.peak=Math.max(e,t.peak*.9)}function w0(t){t.ema=0,t.peak=0}function wi(t,e){let n=e!==void 0&&e>g0?e:g0;return t.ema>=n?"diverging":t.peak>=n?"jitter":"matched"}var g0,Ml=ht(()=>{"use strict";g0=.001});function sc(){return al()}function x0(){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 _0(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 R0(t,e,n,r){let s=Ct();if(s-S0<iT)return;S0=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 S0,iT,zp=ht(()=>{"use strict";Ia();Da();S0=-1/0,iT=1e3});function E0(){return Vp>0}var Up,Vp,Si,Cl=ht(()=>{"use strict";Ml();zp();Up=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),_0(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()}},Vp=0;Si=class{constructor(e){m(this,"lastCorrection",{});m(this,"lastCorrectionMag",0);m(this,"reconcileSeq",0);m(this,"drift",b0());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 Up);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,x0()),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,Fp(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,Vp++;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{Vp--}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||(Fp(this.drift,a),this.warnTolerance!==void 0&&wi(this.drift,this.warnTolerance)==="diverging"&&R0(e,this.lastCorrection,this.drift.ema,this.warnTolerance))),this.memos.prune(e),this.onReconcile?.(e)}get pendingCount(){return this.input_.pendingCount}reset(){this.reseedState(),w0(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 aT,Hp,xi,$p=ht(()=>{"use strict";Lp();Cl();aT=0,Hp=10,xi=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=vl.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(E0()){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:aT;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??Hp;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 ro,Ol=ht(()=>{"use strict";Lp();ro=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 k0,so,Il=ht(()=>{"use strict";Cl();La();zp();k0=t=>typeof t=="number"?t:typeof t=="boolean"?t?1:0:NaN,so=class extends Si{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(Pb(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]=k0(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])!==k0(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 oo,Dl=ht(()=>{"use strict";Cl();La();oo=class extends Si{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(dr(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 A0(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 P0=ht(()=>{"use strict"});function v0(t){return t===null||typeof t!="object"?!1:Array.isArray(t.fields)}function fT(){M0||(M0=!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,dn,En,Lr,Hn,oc,ic,_i,Ri,Ei,ac,It,cT,uT,T0,Kt,ki,io,ao,Ai,Pi,Ti,vi,gr,uc,Ll,Fl,zl,lT,Nl,jp,bs,Bl,dT,M0,Mi,co,Wp=ht(()=>{"use strict";Pt();$p();Ol();Il();Dl();mp();Ml();ll();Da();La();P0();mt=16,dn=0,En=1,Lr=2,Hn=3,oc=4,ic=5,_i=6,Ri=7,Ei=8,ac=9,It=ac+mt*2,cT=3,uT=1.5,T0=250,Kt=7,ki=0,io=1,ao=2,Ai=3,Pi=4,Ti=5,vi=6,gr=0,uc=0,Ll=1,Fl=2,zl=3,lT=4,Nl=5,jp={lerp:uc,extrapolate:Ll,damped:Fl,reckon:zl,raw:lT},bs={mode:"lerp",delay:100,smoothMs:50,maxExtrapolate:200,tickInterval:0,snap:0,angle:!1},Bl={step:void 0,smoothMs:50,substep:16,snap:0};dT=0,M0=!1;Mi=class Mi{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+Hn]|0)*Kt,i=this.renderTime,a=n[r+dn],c=n[r+Lr],u=i-c;n[r+Lr]=i;let l=n[r+En];if(u>0){let d=s[o+ao],f=d>0?1-Math.exp(-u/d):1;l+=(a-l)*f,n[r+En]=l}return l});m(this,"computeLerp",e=>{let n=this.computeLerpRaw(e),r=this.slotBuf,s=e*It,o=this.profileBuf[(r[s+Hn]|0)*Kt+vi],i=this.renderTime;if(o<=0)return r[s+En]=n,r[s+Ei]=n,r[s+Lr]=i,n;let a=r[s+Lr],c=i-a;if(c<=0)return r[s+En];let u=r[s+Ei],l=r[s+En],d=c/o,f=(n-u)/d,h=n-f+(l-u+f)*Math.exp(-d);return r[s+En]=h,r[s+Ei]=n,r[s+Lr]=i,h});m(this,"computeExtrapolate",e=>{let n=this.slotBuf,r=e*It,s=this.profileBuf,o=(n[r+Hn]|0)*Kt,i=this.renderTime,a=n[r+Ri]|0;if(a===0)return n[r+dn];let c=n[r+_i]|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+Ai],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+ao];if(b<=0)return n[r+En]=y,y;let x=i-S,R=n[r+En];if(x>0){let A=1-Math.exp(-x/b);R+=(y-R)*A,n[r+En]=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+dn]});m(this,"computeRaw",e=>this.slotBuf[e*It+dn]);m(this,"computeBound",e=>{let n=this.boundBySlot.get(e);return n!==void 0?n.ctrl.value(n.key):this.slotBuf[e*It+dn]});this.callbacks=fp.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)!==gr)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??Bl.smoothMs,substep:u.substep??Bl.substep,snap:u.snap??Bl.snap}}else this.reckonDefaults={...Bl};this.clock=r??e.clock??void 0,this.useRenderClock=s.renderPresent!==!1,this.clock===ai&&fT(),this.name=s.name??`predict#${++dT}`,il("predict",this.makeCoreHandle())}static get(e,n={}){return new Mi(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:wi(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=gr*Kt,r=e[n+ki]|0;return{mode:r===uc?"lerp":r===Ll?"extrapolate":r===Fl?"damped":r===zl?"reckon":"raw",delay:e[n+io],smoothMs:e[n+ao],lerpSmoothMs:e[n+vi],maxExtrapolate:e[n+Ai],tickInterval:e[n+Pi],snap:e[n+Ti]}}allocProfile(e,n,r,s,o,i,a,c,u){let l=typeof e=="number"?e:jp[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+ki]=l,this.profileBuf[p+io]=n,this.profileBuf[p+ao]=r,this.profileBuf[p+vi]=s,this.profileBuf[p+Ai]=o,this.profileBuf[p+Pi]=i,this.profileBuf[p+Ti]=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===Ll?this.computeExtrapolate:e===Fl?this.computeDamped:e===zl?this.computeReckon:e===Nl?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 gr;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?gr: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=gr*Kt,c=jp[n];this.profileBuf[a+ki]=c,this.profileComputers[gr]=this.computerForMode(c)}let r=e,s=gr*Kt,o=this.profileBuf;r.delay!==void 0&&(o[s+io]=r.delay),r.smoothMs!==void 0&&(o[s+ao]=r.smoothMs,o[s+vi]=r.smoothMs),r.maxExtrapolate!==void 0&&(o[s+Ai]=r.maxExtrapolate),r.tickInterval!==void 0&&(o[s+Pi]=r.tickInterval),r.snap!==void 0&&(o[s+Ti]=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+ki]|0;if(s===Nl)continue;let o=s===uc?"lerp":s===Ll?"extrapolate":s===Fl?"damped":s===zl?"reckon":"raw";e.push({id:n,isDefault:n===gr,label:this.profileLabels[n],mode:o,delay:this.profileBuf[r+io],smoothMs:this.profileBuf[r+(s===uc?vi:ao)],maxExtrapolate:this.profileBuf[r+Ai],tickInterval:this.profileBuf[r+Pi],snap:this.profileBuf[r+Ti]})}return e}setProfile(e,n){if(e<0||e>=this.profileCount)return;let r=e*Kt,s=this.profileBuf;if((s[r+ki]|0)!==Nl){if(n.mode!==void 0){let o=jp[n.mode];s[r+ki]=o,this.profileComputers[e]=this.computerForMode(o),e===gr&&(this.defaultMode=n.mode)}n.delay!==void 0&&(s[r+io]=n.delay),n.smoothMs!==void 0&&(s[r+ao]=n.smoothMs,s[r+vi]=n.smoothMs),n.maxExtrapolate!==void 0&&(s[r+Ai]=n.maxExtrapolate),n.tickInterval!==void 0&&(s[r+Pi]=n.tickInterval),n.snap!==void 0&&(s[r+Ti]=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+dn]=a,d[f+En]=a,d[f+Lr]=performance.now(),d[f+Ei]=a,d[f+Hn]=r,d[f+oc]=o,d[f+ic]=i,d[f+_i]=0,d[f+Ri]=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+dn];p=j+Math.atan2(Math.sin(p-j),Math.cos(p-j))}let x=(S[b+Hn]|0)*Kt,R=this.profileBuf[x+Pi],A=S[b+_i]|0,E=S[b+Ri]|0,P=this.profileBuf[x+Ti];P>0&&E>0&&Math.abs(p-S[b+dn])>P&&(A=0,E=0,S[b+En]=p,S[b+Ei]=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+dn]=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?uT*v:cT*se;if($>0&&M-k>G){let W=$<T0?$:T0,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+_i]=A+1>=mt?0:A+1,E<mt&&(S[b+Ri]=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+dn]=S,p[y+En]=S,p[y+Lr]=0,p[y+Ei]=S,p[y+Hn]=o,p[y+oc]=i,p[y+ic]=Na(n,l),p[y+_i]=0,p[y+Ri]=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(Nl,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[cl],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[cl];h=(S,b,x,R)=>{let A=S[cl];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=Ab(e),y=n.snapshot??(p.length>0?Tb(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=dr(n),s=n.constructor?.name||"?",o=e.config;if(!v0(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(v0(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>Mi.MAX_STEPS_PER_FRAME?(this.stepAcc=0,n=Mi.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 xi(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(A0(this.callbacks,s,n,()=>this.sessionSource.sessionId))}return this.driven.push(s),s}spawns(e,n={}){let r=new ro(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[gr*Kt+io]}bindInputRenderDelay(e){e instanceof ii&&e.bindRenderDelay(()=>this.canonicalDelay())}reconciler(e,n){let r=new so(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 oo({...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+Hn]|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+Hn]|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+dn]}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+Hn]|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+Hn]|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+dn]}return o}computeLerpRaw(e){let n=this.slotBuf,r=e*It,s=this.profileBuf,o=(n[r+Hn]|0)*Kt,i=this.renderTime,a=n[r+Ri]|0;if(a===0)return n[r+dn];let c=n[r+_i]|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+io],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(Mi,"MAX_STEPS_PER_FRAME",5);co=Mi});var ew={};af(ew,{DEFAULT_GRACE_TICKS:()=>Hp,Predict:()=>co,PredictedEventChannel:()=>xi,PredictedSpawns:()=>ro,Reconciler:()=>so,SimReconciler:()=>oo,classifyDrift:()=>wi});var Qp=ht(()=>{"use strict";Wp();Il();Ml();Dl();$p();Ol()});var la="genex-native";var lu="genex_native";var du="genex_protocol",fu="genex_attempt",pu="genex_nonce",uf="genex_caps";var Vo="genex_";var lf="genex_r";var df="entryRef",ff="genex_hash",pf="genex_referrer",hf="genex_ref";var hu="__genexNative";var hE=/^[0-9a-f]{32}$/,mE=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function Ar(t){return typeof t=="string"&&hE.test(t)}function mf(t){return typeof t=="string"&&mE.test(t)}var Ho="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",yE=(()=>{let t=new Array(128).fill(-1);for(let e=0;e<Ho.length;e++)t[Ho.charCodeAt(e)]=e;return t})();function Gm(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 gE(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 yf(t){return Gm(t).length}function gf(t){let e=Gm(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+=Ho[s>>2],n+=Ho[(s&3)<<4|(o??0)>>4],o===void 0||(n+=Ho[(o&15)<<2|(i??0)>>6],i===void 0))break;n+=Ho[i&63]}return n}function bf(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?yE[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=gE(e);if(s!==null)try{return JSON.parse(s)}catch{return}}var Ym=2048,Km=32;var wE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;function SE(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function mu(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 yu=["channel","v","type","slug","attemptId","nonce"];function xE(t){return t.channel===la&&t.v===1&&mf(t.slug)&&Ar(t.attemptId)&&Ar(t.nonce)}function wf(t){if(!(!SE(t)||!xE(t)))switch(t.type){case"ticket":return!mu(t,[...yu,"ticket","expiresAt"])||typeof t.ticket!="string"||t.ticket.length===0||t.ticket.length>Ym||typeof t.expiresAt!="string"||t.expiresAt.length>Km||!wE.test(t.expiresAt)?void 0:t;case"guest":case"cancel":return mu(t,yu)?t:void 0;case"foreground":return!mu(t,[...yu,"active"])||typeof t.active!="boolean"?void 0:t;case"network":return!mu(t,[...yu,"online"])||typeof t.online!="boolean"?void 0:t;default:return}}function RE(t,e){if(typeof t!="string"||t.length===0)return{ok:!1,reason:"undecodable"};if(yf(t)>4096)return{ok:!1,reason:"too-large"};let n=bf(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 xf(t){return RE(t,wf)}function _f(t){let e=gf(t);if(!(e.length>4096))return e}function gu(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 bu(t){return gu(t,lu)==="1"}function Ef(t){if(!bu(t))return null;let e=gu(t,fu),n=gu(t,pu),r=Number(gu(t,du));return!Ar(e)||!Ar(n)||r!==1?null:{attemptId:e,nonce:n,protocol:r}}function ey(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 ty(t){let e=t.indexOf("="),n=e===-1?t:t.slice(0,e);return ey(n.indexOf("+")===-1?n:n.split("+").join(" "))}function wu(t){return ny(t,[lf])}var kE=[lu,du,fu,pu,uf];function kf(t){return ny(t,kE)}function ny(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(ty(i)));if(s.length===r.length)return`?${n}`;let o=s.join("&");return o.length===0?"":`?${o}`}var AE=/^[!$-&(-;=?-~]+$/;function Su(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||!AE.test(n))return"";let o=n.split("&").filter(i=>{if(i.length===0)return!1;let a=ty(i);return!a.startsWith(Vo)&&!e.includes(a)}).join("&");return o.length>1024?"":o}var PE=/^#[!#-;=?-_a-~]+$/;function xu(t){return typeof t!="string"||t.length<2||t.length>4096||!PE.test(t)||ey(t).includes(Vo)?"":t}var TE=/^[a-z0-9._-]+$/,vE=/^\[[0-9a-f:.]+\]$/;function ME(t){return TE.test(t)&&/[a-z0-9]/.test(t)||vE.test(t)}function Rf(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)),!ME(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 jo(t,e){if(typeof t!="string"||t.length===0)return null;let n=Rf(t);return n===null||n.length>255||typeof e=="string"&&Rf(e)===n?null:n}var ry=["open","save","fullscreen"];var sy=50*1024*1024,CE=16;function oy(t){return typeof t=="string"&&ry.includes(t)}function Af(t){if(!Array.isArray(t))return[];let e=[],n=Math.min(t.length,CE);for(let r=0;r<n;r++){let s=t[r];oy(s)&&!e.includes(s)&&e.push(s)}return e}var $E=null;function ay(t){$E=t}var WE=null;function cy(t){WE=t}var qE=null;function uy(t){qE=t}var ha=1,Cf="genex:embed:retry",Ry="genex:guest:popover-dismissed",Ey="genex:embed:local-auth",ky="genex:embed:entry-referrer",GE="none",ly="genex:player",YE="0.35.0",Be=null,Ue="pending",on=null,os=!1,rs=null,Wo=!1,ss,qo,Ay=0,jt,Py,Of,Ty,vy=!1,is=null,My=[],Yo=!1,Hs=!1,fa=!1,sn=0,Ko=1e4,KE=2e3,XE=10*6e4,JE=6e4,dy=500,ZE=3e4,QE=3e4,Ye,Mn,Go,fy=!1,py,_u=null,hy=new Set;var my=!1,ek=new Map,Cy=[],ma=[],pa=null,Ru=null,Vs,Pf,Tf=!1,Eu=new Map;function et(){return globalThis.window}function If(){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 tk(){try{return et()?.sessionStorage?.getItem(Cf)==="1"}catch{return!1}}function nk(){try{et()?.sessionStorage?.setItem(Cf,"1")}catch{}}function Df(){try{et()?.sessionStorage?.removeItem(Cf)}catch{}}function rk(){try{return et()?.sessionStorage?.getItem(Ey)==="1"}catch{return!1}}function sk(){try{et()?.sessionStorage?.setItem(Ey,"1")}catch{}}function ok(){try{let t=et()?.sessionStorage?.getItem(ky);return t==null?void 0:jo(t)}catch{return}}function ik(t){try{et()?.sessionStorage?.setItem(ky,t??GE)}catch{}}function ak(){try{return et()?.sessionStorage?.getItem(Ry)==="1"}catch{return!1}}function ck(){try{et()?.sessionStorage?.setItem(Ry,"1")}catch{}}function uk(){try{let t=et()?.localStorage;if(!t)return"no-storage";let e=t.getItem(ly);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(ly,e)),e}catch{return"no-storage"}}function Au(t){let e=et();if(!e||Yo)return;if(Yo=!0,Go!==void 0&&(clearTimeout(Go),Go=void 0),Be={slug:t.slug,apiUrl:t.apiUrl.replace(/\/$/,""),dashboardOrigins:[...t.dashboardOrigins]},Ue="pending",Fy(e),cy({apiUrl:Be.apiUrl,dashboardOrigins:Be.dashboardOrigins,getToken:()=>jt,getParentOrigin:()=>is,isEmbedded:Wt,isNative:xn,isLocalTest:()=>os}),uy({apiUrl:Be.apiUrl,dashboardOrigins:Be.dashboardOrigins,getToken:()=>jt,getParentOrigin:()=>is,isEmbedded:Wt,isNative:xn,isLocalTest:()=>os}),Uf(e)){Bk(e);return}vu("connecting");let n=zy(e);if(n){Ek(e,n);return}Wt()?_k(e):Pk(e)}function Wt(){let t=et();if(!t)return!1;try{return t.self!==t.top}catch{return!0}}function lk(){let t=et();return t?Wt()?"page":xn()||Bf(t)?"app":Yo?os?"local":"standalone":Uf(t,!1)?"local":"standalone":"standalone"}function Pu(){return vy?{embedToken:Ck}:jt?{embedToken:jt}:void 0}function Oy(){return Py??[]}function Iy(){return Gy(Of)??[]}function Dy(){return Dk(Ty)}function Nf(){return(Ue==="authenticated"||Ue==="guest")&&on?Promise.resolve({user:on,guest:Ue==="guest"}):Ue==="blocked"?Promise.reject(new Error("genex embed auth: blocked")):(dk("waitForPlayer"),new Promise((t,e)=>{ma.push({resolve:t,reject:e})}))}function dk(t){if(!Yo){if(!fy){fy=!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{}}Go===void 0&&(Go=setTimeout(()=>{Go=void 0,Yo||Pr("no-identity")},Ko))}}var fk=32*1024;async function Ny(){if(!Be)throw new Error("genex embed: call initEmbed() first");if(Ue==="pending"&&await Nf(),Ue==="blocked")throw new Error("genex embed auth: blocked")}function By(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<=fk?!0:void 0})}async function pk(t){return t.status!==403?!1:(await t.json().catch(()=>null))?.error==="staging_no_save"}async function hk(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 pk(t)?{saved:!1,staging:!0}:(an("error",{error:new Error(`genex state save failed (${t.status})`)}),{saved:!1})}async function mk(t,e){return await Ny(),Ue==="guest"?(Pf=t,Tf=!0,{saved:!1,guest:!0,queued:!0}):hk(await By("/state/me",{method:"PUT",body:JSON.stringify(t),ifVersion:e?.ifVersion}))}async function yk(t,e){let n=e?.board??"main",r=e?.mode??"max";if(await Ny(),Ue==="guest"){let i=Eu.get(n);return(!i||(r==="min"?t<i.score:t>i.score))&&Eu.set(n,{score:t,mode:r}),{submitted:!1,guest:!0,queued:!0}}let s=await By("/scores",{method:"POST",body:JSON.stringify({score:t,board:n,mode:r})});if(!s.ok)return an("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 gk(){try{if(Tf){let e=Pf;Pf=void 0,Tf=!1,await mk(e)}let t=[...Eu.entries()];Eu.clear();for(let[e,{score:n,mode:r}]of t)await yk(n,{board:e,mode:r})}catch(t){an("error",{error:t})}}function an(t,e){let n=ek.get(t);if(n)for(let r of[...n])try{r(e)}catch{}}var bk=["embed"];function Ly(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:xu(r.get(ff)),entryReferrer:jo(r.get(pf),e)}}catch{return n}}function wk(t,e){try{return new URLSearchParams(t).get(e)}catch{return null}}function Fy(t){if(_u)return _u;let e="",n="",r=null;try{e=t.location.search??"",n=ku??t.location.hash??"",r=t.location.origin??null}catch{}let s=Wt(),o=Ly(n,r),i=!s&&(!!o.ticket||o.guest),a=Su(e,bk);return _u={search:a?`?${a}`:"",hash:i?o.entryHash:n.includes(Vo)?"":n,referrer:Sk(e,s,i,o.entryReferrer,r)},_u}function Sk(t,e,n,r,s){let o=ok();if(o!==void 0)return o;let i;return e?i=jo(wk(t,hf),s):n?i=r:i=jo(If()?.referrer,s),ik(i),i}function xk(){if(!(my||hy.size===0)){my=!0;for(let t of[...hy])try{t()}catch{}}}function _k(t){py=e=>{Rk(e)},t.addEventListener("message",py),t.parent.postMessage({type:"genex:embed:ready",v:ha},"*"),Ye=setTimeout(()=>{Xo()},Ko)}function yy(){return(Ue==="pending"||Ue==="guest")&&!Hs}async function Rk(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&&(!yy()||typeof e.ticket!="string"||!e.ticket))&&!(r&&(Ue!=="pending"||Hs||fa))){if(!Be.dashboardOrigins.includes(t.origin)){let s=await vf();if(n&&!yy()||r&&(Ue!=="pending"||Hs||fa)||!s.includes(t.origin))return}if(Ye!==void 0&&clearTimeout(Ye),is=t.origin,My=Af(e.caps),r){await Xo();return}await zf(e.ticket)}}function Bf(t){let e=t.ReactNativeWebView;return!e||typeof e!="object"?null:typeof e.postMessage=="function"?e:null}function zy(t){if(Wt())return null;let e;try{e=t.location.search??""}catch{return null}return!bu(e)||!Bf(t)?null:Ef(e)}function xn(){return rs!==null}function $s(t){let e=et();if(!e||!Be||!rs)return;let n=Bf(e);if(!n)return;let r=_f({channel:la,v:1,slug:Be.slug,attemptId:rs.attemptId,nonce:rs.nonce,...t});if(r)try{n.postMessage(r)}catch{}}function Uy(t){xn()&&$s({type:"error",code:t})}function Ek(t,e){rs=e,Ay=Date.now(),t[hu]=r=>{kk(r)},$s({type:"ready",sdkVersion:YE,capabilities:["native-ticket","native-guest","heartbeat"]}),Ye=setTimeout(()=>{Xo()},Ko)}async function kk(t){if(!Be||!rs)return;let e=xf(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 zf(n.ticket);return;case"guest":Ye!==void 0&&clearTimeout(Ye),await Xo();return;case"cancel":Vy(),xk();return;case"foreground":case"network":return}}function Vy(){Ye!==void 0&&clearTimeout(Ye),Ye=void 0,Mn!==void 0&&clearTimeout(Mn),Mn=void 0,ss!==void 0&&clearTimeout(ss),ss=void 0,qo!==void 0&&clearInterval(qo),qo=void 0}function Hy(){!xn()||qo!==void 0||(qo=setInterval(()=>{$s({type:"heartbeat",uptimeMs:Math.max(0,Date.now()-Ay)})},QE),qo.unref?.())}function Ak(){!xn()||Wo||(Wo=!0,$s({type:"reauth-required"}),ss=setTimeout(()=>{ss=void 0,Wo&&(Wo=!1,an("error",{error:new Error("embed session expired")}),Pr("session-expired"))},ZE))}function Lf(){Wo=!1,ss!==void 0&&clearTimeout(ss),ss=void 0}function Ff(t,e){let n=et();if(!(!n||!Wt()))try{n.parent.postMessage(t,e)}catch{}}async function Pk(t){let e=$y(t);if(e.ticket){gy(),await zf(e.ticket);return}if(e.guest){gy(),await Xo();return}vu("redirecting"),await Tu(t,{guestOk:!0})}function gy(){Ye!==void 0&&clearTimeout(Ye),Ye=setTimeout(()=>{Ye=void 0,Ue==="pending"&&Pr("no-identity")},Ko+KE)}var ku=null;function Tk(t){return t.location.pathname+wu(t.location.search)}function $y(t){let e=ku??t.location.hash;ku=null;let{ticket:n,guest:r,entryHash:s}=Ly(e);if(n||r)try{t.history.replaceState(t.history.state??null,"",Tk(t)+s)}catch{}return{ticket:n,guest:r}}async function Tu(t,e){if(!Be||os||xn())return;let n=e?.guestOk?Be.dashboardOrigins[0]??(await vf())[0]:(await vf())[0]??Be.dashboardOrigins[0];if(!n){Pr();return}let r=t.location.origin+t.location.pathname,s=kf(wu(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=Fy(t).referrer;a&&(i+=`&${df}=${encodeURIComponent(a)}`),i+=xu(t.location.hash),t.location.replace(i)}async function vf(){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 zf(t){if(!Be||os||Hs||Ue!=="pending"&&Ue!=="guest"&&!(Wo&&Ue==="authenticated"))return;let n=Ue==="guest",r=++sn;Hs=!0;try{let s=await ya(`${Be.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ticket:t})},Ko);if(r!==sn)return;if(!s.ok){an("error",{error:new Error(`ticket redemption failed (${s.status})`)}),n||await by();return}let o=await s.json();if(r!==sn)return;jt=o.embedToken,on=o.user,qy(o.colyseus),Ue="authenticated",Ye!==void 0&&clearTimeout(Ye),Ye=void 0,Df(),Mu(),Hf(),Vf(),Wt()&&is&&Ff({type:"genex:embed:authenticated",v:ha},is),xn()&&(Lf(),$s({type:"authenticated",guest:!1}),Hy()),n&&await gk();let i={user:on};for(let a of Cy.splice(0))a.resolve(i);for(let a of ma.splice(0))a.resolve({user:on,guest:!1});an("authenticated",i)}catch(s){if(r!==sn)return;an("error",{error:s}),n||await by()}finally{Hs=!1}}async function Xo(){if(!Be||os||fa||Hs||Ue!=="pending"&&Ue!=="guest")return;let t=++sn;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:uk()})},Ko);if(t!==sn)return;if(!e.ok){an("error",{error:new Error(`guest session failed (${e.status})`)}),Uy("guest-failed"),Pr(e.status===404?"not-available":"no-identity");return}let n=await e.json();if(t!==sn)return;jt=n.embedToken,on=n.user,qy(n.colyseus),vk()}catch(e){if(t!==sn)return;an("error",{error:e}),Pr()}finally{fa=!1}}function vk(){let t=Ue!=="guest";if(Ue="guest",Ye!==void 0&&clearTimeout(Ye),Mu(),Vf(),Wt()?Ff({type:"genex:embed:authenticated",v:ha,guest:!0},is??"*"):xn()?($s({type:"authenticated",guest:!0}),Hy()):t&&!ak()&&$k(),on){let e={user:on};for(let n of ma.splice(0))n.resolve({user:on,guest:!0});an("guest",e)}}function jy(t){try{let e=new URL(t.location.origin);return e.protocol==="http:"&&Wy.has(e.hostname)}catch{return!1}}var Wy=new Set(["localhost","127.0.0.1","[::1]"]),Mk="genex_authority_url",Ck="local:test",Ok=64;function Ik(t){if(!t||t.length>Ok)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:"||!Wy.has(e.hostname)||!n?null:`ws://${e.host}`}function qy(t){Py=t?.urls,Of=t?.authorityUrls,Ty=t?.authorityRegions}function Gy(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string"&&e.length>0)}function Dk(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=Gy(s)??[];typeof r=="string"&&r.length>0&&o.length>0&&e.push({region:r,urls:o})}return e}function Uf(t,e=!0){if(Wt()||zy(t)||!jy(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&&sk(),!1):rk()?!1:!Nk(t)}function Nk(t){let e=ku??t.location.hash;return!!e&&e.includes("genex_")}function Bk(t){os=!0,$y(t),Lk(t);let e={id:"local:test",name:"Local Tester"};on=e,Ue="guest",Mu();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});an("guest",{user:e})}function Lk(t){if(!jy(t))return;let e=null;try{e=new URLSearchParams(t.location.search).get(Mk)}catch{return}let n=Ik(e);n&&(Of=[n],vy=!0)}async function by(){let t=et();if(Ye!==void 0&&clearTimeout(Ye),Ye=void 0,xn()){Lf(),Uy("ticket-rejected"),Pr();return}if(t&&!Wt()&&!tk()){nk(),vu("redirecting"),await Tu(t,{guestOk:!0});return}Pr()}function Vf(){Mn!==void 0&&clearTimeout(Mn),Mn=setTimeout(()=>{Yy()},XE)}async function Yy(){if(!Be||Ue!=="authenticated"&&Ue!=="guest"||!jt)return;let t=sn,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!==sn||jt!==e)return;if(r.ok){let s=await r.json();if(t!==sn||jt!==e)return;jt=s.embedToken,Vf();return}}catch{n=void 0}if(!(t!==sn||jt!==e)){if(n===401){if(Ue==="guest"){Xo();return}if(xn()){Ak();return}an("error",{error:new Error("embed session expired")}),Pr("session-expired");return}Mn!==void 0&&clearTimeout(Mn),Mn=setTimeout(()=>{Yy()},JE)}}function Pr(t="no-identity"){if(Ue==="blocked")return;sn++,Ue="blocked",on=null,jt=void 0,Ye!==void 0&&clearTimeout(Ye),Mn!==void 0&&clearTimeout(Mn),Hf(),xn()?(Vy(),Lf(),Mu(),$s({type:"blocked",reason:t})):vu(Wt()?"blocked-embedded":"blocked-standalone"),Wt()&&Ff({type:"genex:embed:blocked",v:ha},is??"*");let e=new Error("genex embed auth: blocked");for(let n of Cy.splice(0))n.reject(e);for(let n of ma.splice(0))n.reject(e);an("blocked")}var Fk={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}},zk="https://cdn.genex.technology/fonts/GeistMono-variable.woff2",Ky="'Geist Mono',ui-monospace,SFMono-Regular,Menlo,monospace",wy=!1,Sy="!<>-_/[]{}=+*^?#$%&@",Xy=50,xy=10,_y=[{name:"churn",ticks:5},{name:"settle",ticks:10},{name:"hold",ticks:12},{name:"dissolve",ticks:8}];function Mf(t){let e="";for(let n=0;n<t;n++)e+=Sy[Math.floor(Math.random()*Sy.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 Uk(t,e){if(Jy())return t.textContent=e,()=>{};let n=0;t.textContent=Mf(e.length);let r=setInterval(()=>{if(n++,n>=xy){t.textContent=e,clearInterval(r);return}let s=Math.floor(n/xy*e.length);t.textContent=e.slice(0,s)+Mf(e.length-s)},Xy);return()=>clearInterval(r)}function Vk(t,e){if(Jy())return t.textContent=e,()=>{};let n=0,r=0,s=()=>{let i=_y[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)+Mf(e.length-a),r++,r>=i.ticks&&(r=0,n=(n+1)%_y.length)};s();let o=setInterval(s,Xy);return()=>clearInterval(o)}function Zy(t){if(!wy){wy=!0;try{let e=et()?.FontFace,n=t.fonts;if(!e||!n?.add)return;new e("Geist Mono",`url(${zk}) format('woff2')`,{weight:"100 900",display:"swap"}).load().then(s=>n.add(s)).catch(()=>{})}catch{}}}function vu(t){let e=If();if(e?.createElement)try{pa||(pa=Hk(e)),pa.setContent(t)}catch{}}function Mu(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 Hk(t){Zy(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:${Ky};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,Df(),Tu(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=Fk[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?Vk(n,u.title):Uk(n,u.title)};u.instant||dy<=0?l():(n.style.opacity="0",o=setTimeout(()=>{o=void 0,l()},dy)),r.style.display=u.button?"inline-block":"none",u.button&&(r.textContent=u.button),s()}}}function $k(){let t=If();if(!(!t?.createElement||Ru))try{Ru=jk(t)}catch{}}function Hf(){Vs!==void 0&&(clearTimeout(Vs),Vs=void 0);try{Ru?.root?.remove?.()}catch{}Ru=null}function jk(t){Zy(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:${Ky};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&&on?.name?`Playing as ${on.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,Df(),Tu(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",()=>{ck(),Hf()}),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"};Vs=setTimeout(()=>u(!0),5e3),r.addEventListener("pointerdown",()=>{Vs!==void 0&&clearTimeout(Vs),Vs=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}}ay({getShell:lk,isLocalTest:()=>{let t=et();return!t||Wt()?!1:Yo?os:Uf(t,!1)},getConfig:()=>Be,getParentOrigin:()=>is,getShellCaps:()=>My});var sh={};af(sh,{chatSend:()=>wv,claim:()=>Sv,claimAsHost:()=>xv,connect:()=>cv,destroy:()=>Rv,dispose:()=>uv,drainEventsJson:()=>Iv,leave:()=>yw,listen:()=>yv,objectsJson:()=>Cv,open:()=>av,playersJson:()=>Mv,release:()=>_v,reportEliminated:()=>Ev,reportFinish:()=>Av,reportScore:()=>kv,send:()=>mv,sendInput:()=>gv,serverNow:()=>Pv,sessionJson:()=>vv,setIdentity:()=>rv,setMe:()=>lv,setObject:()=>pv,setRoomOpen:()=>bv,setShared:()=>fv,sharedJson:()=>Ov,snapMe:()=>dv,snapObject:()=>hv,timeUntil:()=>Tv,version:()=>nv});var ga={ready(t){let e=globalThis.__GENEX__;return t&&e&&typeof e.apiUrl=="string"&&Array.isArray(e.dashboardOrigins)&&Au({slug:t,apiUrl:e.apiUrl,dashboardOrigins:e.dashboardOrigins.filter(n=>typeof n=="string")}),Nf()},auth:()=>Pu(),urls:()=>Oy()},Wk=4096;function ye(t,e){t.q.length>=Wk&&(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 Jo=t=>({type:"warning",message:`genex bridge: ${t}`});function qk(t){try{return JSON.stringify(t)}catch(e){let n=typeof t.kind=="string"?t.kind:t.type;return JSON.stringify(Jo(`event ${JSON.stringify(n)} dropped: JSON cannot carry it (${nr(e)})`))}}function Cu(t){return t.overflowed=!1,`[${t.q.splice(0).map(qk).join(",")}]`}var Cn=t=>!!t&&typeof t=="object"&&!Array.isArray(t),Zo=t=>{let e=Cn(t)||t instanceof Error?t.code:void 0;return typeof e=="number"&&Number.isFinite(e)?e:0},nr=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 rr(t,e){let n=ba(t,e);if(!Cn(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{});Tr();var sr=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)}};Tr();Pt();Pt();Pt();Pt();Pt();Pt();Pt();Pt();var kb=256,pp=5,Zs=class Zs{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=op(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(kb);this._outBuffer=new Uint8Array((kb+pp)*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]=Zs._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=pp;for(let i=0;i<this._slotCount;i++)n+=this._slotLens[i]+pp;let r=this._outBuffer;n>r.byteLength&&(r=this._outBuffer=Zs._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 Zs._warned||(Zs._warned=!0,console.warn(`@colyseus/schema/input: InputEncoder buffer overflow in ${r}. Growing to ${s} bytes.`)),new Uint8Array(s)}};m(Zs,"_warned",!1);var ol=Zs;Tr();mp();ll();var Qs,Vn,ci,Fa,za,Ua,Va,Ha,$a,ui,ja,dl,vb,li=class{constructor(e){He(this,dl);He(this,Qs);He(this,Vn);He(this,ci);He(this,Fa);He(this,za,!1);He(this,Ua);He(this,Va,!1);He(this,Ha,!1);He(this,$a);He(this,ui);He(this,ja);$e(this,Qs,e)}get patchRate(){return de(this,ui)}applyReflection(e,n,r){let s=Un.decode(e.subarray(0,r),n);Un.makeEncodable(s.state.constructor),$e(this,Ua,s.state.constructor),de(this,Qs).clock===ai&&(de(this,Qs).clock=new ul)}applyOptions(e,n){let r=e[n.offset++];$e(this,Va,(r&js.RENDER_TIME)!==0),$e(this,Ha,(r&js.RECKON_TIME)!==0),r&js.FIXED_TIMESTEP&&$e(this,$a,Pe.number(e,n)),r&js.PATCH_RATE&&$e(this,ui,Pe.number(e,n)),r&js.SUB_STEPS&&$e(this,ja,Pe.number(e,n))}ackInput(e){return de(this,Vn)?de(this,Vn).ackInput(e):-1}reset(){de(this,Vn)?.reset()}handle(e){if(de(this,Vn))return e!==void 0&&Us(this,dl,vb).call(this,e),de(this,Vn);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 ol(r,e);return $e(this,Vn,new ii(de(this,Qs),r,s,{stampRender:de(this,Va),stampReckon:de(this,Ha),renderDelay:e?.renderDelay,allowRewind:e?.allowRewind,tickRate:de(this,$a),patchRate:de(this,ui),subSteps:de(this,ja)})),$e(this,ci,e),$e(this,Fa,s),de(this,Vn)}};Qs=new WeakMap,Vn=new WeakMap,ci=new WeakMap,Fa=new WeakMap,za=new WeakMap,Ua=new WeakMap,Va=new WeakMap,Ha=new WeakMap,$a=new WeakMap,ui=new WeakMap,ja=new WeakMap,dl=new WeakSet,vb=function(e){if(de(this,za))return;let n=de(this,Vn),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,ci)?.renderDelay&&r.push("renderDelay"),e.allowRewind!==void 0!=(de(this,ci)?.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 gp;try{gp=new TextDecoder}catch{}var Z,Rn,O=0;var Ub=[],bp=Ub,wp=0,Le={},Ce,hs,_n=0,fr=0,_t,Nr,Yt=[],ve,Mb={useRecords:!1,mapsAsObjects:!0},Wa=class{},xp=new Wa;xp.name="MessagePack 0xC1";var ms=!1,Cb=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 Wb(()=>(pl(),this?this.unpack(e,n):t.prototype.unpack.call(Mb,e,n)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof n=="object"?(Rn=n.end||e.length,O=n.start||0):(O=0,Rn=n>-1?n:e.length),wp=0,fr=0,hs=null,bp=Ub,_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,fl(n);(!Ce||Ce.length>0)&&(Ce=[])}else Le=Mb,(!Ce||Ce.length>0)&&(Ce=[]);return fl(n)}unpackMultiple(e,n){let r,s=0;try{ms=!0;let o=e.length,i=this?this.unpack(e,o):ml.unpack(e,o);if(n){if(n(i,s,O)===!1)return;for(;O<o;)if(s=O,n(fl(),s,O)===!1)return}else{for(r=[i];O<o;)s=O,r.push(fl());return r}}catch(o){throw o.lastPosition=s,o.values=r,o}finally{ms=!1,pl()}}_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 fl(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,Rn),Z=null,!(t&&t.lazy)&&e&&(e=e.toJSON()),O=Rn):e=ot(),_t&&(O=_t.postBundlePosition,_t=null),ms&&(Ce.restoreStructures=null),O==Rn)Ce&&Ce.restoreStructures&&Ob(),Ce=null,Z=null,Nr&&(Nr=null);else{if(O>Rn)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&&Ob(),pl(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||O>Rn)&&(e.incomplete=!0),e}}function Ob(){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&&Vb()[t&63];return e?(e.read||(e.read=_p(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=$b();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(fr>=O)return hs.slice(O-_n,(O+=e)-_n);if(fr==0&&Rn<140){let n=e<16?Rp(e):Hb(e);if(n!=null)return n}return Sp(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)):xp;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 yp(e);case 197:return e=ve.getUint16(O),O+=2,yp(e);case 198:return e=ve.getUint32(O),O+=4,yp(e);case 199:return eo(Z[O++]);case 200:return e=ve.getUint16(O),O+=2,eo(e);case 201:return e=ve.getUint32(O),O+=4,eo(e);case 202:if(e=ve.getFloat32(O),Le.useFloat32>2){let n=hl[(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 Fb(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++,Fb(Z[O++]&63,Z[O++])):eo(2);case 214:return eo(4);case 215:return eo(8);case 216:return eo(16);case 217:return e=Z[O++],fr>=O?hs.slice(O-_n,(O+=e)-_n):BP(e);case 218:return e=ve.getUint16(O),O+=2,fr>=O?hs.slice(O-_n,(O+=e)-_n):LP(e);case 219:return e=ve.getUint32(O),O+=4,fr>=O?hs.slice(O-_n,(O+=e)-_n):FP(e);case 220:return e=ve.getUint16(O),O+=2,Db(e);case 221:return e=ve.getUint32(O),O+=4,Db(e);case 222:return e=ve.getUint16(O),O+=2,Nb(e);case 223:return e=ve.getUint32(O),O+=4,Nb(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 NP=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function _p(t,e){function n(){if(n.count++>Cb){let s;try{s=t.read=new Function("r","return function(){return "+(Le.freezeData?"Object.freeze":"")+"({"+t.map(o=>o==="__proto__"?"__proto_:r()":NP.test(o)?o+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"})}")(ot)}catch{return Cb=1/0,n()}return t.read0=s,t.highByte===0&&(t.read=Ib(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?Ib(e,n):n}var Ib=(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]||Vb()[r];if(!s)throw new Error("Record id is not defined for "+r);return s.read||(s.read=_p(s,t)),s.read()};function Vb(){let t=Wb(()=>(Z=null,Le.getStructures()));return Ce=Le._mergeStructures(t,Ce)}var Sp=qa,BP=qa,LP=qa,FP=qa;function qa(t){let e;if(t<16&&(e=Rp(t)))return e;if(t>64&&gp)return gp.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 Db(t){let e=new Array(t);for(let n=0;n<t;n++)e[n]=ot();return Le.freezeData?Object.freeze(e):e}function Nb(t){if(Le.mapsAsObjects){let e={};for(let n=0;n<t;n++){let r=$b();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 Hb(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 Rp(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 Bb(){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 yp(t){return Le.copyBuffers?Uint8Array.prototype.slice.call(Z,O,O+=t):Z.subarray(O,O+=t)}function eo(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 Lb=new Array(4096);function $b(){let t=Z[O++];if(t>=160&&t<192){if(t=t-160,fr>=O)return hs.slice(O-_n,(O+=t)-_n);if(!(fr==0&&Rn<180))return Sp(t)}else return O--,jb(ot());let e=(t<<5^(t>1?ve.getUint16(O):t>0?Z[O]:0))&4095,n=Lb[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=[],Lb[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?Rp(t):Hb(t);return a!=null?n.string=a:n.string=Sp(t)}function jb(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 Fb=(t,e)=>{let n=ot().map(jb),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=_p(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 zb={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError=="function"?AggregateError:null};Yt[101]=()=>{let t=ot();if(!zb[t[0]]){let e=Error(t[1],{cause:t[2]});return e.name=t[0],e}return zb[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);Nr||(Nr=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};Nr.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=Nr.get(e);return n.used=!0,n.target};Yt[115]=()=>new Set(ot());var Ep=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(t=>t+"Array"),zP=typeof globalThis=="object"?globalThis:window;Yt[116]=t=>{let e=t[0],n=Uint8Array.prototype.slice.call(t,1).buffer,r=Ep[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 zP[r](n)};Yt[120]=()=>{let t=ot();return new RegExp(t[0],t[1])};var UP=[];Yt[98]=t=>{let e=(t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3],n=O;return O+=e-t.length,_t=UP,_t=[Bb(),Bb()],_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 Wb(t){Le&&Le._onSaveState&&Le._onSaveState();let e=Rn,n=O,r=wp,s=_n,o=fr,i=hs,a=bp,c=Nr,u=_t,l=new Uint8Array(Z.slice(0,Rn)),d=Ce,f=Ce.slice(0,Ce.length),h=Le,p=ms,y=t();return Rn=e,O=n,wp=r,_n=s,fr=o,hs=i,bp=a,Nr=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 pl(){Z=null,Nr=null,Ce=null}var hl=new Array(147);for(let t=0;t<256;t++)hl[t]=+("1e"+Math.floor(45.15-t*.30103));var ml=new ys({useRecords:!1}),yl=ml.unpack,VP=ml.unpackMultiple,HP=ml.unpack,gl={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},$P=new Float32Array(1),vL=new Uint8Array($P.buffer,0,4);ys.SUPPORTS_STRUCT_HOOKS=!0;var wl;try{wl=new TextEncoder}catch{}var Pp,Tp,fi=typeof Buffer<"u",bl=fi?function(t){return Buffer.allocUnsafeSlow(t)}:Uint8Array,Kb=fi?Buffer:Uint8Array,qb=fi?4294967296:2144337920,F,Ga,je,D=0,Ot,Ze=null,jP=21760,WP=/[\u0080-\uFFFF]/,di=Symbol("record-id"),gs=class extends ys{constructor(e){super(e),this.offset=0;let n,r,s,o,i,a=Kb.prototype.utf8Write?function(v,$){return F.utf8Write(v,$,F.byteLength-$)}:wl&&wl.encodeInto?function(v,$){return wl.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 bl(8192),je=F.dataView||(F.dataView=new DataView(F.buffer,0,8192)),D=0),Ot=F.length-10,Ot-D<2048?(F=new bl(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,$&pi&&(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[di]=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)&&!Tp.some(q=>v instanceof q)?K(v.toJSON?v.toJSON():v):E(v):E(v);let W=Ze;if(Ze&&Yb(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=qP(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(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||GP)(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),$&Zb&&(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[$][di]=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)>jP){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,Yb(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=WP.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*hl[(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=Pp.length;q<ae;q++){let ce=Tp[q];if(v instanceof ce){let ne=Pp[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=Gb(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),fi)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=Gb(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[di];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[di];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>qb)throw new Error("Packed buffer would be larger than maximum buffer size");$=Math.min(qb,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 bl($);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[di]=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()[di]=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 bl(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=[])}};Tp=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Wa];Pp=[{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?kp(t,16,e):Ap(fi?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let n=t.constructor;n!==Kb&&this.moreTypes?kp(t,Ep.indexOf(n.name),e):Ap(t,e)}},{pack(t,e){this.moreTypes?kp(t,17,e):Ap(fi?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let{target:n,position:r}=e(1);n[r]=193}}];function kp(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 Ap(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 Gb(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 qP(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 Yb(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 GP(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 Xb=new gs({useRecords:!1}),YP=Xb.pack,KP=Xb.pack;var{NEVER:XP,ALWAYS:JP,DECIMAL_ROUND:ZP,DECIMAL_FIT:QP}=gl,Jb=512,Zb=1024,pi=2048;Pt();Tr();var eT=9,Sl=class{constructor(){m(this,"pending",new Uint8Array(0))}push(e){if(!e||e.byteLength===0)return[];let n=this.pending.byteLength===0?e:tT(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<=eT)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 tT(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 Sl);m(this,"unreliableReassembler",new Sl);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 n0=pE(e0(),1);Tr();var vp=globalThis.WebSocket||n0.default,t0=!1,xl=class{constructor(e){m(this,"ws");m(this,"protocols");m(this,"events");this.events=e}send(e){this.ws.send(e)}sendUnreliable(e){t0||(t0=!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 vp(e,{headers:n,protocols:this.protocols})}catch{this.ws=new vp(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===vp.OPEN}};Tr();var Ka=[],Mp=typeof addEventListener=="function"&&typeof removeEventListener=="function";Mp&&addEventListener("offline",()=>{console.warn(`@colyseus/sdk: \u{1F6D1} Network offline. Closing ${Ka.length} connection(s)`),Ka.forEach(t=>t())},!1);var Xa,hi=class{constructor(e){m(this,"transport");m(this,"events",{});m(this,"url");m(this,"options");He(this,Xa,Mp?()=>this.close(St.MAY_TRY_RECONNECT):null);e==="h3"?this.transport=new Ya(this.events):this.transport=new xl(this.events)}connect(e,n){if(Mp){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 r0={};function Cp(t,e){r0[t]=e}function Op(t){let e=r0[t];if(!e)throw new Error("missing serializer: "+t);return e}var _l=()=>({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 s0=new WeakMap,Ip=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=>s0.get(r)===e)),n!==-1&&(this.handlers=this.handlers.filter((r,s)=>s!==n))}clear(){this.handlers=[]}};function to(){let t=new Ip;function e(n){return t.register(n,this===null)}return e.once=n=>{let r=function(...s){t.remove(r),n.apply(this,s)};s0.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 Yu(t.serializer.decoder)}catch{return}}var mi=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?(Un.decode(e,n),this.decoder=new zn(this.state)):(this.decoder=Un.decode(e,n),this.state=this.decoder.state)}};ll();function o0(){return{enabled:!0,retryCount:0,maxRetries:15,delay:100,minDelay:100,maxDelay:5e3,minUptime:5e3,backoff:nT,maxEnqueuedMessages:10,enqueuedMessages:[],isReconnecting:!1}}var nT=(t,e)=>Math.floor(Math.pow(2,t)*e);function Rl(t,e){t.reconnection.enqueuedMessages.push({data:e}),t.reconnection.enqueuedMessages.length>t.reconnection.maxEnqueuedMessages&&t.reconnection.enqueuedMessages.shift()}function i0(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,yi,gi,pr,hr,bi,mr,a0,c0,u0,l0,El=class El{constructor(e,n){He(this,mr);m(this,"roomId");m(this,"sessionId");m(this,"reconnectionToken");m(this,"name");m(this,"connection");m(this,"onStateChange",to());m(this,"onError",to());m(this,"onLeave",to());m(this,"onReconnect",to());m(this,"onDrop",to());m(this,"onJoin",to());m(this,"serializerId");m(this,"serializer");m(this,"reconnection",o0());m(this,"joinedAtTime",0);m(this,"clock",ai);m(this,"onMessageHandlers",_l());m(this,"packr");m(this,"sharedBuffer");He(this,Qa,0);He(this,yi);He(this,gi,0);He(this,pr,new Map);He(this,hr);He(this,bi,0);if(this.name=e,this.packr=new gs,this.sharedBuffer=new Uint8Array(8192),n){let r=new(Op("schema"));this.serializer=r;let s=new n;r.state=s,r.decoder=new zn(s)}this.onLeave(()=>{this.removeAllListeners(),this.destroy()})}connect(e,n,r){this.connection=new hi(n.protocol),this.connection.events.onmessage=this.onMessageCallback.bind(this),this.connection.events.onclose=o=>{if(Us(this,mr,u0).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,yi,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,pi|o),i.set(this.sharedBuffer.subarray(0,o),0)):i=this.sharedBuffer.subarray(0,o),this.connection.isOpen?this.connection.send(i):Rl(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??El.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(i0(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=Us(this,mr,a0).call(this),a=Us(this,mr,c0).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):Rl(this,new Uint8Array(a));return de(this,pr).set(i,{onReply:s,onClose:o}),i}cancelRequest(e){de(this,pr).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,pi|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)):Rl(this,this.sharedBuffer.subarray(0,s+n.byteLength))}input(e){return(de(this,hr)??$e(this,hr,new li(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 mi&&(this.serializer.decoder.root.callbacks={})}onMessageCallback(e){Us(this,mr,l0).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,hr)?.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,yi=new WeakMap,gi=new WeakMap,pr=new WeakMap,hr=new WeakMap,bi=new WeakMap,mr=new WeakSet,a0=function(){let e=de(this,gi);return $e(this,gi,de(this,gi)+1>>>0),e},c0=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,pi|o);return i.set(this.sharedBuffer.subarray(0,o),0),i}return this.sharedBuffer.subarray(0,o)},u0=function(e){if(de(this,pr).size!==0){for(let n of de(this,pr).values())n.onClose?.(e);de(this,pr).clear()}},l0=function(e){var o;let n={offset:1},r=e[0],s=r&$f;if(r&Qo.TIMED){let i=Pe.uint32(e,n),a=Pe.uint32(e,n),c=de(this,hr)?de(this,hr).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=Op(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===Iu.INPUT_REFLECTION?(de(this,hr)??$e(this,hr,new li(this))).applyReflection(e,n,d):u===Iu.INPUT_OPTIONS&&(de(this,hr)??$e(this,hr,new li(this))).applyOptions(e,n),n.offset=d}let c=de(this,hr)?.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,bi,0),this.serializer.setState(e,n),this.onStateChange.invoke(this.serializer.getState());else if(s===Ke.ROOM_STATE_PATCH){if(r&Qo.UNRELIABLE){let i=Pe.uint16(e,n);if(i-de(this,bi)<<16>>16<=0)return;$e(this,bi,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?yl(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?yl(e,{start:n.offset}):void 0,u=de(this,pr).get(i);u!==void 0&&(de(this,pr).delete(i),u.onReply(a===Ou.OK,c,a===Ou.ERROR))}else s===Ke.PING&&((o=de(this,yi))==null||o.call(this,Math.round(Ct()-de(this,Qa))),$e(this,yi,void 0))},m(El,"defaultRequestTimeout",1e4);var Za=El;function d0(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 Dp(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 Dp=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 rT(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 sT(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 kl=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):d0),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}`),rT(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=sT(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 sr(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 sr(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 no;function Bp(){if(!no)try{no=typeof cc<"u"&&cc.sys&&cc.sys.localStorage?cc.sys.localStorage:window.localStorage}catch{}return!no&&typeof globalThis.indexedDB<"u"&&(no=new Np),no||(no={cache:{},setItem:function(t,e){this.cache[t]=e},getItem:function(t){return this.cache[t]},removeItem:function(t){delete this.cache[t]}}),no}function f0(t,e){Bp().setItem(t,e)}function p0(t){Bp().removeItem(t)}function h0(t,e){let n=Bp().getItem(t);typeof Promise>"u"||!(n instanceof Promise)?e(n):n.then(r=>e(r))}var Np=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,Br,nc,ec=class{constructor(e){m(this,"settings",{path:"/auth",key:"colyseus-auth-token"});He(this,tc,!1);He(this,Br,null);He(this,nc,_l());m(this,"http");this.http=e,h0(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,Br,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,Br)?.close(),$e(this,Br,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,Br)||de(this,Br).closed)&&($e(this,Br,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?p0(this.settings.key):f0(this.settings.key,e.token)),de(this,nc).emit("change",e)}};tc=new WeakMap,Br=new WeakMap,nc=new WeakMap;function m0(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 y0=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",Pl=class Pl{constructor(e=y0,n){m(this,"http");m(this,"auth");m(this,"settings");m(this,"urlBuilder");if(typeof e=="string"){let r=e.startsWith("/")?new URL(e,y0):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 kl(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=m0,console.log("Colyseus SDK: Discord Embedded SDK detected. Using custom URL builder."))}static async selectByLatency(e,n,r={}){let s=e.map(i=>new Pl(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 sr(c,u));r.onError.once(a),r.onJoin.once(()=>{r.onError.remove(a),il("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 hi(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 sr(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 sr?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(Pl,"VERSION","0.18");var Al=Pl,yr=Al;Tr();var Tl=class{setState(e){}getState(){return null}patch(e){}teardown(){}handshake(e){}};Pt();Wp();Il();Dl();Ol();Cp("schema",mi);Cp("none",Tl);var iz=Object.freeze({min:3,max:3}),az=Object.freeze({min:4,max:4});var ws={PLAY:"play",QUEUE:"queue",MATCH:"match",AUTHORITY:"authority"};var qp={CAPS:"caps",SDK:"sdk",MATCH_KEY:"matchKey",PRIVATE:"private",SUCCESSOR_OF:"successorOf",SUCCESSOR_CLOSED:"successorClosed"},C0="ts/0.17.10",fn={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 pT=["clients","preset","winCondition","config","matchmade"],cz=[...pT,"moduleSha","tickHz","maxPlayers","lagComp","seed","units","leaseId","region","createdBy"],pn={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},O0="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"},hT=["__","match:","server:","rate:"],mT=["state","shared","claim","release","destroy","obj","queue","seat"];function Ss(t){return mT.includes(t)||hT.some(e=>t.startsWith(e))}var Ul="__",br="__t";var uz=4*1024;var lz={[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"},hn={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},yT={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 I0(t){return Object.values(yT).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},dz={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},xs={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},mn={enabled:!0,minUptime:0,delay:125,minDelay:100,maxDelay:4e3,maxRetries:9,maxEnqueuedMessages:0,firstStateTimeoutMs:2e3},D0=["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 N0(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??Gp,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 Gp=(t,e)=>new yr(t).getLatency({pingCount:1,timeout:e});var gT=t=>typeof t=="function"?t():t;async function lc(t){return t.url?new yr(t.url):new yr(await N0(t.urls))}function dc(t,e,n){return{gameId:t,name:e,embedToken:gT(n)?.embedToken,protocol:3}}var fc=t=>!!t&&typeof t=="object"&&t.code===pn.PROTOCOL_UNSUPPORTED,Yp=()=>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.`),B0=t=>{throw fc(t)&&Yp(),t};function L0(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 F0=["x","y","z","yaw","vx","vy","vz"],z0=[["x","vx"],["y","vy"],["z","vz"]],Kp=Math.PI*2,bT=t=>D0.includes(t);function Xp(t){if(!Number.isFinite(t))return 0;let e=t%Kp;return e<=-Math.PI?e+=Kp:e>Math.PI&&(e-=Kp),e}var U0=t=>typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=Xt.MAX_POSE_ABS;function V0(t){let e={},n={},r=[];for(let s of Object.keys(t)){let o=t[s];if(!bT(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):U0(o)?e[s]=o:r.push(s))}return{pose:e,data:n,invalid:r}}function H0(t){for(let e in t)if(t[e]!==void 0)return!0;return!1}function $0(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 z0){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]=U0(d)?d:0}return{pose:r,memory:s}}function jl(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 Ci=(t,e)=>{let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0};function j0(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 z0)l[f]=Ci(u.state,f)+Ci(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=Ci(u.state,"yaw");l.yaw=y+Xp(y-Ci(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 F0){let l=Ci(s.state,u),d=Ci(o.state,u);c[u]=u==="yaw"?l+Xp(d-l)*a:l+(d-l)*a}return c}function W0(t,e,n,r){let s={...e};for(let o of F0){let i=t[o],a=e[o];typeof i!="number"||typeof a!="number"||!Number.isFinite(i)||!Number.isFinite(a)||(s[o]=o==="yaw"?i+Xp(a-i)*r:i+(a-i)*n)}return s}var $l=class $l{constructor(){m(this,"pending",[]);m(this,"current")}push(e,n){for(this.pending.push({t:e,state:n});this.pending.length>$l.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($l,"MAX_PENDING",64);var Hl=$l;function q0(t){try{let e=t.input();return e&&typeof e.send=="function"?e:null}catch{return null}}function G0(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 Y0(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 _s(t){let e=t.reconnection;return e.enabled=mn.enabled,e.minUptime=mn.minUptime,e.delay=mn.delay,e.minDelay=mn.minDelay,e.maxDelay=mn.maxDelay,e.maxRetries=mn.maxRetries,e.maxEnqueuedMessages=mn.maxEnqueuedMessages,e.enqueuedMessages.length=0,t}function K0(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 X0(t,e,n){return t!==e&&n!=null}var wT="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.",Jp=class extends Error{constructor(e){super(wT,{cause:e}),this.name="VoiceNotDelegatedError"}},J0=[{urls:"stun:stun.l.google.com:19302"}],ST=120,Z0=.02,xT=.6,Wl=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",J0);m(this,"spatial",!1);m(this,"threshold",Z0);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:J0,this.spatial=e.spatial===!0,this.threshold=e.speakingThreshold??Z0,this.micOn=e.startMuted!==!0;try{this.local=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1})}catch(r){throw RT(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(),ST)}}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=>ET(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?Q0(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(Q0(s.analyser),s.speaking);o!==s.speaking&&(s.speaking=o,e=!0)}e&&this.emit()}crossed(e,n){return e>=(n?this.threshold*xT:this.threshold)}emit(){for(let e of[...this.listeners])try{e()}catch(n){console.error("[multiplayer] a voice listener threw",n)}}};function _T(){try{return window.self!==window.top}catch{return!0}}function RT(t){if(t?.name!=="NotAllowedError")return t;try{if(!_T()||document.featurePolicy?.allowsFeature?.("microphone")!==!1)return t}catch{return t}return new Jp(t)}function ET(t){return(Array.isArray(t.urls)?t.urls:[t.urls]).some(n=>typeof n=="string"&&n.startsWith("turn"))}function Q0(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 Zp=Symbol("genex.roomRef"),zr=t=>t[Zp]();var kT=Ge.RATIO,AT=Ge.MIN_MS,PT=Ge.MAX_MS,ql=Ge.DEFAULT_MS,TT=Ge.JITTER_SAFETY,vT=Ge.POISON_GUARD_MS,MT=Ge.EASE,CT=Ge.MAX_EXTRAP_MS,OT=Ge.ROT_EXTRAP_MS,tw=Ge.CLOCK_WINDOW,IT=Ge.CLOCK_WINDOW_MS,DT=Ge.CLOCK_WINDOW_MAX,NT=Ge.INTERVAL_WINDOW,BT=Ge.MIN_GAP_MS,LT=Ge.MAX_GAP_MS,FT=Ge.HISTORY_MS,zT=Ge.SMOOTH_TAU_POS_MS,UT=Ge.SMOOTH_TAU_ROT_MS,nw=Ge.MAX_HOST_TICK_DT_MS,VT=Ge.REBASE_AFTER_GAP_MS,wr="obj:",HT=3e3,$T=5e3,jT=6e4,WT=2e3;function ow(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 Kl=async t=>ow(t)?Promise.resolve().then(()=>(Qp(),ew)):void 0;function rw(t){if(!t)return{state:{}};try{let e=JSON.parse(t);if(!e||typeof e!="object")return{state:{}};let n=e,r=n[br];if(typeof r=="number"&&Number.isFinite(r)){let s={...n};return delete s[br],{state:s,sendTime:r}}return{state:n}}catch{return{state:{}}}}function Gl(t){if(t!=null)try{return JSON.parse(t)}catch{return}}var qT=(t,e)=>typeof e=="number"?Number.isFinite(e)?e:0:typeof e=="bigint"?Number(e):e;function Oi(t){return JSON.parse(JSON.stringify(t,qT))}var lo=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function iw(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 Yl(t){return Array.isArray(t)&&t.length===4&&t.every(e=>typeof e=="number"&&Number.isFinite(e))}function sw(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:Yl(a)&&Yl(c)?s[i]=iw(a,c,r):s[i]=o&&i in t?a:c}return s}function GT(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:Yl(a)&&Yl(i)?s[o]=iw(a,i,r):s[o]=i}return s}function YT(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+CT)-c.t)/l,f=(Math.min(e,u.t+OT)-c.t)/l;return sw(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 sw(s.state,o.state,a,a)}function KT(t){if(t.length===0)return 66;let e=[...t].sort((n,r)=>n-r);return e[e.length>>1]}function XT(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 aw(t){let e=await lc(t),n=await Kl(t.smoothing),r=_s(await e.joinOrCreate(ws.PLAY,{...dc(t.room,t.name,t.auth),...t.options,protocol:3}).catch(B0));return eh(r,{pose:t.pose,smoothing:t.smoothing,predict:n})}var JT=t=>typeof t=="string"&&t.length>0&&t.length<=Xt.MAX_EVENT_TYPE_CHARS&&!Ss(t),ZT=new Set(["join","leave","change","shared","object","host","reconnecting","reconnected","disconnect","room:open","voice","voice:rejected"]),QT=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)]),ev=[500,1e3,2e3,4e3,8e3];function eh(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>DT||ie.samples.length>tw&&ie.samples[0].at<we-IT;)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>tw&&nt.shift(),a.set(w,X);let ut=r.get(w);if(r.set(w,pe),ut!=null){let rt=pe-ut;if(rt>BT&&rt<LT){let kr=d.get(w);kr||d.set(w,kr=[]),kr.push(rt),kr.length>NT&&kr.shift();let Kd=nt.length>=8?Math.max(0,XT(nt,.9)-ie.mins[0].v):0,nu=Math.min(PT,Math.max(AT,kT*KT(kr),TT*Kd)),er=f.get(w)??ql;f.set(w,er+(nu-er)*MT)}}let Qe=n.get(w);Qe||n.set(w,Qe=[]);let Zn=k.get(w);if(Zn&&Qe.length===0){let rt=f.get(w)??ql;Qe.push({t:pe-Math.max(1,rt),state:Zn})}k.delete(w),Qe.push({t:pe,state:C});let Qn=pe-FT;for(;Qe.length>2&&Qe[0].t<Qn;)Qe.shift();for(;Qe.length>1&&Qe[0].t>Qe[Qe.length-1].t+vT;)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)??ql)},W=(w,C)=>{let V=n.get(w),X=G(w,C)??C-ql,we=c.has(w),pe=V&&(we?j0(V,X):YT(V,X));if(!pe)return u.get(w);let Me=u.get(w),ie;if(Me){let Ne=Math.min(nw,Math.max(0,C-(l.get(w)??C))),ze=1-Math.exp(-Ne/zT),nt=1-Math.exp(-Ne/UT);ie=we?W0(Me,pe,ze,nt):GT(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,Gl(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))},Rr=(w,C)=>{let V=wr+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),Zn=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?Gl(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 Qn=A.get(w);if(Qn&&pe!==X){let rt=Ne!==0&&Zn&&pe!==void 0;Qe?(u.set(V,Qn),l.set(V,se()),rt&&$(V,Qn,Ne,pe)):(ut&&k.set(V,u.get(V)??Qn),rt&&$(V,Qn,Ne,pe))}(!we||ut)&&oe("object",w)},Yn=w=>{let C=b.has(w)||p.has(w)||A.has(w)||E.has(w);q(wr+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)},Oo=new Map,Cs=new Map,na=new Map,Gd=(w,C)=>{if(!C)return{};let V=Oo.get(w);if(V&&V.raw===C)return V.state;let{state:X}=rw(C);return Oo.set(w,{raw:C,state:X}),X},Pn=new Map,wn=new Map,Kn=e.predict?ow(e.smoothing):void 0,ct,Xn=new Map,Yd=(w,C)=>{if(!Kn||!e.predict)return;ct??(ct=e.predict.Predict.get(t));let V={mode:Kn.mode,delay:Kn.delay,smoothMs:Kn.smoothMs};ct.attach(C,{x:V,y:V,z:V,vx:V,vy:V,vz:V}),ct.attach(C,{yaw:{...V,angle:!0}}),Xn.set(w,C)},qc=w=>{let C=Xn.get(w);C&&ct&&ct.detach(C),Xn.delete(w)},Gc=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??""}},tn=!1,Tn=!1,bt=!0,Xr=!1,ra=0,Jr=0,sa=0,oa=new Set,Os=()=>oa.forEach(w=>w()),Is=(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(wr+w.id)),w.operation==="release"&&C.accepted&&(E.delete(w.id),p.get(w.id)===t.sessionId&&p.delete(w.id),ae(wr+w.id)),w.operation==="remove"&&C.accepted&&(E.delete(w.id),A.delete(w.id),p.delete(w.id),q(wr+w.id)),w.resolve(C)},Ds=(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}},Io=w=>{for(let C of[...K.values()])Is(C,Ds(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??$T,jT));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(tn||Tn){Me(Ds(ie,tn?"aborted":"disconnected"));return}if(ie.optimistic&&p.set(X,t.sessionId),ie.timeout=setTimeout(()=>Is(ie,Ds(ie,"timeout")),pe),V.signal){let Ne=()=>Is(ie,Ds(ie,"aborted"));V.signal.addEventListener("abort",Ne,{once:!0}),ie.abort=()=>V.signal?.removeEventListener("abort",Ne)}if(K.set(we,ie),V.signal?.aborted){Is(ie,Ds(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},Do,Yc=0,Kc,Xc=new Set,Jc=(w,C)=>{let{pose:V,data:X,invalid:we}=V0(w);for(let ze of we)Xc.has(ze)||(Xc.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(!H0(V))return!1;let pe=se(),Me=$0(V,pe,C?void 0:Kc);Kc=Me.memory;let ie=JSON.stringify(X),Ne=C||ie!==Do||pe-Yc>=WT;return Ne&&tt(he.STATE,JSON.stringify({...X,[br]:pe}))?(Do=ie,Yc=pe):Ne&&(Do=void 0),tt(C?he.POSE_SNAP:he.POSE,{...Me.pose,t:pe})||(Do=void 0),!0},Ve=new Wl({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,Ns=L0(()=>tt(he.VOICE_ICE_REQUEST,{},!0),HT),No=()=>{es&&clearTimeout(es),es=null},Jn=w=>{No(),!(typeof w!="number"||!Number.isFinite(w)||w<=0)&&(es=setTimeout(()=>{Ve.active&&Ns.request().then(C=>{!Ve.active||!C?.iceServers?.length||(Ve.setIceServers(C.iceServers),Jn(C.ttl))})},Math.max(6e4,Math.floor(w*800))))},Er=[],Bo=new Set,Bs=new Set,Ls=new Set,Lt=w=>!!w&&typeof w=="object"&&typeof w.id=="number"&&typeof w.from=="string"&&typeof w.name=="string"&&typeof w.text=="string",Zc=w=>{if(!Lt(w)||Bo.has(w.id)||Ls.has(w.from))return;Bo.add(w.id);let C=Er[Er.length-1];if(!C||w.id>C.id)Er.push(w);else{let V=Er.length;for(;V>0&&(Er[V-1]?.id??0)>w.id;)V--;Er.splice(V,0,w)}for(let V of[...Bs])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 Lo=(w,C,V)=>{let X=w===t.sessionId,{state:we,sendTime:pe}=rw(C.data),Me=Number.isFinite(C.epoch)?C.epoch:0,ie=Cs.has(w)&&Me!==Cs.get(w);Cs.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!==(wn.get(w)??0);wn.set(w,ze);let ut=C.posed===!0;if(!X&&ut&&!c.has(w)&&(q(w),c.add(w),Pn.set(w,new Hl)),!X&&ie&&(q(w),Xn.has(w)&&qc(w)),oe(V?"join":"change",w,ut?{...we,...jl(C)}:we),!X){if(ut){let Qe=Pn.get(w);(Ne||ie)&&(Qe.push(pe,we),(ie||Kn)&&Qe.flush()),Kn?Xn.has(w)||Yd(w,C):ze!==0&&(nt||ie)&&$(w,jl(C),ze,w);return}(Ne||ie)&&X0(w,t.sessionId,pe)&&$(w,we,pe,w)}};Et(t.state).players.onAdd((w,C)=>{Lo(C,w,!0),Et(w).onChange(()=>Lo(C,w,!1))});let Fo=w=>{oe("leave",w),q(w),ce(w),qc(w),Oo.delete(w),Cs.delete(w),na.delete(w),wn.delete(w),c.delete(w),Pn.delete(w)};Et(t.state).players.onRemove((w,C)=>Fo(C)),Et(t.state).shared.onAdd(ue),Et(t.state).shared.onChange(ue),Et(t.state).objects.onAdd((w,C)=>{Rr(C,w),Et(w).onChange(()=>Rr(C,w))}),Et(t.state).objects.onRemove((w,C)=>Yn(C)),Et(t.state).listen("host",w=>Ae(w)),Et(t.state).voice.onAdd(Bt),Et(t.state).voice.onRemove(Bt);let Qc=()=>{let w=t.state;if(w){for(let C of new Set([...p.keys(),...A.keys(),...b.keys()]))w.objects?.has(C)||Yn(C);for(let C of[...Cs.keys()])w.players?.has(C)||Fo(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=>{No(),Ve.stop(),oe("voice:rejected",w??{reason:"full"})}),t.onMessage(xe.VOICE_ICE,w=>{Ns.deliver(w??null)}),t.onMessage(xe.CHAT,w=>Zc(w)),t.onMessage(xe.CHAT_HISTORY,w=>{if(Array.isArray(w?.messages))for(let C of w.messages)Zc(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||Is(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 eu=q0(t),ts=eu?G0(eu,()=>!Tn&&!tn):void 0,ns=()=>ts?t.clock.serverNow():void 0,aa=w=>Y0(w,{synced:ts?.synced===!0,clockOrigin:Number.isFinite(t.state?.clockOrigin)?t.state?.clockOrigin:0,serverNow:ns(),wallNow:Date.now()}),tu=()=>{ts?.stop(),ct?.dispose(),ct=void 0,Xn.clear()};t.onDrop(w=>{if(tn||Tn)return;sa++,Xr||(Xr=!0,ra=0,Jr=lo()),bt=!1,Os();let{isReconnecting:C,retryCount:V,maxRetries:X}=t.reconnection;C&&V>=X||oe("reconnecting",{attempt:++ra,code:w})}),t.onReconnect(()=>{if(Tn)return;if(tn){t.leave().catch(()=>{});return}let w=sa;if((Jr?lo()-Jr:0)>VT){for(let V of[...n.keys()])q(V);for(let V of[...o.keys()])ce(V)}(async()=>{if(await pc(t,mn.firstStateTimeoutMs),!(w!==sa||Tn||tn)){Qc();for(let V of[...K.values()])ia(V,!0);tt(he.CHAT_HISTORY_REQUEST,{}),Xr=!1,Jr=0,bt=!0,Os(),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=>{Tn||(Tn=!0,bt=!1,Xr=!1,tu(),Os(),!tn&&(Io("disconnected"),oe("disconnect",w??1006)))}),t.onError(()=>{});let zo=((w,C)=>{let V=ne.get(w);return V||ne.set(w,V=new Set),V.add(C),!ZT.has(w)&&!QT.has(w)&&!Re.has(w)&&(Re.add(w),t.onMessage(w,X=>oe(w,X))),()=>{V?.delete(C)}}),Fs={id:t.sessionId,get players(){let w=new Map,C=se();return ct&&Xn.size>0&&ct.tick(lo()),t.state?.players?.forEach((V,X)=>{let we=Gd(X,V.data),pe=we,Me=we,ie=Pn.get(X);if(X!==t.sessionId&&ie){let Ne=jl(V);if(Me={...we,...Ne},Xn.has(X))pe={...ie.at(void 0)??we,...Gc(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([...Fs.players].filter(([,w])=>w.connected))},me:{set(w){br in w&&console.warn(`[multiplayer] '${br}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let C=Oi(w);h=C,!(e.pose&&Jc(C,!1))&&tt(he.STATE,JSON.stringify({...C,[br]:se()}))},snap(w){br in w&&console.warn(`[multiplayer] '${br}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let C=Oi(w);h=C,!(e.pose&&Jc(C,!0))&&tt(he.STATE_SNAP,JSON.stringify({...C,[br]:se()}))}},shared:{get(w){return Gl(t.state?.shared?.get(w))},set(w,C){w.startsWith(Ul)||tt(he.SHARED,{key:w,value:JSON.stringify(Oi(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(wr+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(wr+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=Oi(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=Oi(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(wr+C,X),l.set(wr+C,se())):(Me=A.get(C)??{},pe=W(wr+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&&!tn&&!Tn&&M!==void 0&&M===t.sessionId},get host(){return M},inputs:{send(w){tt(he.INPUT,Oi(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&&!tn&&!Tn&&M!==void 0&&M===t.sessionId;Ne&&!V?(X=lo(),V=setInterval(()=>{let ze=lo();C(Math.min(ze-X,nw)),X=ze},pe)):!Ne&&V&&(clearInterval(V),V=null)},ie=zo("host",Me);return oa.add(Me),Me(),()=>{ie(),oa.delete(Me),V&&clearInterval(V),V=null}},on:zo,send(w,C){if(!JT(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 Bs.add(w),()=>Bs.delete(w)},get history(){return[...Er]},mute(w){typeof w=="string"&&w&&Ls.add(w)},unmute(w){Ls.delete(w)},get muted(){return[...Ls]}},voice:{async join(w){if(await Ve.start(w,!0),!w?.iceServers?.length){let C=await Ns.request();Ve.active&&C?.iceServers?.length&&(Ve.setIceServers(C.iceServers),Jn(C.ttl))}Ve.active&&(tt(he.VOICE_JOIN,{},!0),Ve.releasePeering())},leave(){No(),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(){tn=!0,tu(),Ve.stop(),No(),bt=!1,Os(),Io("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(Fs,Zp,{value:()=>t,enumerable:!1}),Object.defineProperty(Fs,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}}),Fs}var tv=[1e3,2e3,4e3],th=t=>dc(t.room,t.name,t.auth);function cw(t,e,n=r=>r-Date.now()){let r=t?.state?.match,s=r?Gl(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 Ii(t,e,n){if(t?.connection?.isOpen)try{t.send(e,n)}catch{}}async function uw(t){let e=await lc(t),n=await Kl(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=K0(await e.joinOrCreate(ws.QUEUE,th(t)))}catch(B){if(l)return;let K=fc(B);K&&Yp();let j=K?void 0:tv[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 ev)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=_s(await e.consumeSeatReservation(P));if(l||M!==f){B.leave();return}a=B;let K=eh(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===hn.SUPERSEDED||j===hn.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=cw(P,u,i?i.timeUntil:void 0);return k&&(A=M),M};return{get session(){return i},get matchmaking(){return E()},on:o,eliminated(){Ii(x(),he.MATCH_ELIMINATED,{})},score(P=1){Ii(x(),he.MATCH_SCORE,{delta:P})},finish(){Ii(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 lw(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=eh(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 cw(a(),{position:0,size:0},i.timeUntil)},on:s,eliminated(){Ii(a(),he.MATCH_ELIMINATED,{})},score(c=1){Ii(a(),he.MATCH_SCORE,{delta:c})},finish(){Ii(a(),he.MATCH_FINISH,{})},retry(){},cancel(){i.leave(),o=!1}}}async function dw(t){let e=await lc(t),n=await Kl(t.smoothing),r=_s(await e.create(ws.MATCH,th(t))),s=lw(r,{pose:t.pose,smoothing:t.smoothing,predict:n});return Object.defineProperty(s,"code",{value:r.roomId,enumerable:!0}),s}async function fw(t,e){let n=await lc(e),r=await Kl(e.smoothing),s=_s(await n.joinById(t,th(e)));return lw(s,{pose:e.pose,smoothing:e.smoothing,predict:r})}var nv=2,Xl=ga;function rv(t){Xl=t??ga}function sv(t){let e=JSON.parse(t);if(!Cn(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(Cn(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"||Cn(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:Cn(e.options)?e.options:void 0}}var nh=new Map,ov=1,rh=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 hw(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:Cn(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:Cn(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:Cn(i)&&typeof i.dropped=="number"?i.dropped:0})),n.onMessage("*",(i,a)=>{typeof i=="string"&&!Ss(i)&&ye(t,{type:"message",kind:i,data:a??null})}))}function Jl(t){let e=rh(t);e&&e!==t.wired&&hw(t,e)}async function iv(t){let e=t.opts;if(await Xl.ready(e.gameId),t.closed)return;let n=e.urls.length?e.urls:Xl.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=()=>Xl.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 aw({...s,options:e.options});if(t.closed)return void a.leave();t.session=a,hw(t,a);return}let o=s,i=e.room==="queue"?await uw(o):e.room==="private"?await dw(o):await fw(e.room.joinById,o);if(t.closed)return void i.cancel();t.mm=i,i.on("queue",a=>{Cn(a)&&ye(t,{type:"queue",position:Number(a.position)||0,size:Number(a.size)||0})}),i.on("matched",()=>{ye(t,{type:"seated"}),Jl(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:Zo(a),message:nr(a)})}),i.on("disconnect",a=>{hc(t),ye(t,{type:"disconnected",code:typeof a=="number"?a:0,reason:""})}),Jl(t)}function mw(t){let e=sv(t),n=ov++,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};nh.set(n,r);let s=iv(r).catch(o=>{throw hc(r),ye(r,{type:"joinFailed",code:Zo(o),message:nr(o)}),o});return{handle:n,done:s}}function av(t){let{handle:e,done:n}=mw(t);return n.catch(()=>{}),e}async function cv(t){let{handle:e,done:n}=mw(t);try{await n}catch(r){let s=new Error(nr(r));throw s.code=Zo(r),s}return e}var Rs=t=>nh.get(t),Dt=t=>{let e=Rs(t);return e?(Jl(e),rh(e)):null};function yw(t){let e=Rs(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 uv(t){yw(t),typeof t=="number"&&nh.delete(t)}function lv(t,e){let n=rr(e,"state"),r=Dt(t);return r?(r.me.set(n),!0):!1}function dv(t,e){let n=rr(e,"state"),r=Dt(t);return r?(r.me.snap(n),!0):!1}function fv(t,e,n){let r=ba(n,"value");if(typeof e!="string"||!e||e.startsWith(Ul))return!1;let s=Dt(t);return s?(s.shared.set(e,r),!0):!1}function pv(t,e,n){let r=rr(n,"object state"),s=Dt(t);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.set(e,r),!0)}function hv(t,e,n){let r=rr(n,"object state"),s=Dt(t);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.snap(e,r),!0)}function mv(t,e,n){let r=ba(n,"event data");if(typeof e!="string"||!e||e.length>Xt.MAX_EVENT_TYPE_CHARS||Ss(e))return!1;let s=Dt(t);return s?(s.send(e,r),!0):!1}function yv(t,e){}function gv(t,e){let n=ba(e,"input"),r=Dt(t);return r?(r.inputs.send(n),!0):!1}function bv(t,e){let n=Dt(t);return n?(n.setRoomOpen(e===!0),!0):!1}function wv(t,e){let n=Dt(t);return!n||typeof e!="string"?!1:(n.chat.send(e),!0)}function Zl(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=Rs(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 Sv(t,e,n){Zl(t,"claim",e,n)}function xv(t,e,n){Zl(t,"claim",e,n,!0)}function _v(t,e,n){Zl(t,"release",e,n)}function Rv(t,e,n){Zl(t,"remove",e,n)}function Ev(t){let e=Rs(t);return!e?.mm||e.closed?!1:(e.mm.eliminated(),!0)}function kv(t,e=1){let n=Rs(t);return!n?.mm||n.closed||typeof e!="number"||!Number.isFinite(e)?!1:(n.mm.score(e),!0)}function Av(t){let e=Rs(t);return!e?.mm||e.closed?!1:(e.mm.finish(),!0)}function Pv(t){return Dt(t)?.serverNow()??null}function Tv(t,e){let n=Dt(t);return n?n.timeUntil(e):e-Date.now()}var pw=t=>typeof t=="number"&&Number.isFinite(t)?t:null;function vv(t){let e=Rs(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:pw(n?.serverNow()),rtt:pw(n?.rtt),clockSynced:n?.clockSynced??!1,clockOrigin:r?.state?.clockOrigin??0,matchState:o})}function Mv(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 Cv(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 Ov(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 Iv(t){let e=Rs(t);if(!e)return"[]";try{Jl(e);let n=rh(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,Jo(nr(n)))}return Cu(e)}var Om={};af(Om,{BODY_F32_STRIDE:()=>Tm,BodyF32Flag:()=>vm,authorityJson:()=>CD,bodiesF32:()=>vD,bodyKeysJson:()=>MD,closeAuthority:()=>jR,disposeAuthority:()=>DD,drainAuthorityEventsJson:()=>ID,frame:()=>PD,openAuthority:()=>_D,predictProjectile:()=>ED,setAuthorityIdentity:()=>lD,setAuthorityPhysicsCore:()=>dD,setInput:()=>RD,setWorld:()=>kD,version:()=>uD});var gw=2*Math.PI,bw=Math.fround(Math.PI),Oe=t=>t===0?0:t;function $n(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 Es(t){if(typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>1e9)return null;let e=Math.fround(t-gw*Math.floor((t+Math.PI)/gw));return e===bw?-bw:Oe(e)}function fo(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<16777216?t:0}function Ql(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?0:t>e?e:t}var yn=(t,e,n)=>t<e?e:t>n?n:t,ww=5734161139222659/2**53,Sw=1686629713/2**30,xw=2242054355/2**65,_w=5376105825661043/2**121,Rw=-6004799503160649/2**55,Ew=0x8888888887c53/2**58,kw=-7320136532976085/2**65,Aw=6506786730409597/2**71,Pw=-7571127717829867/2**78,Tw=0x5764e96b3f55f/2**83,vw=0x5555555555553/2**55,Mw=-6405119470031223/2**62,Cw=457508533350745/2**64,Ow=-5205429506036397/2**74,Iw=0x47ba7af6d2c71/2**79,Dw=-0x63eba6fa20e35/2**87,Xz=Object.freeze({invpio2:ww,pio2_1:Sw,pio2_2:xw,pio2_2t:_w,S1:Rw,S2:Ew,S3:kw,S4:Aw,S5:Pw,S6:Tw,C1:vw,C2:Mw,C3:Cw,C4:Ow,C5:Iw,C6:Dw});function Ut(t){if(!Number.isFinite(t)||Math.abs(t)>1e9)return[0,1];let e=Math.floor(t*ww+.5),n=e-4*Math.floor(e/4),r=t-e*Sw-e*xw-e*_w,s=r*r,o=r+s*r*(Rw+s*(Ew+s*(kw+s*(Aw+s*(Pw+s*Tw))))),i=.5*s,a=1-i,c=a+(1-a-i+s*(s*(vw+s*(Mw+s*(Cw+s*(Ow+s*(Iw+s*Dw)))))));return n===0?[Oe(o),Oe(c)]:n===1?[Oe(c),Oe(-o)]:n===2?[Oe(-o),Oe(-c)]:[Oe(-c),Oe(o)]}var Nw=t=>Ut(t)[0],Bw=t=>Ut(t)[1];var xr={TOPDOWN:"topdown",FIRSTPERSON:"firstperson",VEHICLE:"vehicle"},uh=.25,Dv=Object.freeze({speed:6,arena:20}),Nv={speed:{min:0,max:1e3,positive:!1},arena:{min:0,max:1e6,positive:!0}};var lh=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.getPrototypeOf(t)===Object.prototype;function Hw(t,e){if(e===void 0)return!0;let n=bc(t)?.ranges;return n===void 0||!lh(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 Ni(t,e){let n=bc(t);if(n===void 0)return{};let r={...n.defaults};if(!lh(e))return r;for(let s of Object.keys(n.ranges))Hw(t,{[s]:e[s]})&&(r[s]=e[s]);return r}var oh=t=>Number.isFinite(t)?t:0;function Bv(t,e,n,r){let s=$n(e.moveX),o=$n(e.moveY),i=Ql(n,uh),a=Math.sqrt(s*s+o*o),c=a>1?1/a:1,u=oh(t.x)+s*c*r.speed*i,l=oh(t.y)+o*c*r.speed*i;return{x:Oe(Math.fround(yn(u,-r.arena,r.arena))),y:Oe(Math.fround(yn(l,-r.arena,r.arena))),yaw:Es(e.yaw)??Oe(Math.fround(oh(t.yaw)))}}var $w=2615243109,Lv=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:$w}),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}),Fv={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},zv=Vt.ON_GROUND|Vt.DUCKING|Vt.JUMP_HELD,Uv={MAX_BOXES:32768,MAX_RAMPS:4096,MAX_ABS:1e9},gn=class extends RangeError{constructor(n,r){super(`firstperson world: ${n} ${r}`);m(this,"path");this.name="WorldError",this.path=n}},mc=new WeakMap,Vv=(t,e)=>{if(typeof t!="number"||!Number.isFinite(t))throw new gn(e,"is not a finite number");if(Math.fround(t)!==t)throw new gn(e,"is not a float32");if(Math.abs(t)>1e9)throw new gn(e,`is past \xB1${1e9}`);return Oe(t)};function Lw(t,e,n){if(!Array.isArray(t)||t.length!==e)throw new gn(n,`is not an array of ${e} numbers`);let r=[];for(let s=0;s<e;s++)r.push(Vv(t[s],`${n}[${s}]`));if(!(r[0]<r[3]&&r[1]<r[4]&&r[2]<r[5]))throw new gn(n,"needs min < max on every axis");return r}function Fw(t,e,n){if(t===void 0)return[];if(!Array.isArray(t))throw new gn(e,"is not an array");if(t.length>n)throw new gn(e,`holds more than ${n}`);return t}function Hv(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&&!lh(t))throw new gn("$","is not an object");let r=t??{},s=e.caps??Uv,o=Fw(r.boxes,"boxes",s.MAX_BOXES).map((c,u)=>Object.freeze(Lw(c,6,`boxes[${u}]`))),i=Fw(r.ramps,"ramps",s.MAX_RAMPS).map((c,u)=>{let l=`ramps[${u}]`,d=Lw(c,9,l);if(d[6]!==0&&d[6]!==1)throw new gn(`${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 gn(l,"needs minZ \u2264 lo and minZ \u2264 hi");if(h!==Math.max(p,y))throw new gn(l,"needs maxZ = max(lo, hi)");return Object.freeze(d)}),a=Object.freeze({boxes:Object.freeze(o),ramps:Object.freeze(i),hash:Hv(o,i),broadphase:e.broadphase!==!1});return mc.set(a,$v(a)),a}var yc=mo(void 0),Hr={Box:0,OBox:1,Disc:2},ah=96,dh=new Int32Array(ah);function gc(t){let e=t.length;if(e>ah)throw new RangeError(`posed solids: at most ${ah} 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 jw=gc([]);function fh(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 Di=8,zw=2**23;function $v(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?Wv(s):null}}function ih(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 jv(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]=(ih(f)|ih(h)<<1|ih(p)<<2)*zw+d}u.sort();let l=new Int32Array(t);for(let d=0;d<t;d++)l[d]=u[d]%zw;return l}function Wv(t){let e=t.count,n=jv(e,t),r=[e];for(;r[r.length-1]>1;)r.push(Math.ceil(r[r.length-1]/Di));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+=Di){let h=Math.min(f+Di,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 Ww=16,qw=50,qv=.5,ph=(t,e)=>t/e<qv?t/e:1,hh=(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)),Sr=null;function mh(t,e,n,r,s,o,i){Gv(t,e,n,r,s,o,i);let a=t.w.tree;if(a===null){t.nCand=-1;return}let c=hh(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+Di;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,Sr!==null&&(Sr.nodes+=M,Sr.tests+=P)}function Gv(t,e,n,r,s,o,i){let a=t.p,c=0;if(a.count>0){let u=hh(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 yh=t=>(t.nCand<0?t.w.count:t.nCand)+t.nPosed,gh=(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 Yv(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*yn(a-s.m0[e],0,s.span[e])}function Gw(t,e,n,r){let s=t.w;return e<s.boxCount?s.maxZ[e]:e<s.count?Yv(t,e,n,r):t.p.maxZ[e-s.count]}var Kv=(t,e)=>e<t.w.count?t.w.minZ[e]:t.p.minZ[e-t.w.count];function Yw(t,e,n,r){let s=t.w,o=t.r;return e>=s.count?Qw(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 Kw(t,e,n,r,s){let o=t.w;mh(t,e,n,r,e,n,r+s);let i=yh(t);for(let a=0;a<i;a++){let c=gh(t,a);if(!Yw(t,c,e,n)||!(r+s>Kv(t,c)))continue;let u=Gw(t,c,e,n);if(r<u-1e-4)return!1}return!0}function od(t,e,n,r,s,o){let i=t.w;mh(t,e,n,r-s,e,n,r+o);let a=yh(t),c=Number.NaN,u=Number.NaN;for(let l=0;l<a;l++){let d=gh(t,l);if(!Yw(t,d,e,n))continue;let f=Gw(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 nd(t){if(t.vz>.1*t.unit){t.onGround=!1;return}let e=od(t,t.x,t.y,t.z,t.groundTrace,t.groundSnap);e===e?(t.z=e,t.onGround=!0):t.onGround=!1}function td(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 Xv(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 rd(t,e,n,r,s,o){let i=t.w,a=t.r,c=t.skin;if(s>=i.count)return tM(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++){Xv(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 bh(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&&rd(t,e,n,r,y,c)&&!rd(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=hh(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=$+Di;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 Sr!==null&&(Sr.nodes+=d,Sr.tests+=f),p}function Xw(t,e,n,r,s,o,i,a,c,u){return bh(t,e+s*a,n+o*a,r+i*a,e,n,r,c,u)}function Jv(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&&!bh(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 wh(t,e,n,r,s,o,i,a,c,u=t.w,l=a){let d=t.r;return t.depth=0,Jv(t,e,n,r,u,a,c,l)?!0:(t.tMin=0,t.tMax=1,t.ax=-1,t.sg=0,!td(t,e,s,u.minX[a]-d,u.maxX[a]+d,0)||!td(t,n,o,u.minY[a]-d,u.maxY[a]+d,1)||!td(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 Zv(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&&Xw(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 Jw(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 Qv=10,Zw=8,eM=9;function Qw(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 eS(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 tM(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 eS(t,s,e,n)>a;for(let u=0;u<Zw;u++){Jw(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 nM(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<Qv;x++){Jw(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!==Zw&&B<p&&!(h&&x===eM&&Xw(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 rM(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(!td(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 jn={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 sM(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=eS(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&&!bh(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;jn.minX[0]=h-f,jn.maxX[0]=h+f,jn.minY[0]=p,jn.maxY[0]=p,jn.minX[1]=h,jn.maxX[1]=h,jn.minY[1]=p-f,jn.maxY[1]=p+f;for(let B=0;B<2;B++)jn.minZ[B]=l.minZ[a],jn.maxZ[B]=S,wh(t,e,n,r,s,o,i,B,u,jn,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;rM(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 oM(t,e,n,r,s,o,i,a,c){let u=a-t.w.count,l=t.p.kind[u];return l===Hr.Box?wh(t,e,n,r,s,o,i,u,c,t.p,a):l===Hr.OBox?nM(t,e,n,r,s,o,i,u,a,c):sM(t,e,n,r,s,o,i,u,a,c)}function Sh(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;mh(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=yh(t),h=!1,p=0,y=0,S=0,b=0,x=0,R=0;Sr!==null&&(Sr.sweeps+=f);for(let A=0;A<f;A++){let E=gh(t,A);Sr!==null&&E>=a.boxCount&&E<a.count&&(Sr.wedges+=1),(E<a.boxCount?wh(t,e,n,r,s,o,i,E,c):E<a.count?Zv(t,e,n,r,s,o,i,E,c):oM(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 sd(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;Sh(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 tS(t,e=!1){let n=t.x,r=t.y,s=t.z,o=t.vx,i=t.vy,a=t.vz;sd(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;Sh(t,n,r,s,0,0,b);let x=t.tMin,R=s+b*x;if(x>0&&Kw(t,n,r,R,Ur(t,t.duck))){t.z=R,sd(t,t.h,e);let A=od(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 nS(t){let e=od(t,t.x,t.y,t.z,t.stepHeight,t.groundSnap);e===e&&(t.z=e,t.vz=0)}function iM(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 aM(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 Uw(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 kn=t=>Oe(Math.fround(yn(t,-1e9,1e9)));function cM(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));Kw(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;nd(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,Uw(t)):(iM(t),aM(t),t.vz=0):Uw(t);let i=!t.onGround;i&&(t.vz=t.vz-t.gravity*t.h*.5),t.vx=yn(t.vx,-t.maxVelocity,t.maxVelocity),t.vy=yn(t.vy,-t.maxVelocity,t.maxVelocity),t.vz=yn(t.vz,-t.maxVelocity,t.maxVelocity),t.onGround?(tS(t),nS(t)):sd(t,t.h),nd(t),i&&!t.onGround?t.vz=t.vz-t.gravity*t.h*.5:t.onGround&&(t.vz=0),t.x=kn(t.x),t.y=kn(t.y),t.z=kn(t.z),t.vx=kn(t.vx),t.vy=kn(t.vy),t.vz=kn(t.vz),t.duck=Oe(Math.fround(t.duck))}var Tt=(t,e,n,r)=>Oe(Math.fround(yn(typeof t=="number"&&Number.isFinite(t)?t:e,n,r))),ch=t=>Oe(Math.fround(typeof t=="number"&&Number.isFinite(t)?t:0)),ed={cand:new Int32Array(0),stack:new Int32Array(Di*16)};function xh(t){return ed.cand.length<t.count&&(ed={cand:new Int32Array(t.count),stack:ed.stack}),ed}function rS(t,e,n=yc){let r=fh(n),s=Math.fround,o=a=>s(t==="vehicle"?e.height:e[a]),i=(a,c)=>{let u=xh(r);return{w:r,p:gc(c),r:s(e.radius),unit:ph(s(e.radius),t==="vehicle"?qw:Ww),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:dh,nPosed:0,stack:u.stack}};return{support(a,c){let u=i(a,c);if(u.vz>.1*u.unit)return-1;let l=od(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&&Qw(u,d,u.x,u.y))return d;return-1},inside(a,c,u){let l=i(a,c);return rd(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&&(Sh(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=rd(u,u.x,u.y,u.z,f,l);return{x:u.x,y:u.y,z:u.z,inside:d}}}}function uM(t,e,n,r,s=yc,o=jw){let i=fh(s),a=xh(i),c=Math.fround,u=fo(t.mstate)&zv,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:ph(c(r.radius),Ww),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:dh,nPosed:0,stack:a.stack},d=$n(e.moveX),f=$n(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=Ql(n,uh);l.h=x/r.substeps;let R=Es(e.yaw)??ch(t.yaw),A=c(r.pitchLimit),E=Oe(yn(Es(e.pitch)??ch(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++)cM(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 lM=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:$w}),dM={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 fM=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,sS=t=>Es(t)??0;function pM(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 hM(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 mM(t){let e=t.onGround;nd(t),t.onGround&&!e&&(t.vz=0),t.c=Bw(t.yaw),t.s=Nw(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?pM(t):hM(t);let n=!t.onGround;n&&(t.vz-=t.gravity*t.h*.5),t.vx=yn(t.vx,-t.maxVelocity,t.maxVelocity),t.vy=yn(t.vy,-t.maxVelocity,t.maxVelocity),t.vz=yn(t.vz,-t.maxVelocity,t.maxVelocity),t.yaw=sS(t.yaw+t.spin*t.h),t.onGround?(tS(t,!0),nS(t)):sd(t,t.h),nd(t),n&&!t.onGround?t.vz-=t.gravity*t.h*.5:t.onGround&&(t.vz=0),t.x=kn(t.x),t.y=kn(t.y),t.z=kn(t.z),t.vx=kn(t.vx),t.vy=kn(t.vy),t.vz=kn(t.vz),t.spin=Oe(Math.fround(t.spin)),t.fuel=Oe(Math.fround(t.fuel))}function yM(t,e,n,r,s=yc,o=jw){let i=fh(s),a=xh(i),c=Math.fround,u=fo(t.mstate)&fM,l=c(r.height),d=Oe(-$n(e.moveX)),f=$n(e.moveY),h=fo(e.buttons),p=(h&r.jumpBit)!==0,y=Ql(n,uh),S=ch(t.yaw),b={w:i,p:o,r:c(r.radius),unit:ph(c(r.radius),qw),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?sS(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:dh,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++)mM(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 gM={defaults:Dv,ranges:Nv,fields:["x","y","yaw"],reads:[],world:!1,step:(t,e,n,r)=>Bv(t,e,n,r)},bM={defaults:Lv,ranges:Fv,fields:["x","y","z","vx","vy","vz","yaw","pitch","duck","mstate"],reads:["cap"],world:!0,step:(t,e,n,r,s,o)=>uM(t,e,n,r,s,o)},wM={defaults:lM,ranges:dM,fields:["x","y","z","vx","vy","vz","yaw","spin","fuel","mstate"],reads:["cap"],world:!0,step:(t,e,n,r,s,o)=>yM(t,e,n,r,s,o)},Vw=Object.freeze({[xr.TOPDOWN]:Object.freeze(gM),[xr.FIRSTPERSON]:Object.freeze(bM),[xr.VEHICLE]:Object.freeze(wM)});function bc(t){return typeof t=="string"&&Object.hasOwn(Vw,t)?Vw[t]:void 0}Qp();var SM=2,xM=350,_h={Players:"players",Nearest:"nearest"},oS=t=>typeof t=="string"&&t.length>0;function aS(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(oS):[];a.length!==0&&(r.add(o),n.push({region:o,urls:a}))}return n.length>0?n:(Array.isArray(e)?e.filter(oS):[]).map(s=>({region:s,urls:[s]}))}function _M(t,e){return Array.from({length:e},(n,r)=>t[r%t.length])}var Rh=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0;function RM(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];!Rh(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]}function iS(t,e,n={}){let r=RM(t,e),s=r.map(c=>c.pick),o=typeof n.region=="string"?r.find(c=>c.pick.region===n.region):void 0;if(o!==void 0)return{search:[],create:[o.pick]};if(n.rule===_h.Nearest)return{search:[],create:s};let i=Rh(n.maxPingMs)?n.maxPingMs:xM,a=r.filter(c=>c.ms!==null&&c.ms<=i).map(c=>c.pick);return{search:a.length>=2?a:[],create:s}}var yo={Capacity:"capacity",NextRegion:"next_region",Final:"final"},EM=new Set([503,4213]),kM=new Set([502,504,520,521,522,523,524,525,526,530]);function Eh(t){return typeof t!="number"||t<=0||kM.has(t)?yo.NextRegion:EM.has(t)?yo.Capacity:yo.Final}var id={Next:"next",Final:"final"};function cS(t){return Eh(t)===yo.Final?id.Final:id.Next}function uS(t,e,n){let r=t.refused+1;if(r>=SM&&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 AM(t,e){let n=Math.max(1,e.samples??uo.SAMPLES),r=t.map(o=>_M(o.urls,n)),s=await PM(r,e);return t.map((o,i)=>o.urls.map(a=>{let c;return r[i]?.forEach((u,l)=>{let d=s[i]?.[l];u===a&&Rh(d)&&(c=Math.min(c??Number.POSITIVE_INFINITY,d))}),c}))}async function lS(t,e={},n={}){return t.length<=1?iS(t,[],e):iS(t,await AM(t,n),e)}async function PM(t,e={}){let n=e.probe??Gp,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 Ph={MAX_MATCH_KEY_CHARS:32,MAX_CODE_CHARS:32,MAX_WORLDS:16},TM=522,Ah=(t,e,n)=>t>=e.charCodeAt(0)&&t<=n.charCodeAt(0),dS=t=>Ah(t,"a","z")||Ah(t,"0","9"),vM="._:-",MM="_-";function fS(t){if(typeof t!="string"||t.length===0||t.length>Ph.MAX_MATCH_KEY_CHARS)return!1;for(let e=0;e<t.length;e++)if(!dS(t.charCodeAt(e))&&(e===0||!vM.includes(t.charAt(e))))return!1;return!0}function pS(t){if(typeof t!="string"||t.length===0||t.length>Ph.MAX_CODE_CHARS)return!1;for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(!dS(n)&&!Ah(n,"A","Z")&&!MM.includes(t.charAt(e)))return!1}return!0}function CM(t){return t===void 0||t===""?"":fS(t)?t:null}var Zt={JoinOrCreate:"joinOrCreate",Create:"create",JoinById:"joinById",Join:"join"},kh={BadMatchKey:"bad_match_key",BadCode:"bad_code",Conflict:"conflict"};function hS(t){let e=t.matchKey??"";if(t.code!==void 0)return t.createPrivate===!0||e!==""?{refused:kh.Conflict}:pS(t.code)?{method:Zt.JoinById,roomId:t.code,options:{}}:{refused:kh.BadCode};let n=CM(e);if(n===null)return{refused:kh.BadMatchKey};let r=n===""?{}:{matchKey:n};return t.createPrivate===!0?{method:Zt.Create,options:{...r,private:!0}}:{method:Zt.JoinOrCreate,options:r}}function mS(t,e,n){return(t===pn.WRONG_REGION||t===TM)&&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"},yS={Final:"final",Budget:"budget"},OM=new Set([hn.GOING_AWAY,hn.NO_STATUS,hn.ABNORMAL,1011,1012,1013,hn.SERVER_SHUTDOWN,hn.FAILED_TO_RECONNECT,hn.MAY_TRY_RECONNECT]),IM=new Set([pn.BAD_OPTION,pn.NOT_ENTITLED,pn.FORBIDDEN,pn.MODULE_UNAVAILABLE,pn.PROTOCOL_UNSUPPORTED]);function gS(t){return OM.has(t)}function bS(t){let{attempt:e,elapsedMs:n,refusal:r,lostCode:s,closed:o,regions:i,jitter:a}=t;if(r!==null&&IM.has(r))return{stop:yS.Final};if(n>=Bi.budgetMs)return{stop:yS.Budget};let c=Bi.scheduleMs.length-1,l=Bi.scheduleMs[Math.min(e,c)]+Math.floor(a*Bi.jitterMs);if(e===0&&s!==hn.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 wS(t){return{...t.matchKey===""?{}:{matchKey:t.matchKey},successorOf:t.lostRoomId,...t.closed?{successorClosed:!0}:{}}}var ks={Draining:"draining",Rejoining:"rejoining",Rejoined:"rejoined"},ad="disconnect",DM=-1,NM=t=>new Promise(e=>setTimeout(e,t)),BM=t=>{let e=t!==null&&typeof t=="object"?t.code:void 0;return typeof e=="number"?e:null};function SS(t,e){let n=e.now??Date.now,r=e.random??Math.random,s=e.sleep??NM,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===ad||x===ks.Draining||x===ks.Rejoining||x===ks.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=bS({attempt:P,elapsedMs:n()-R,refusal:k,lostCode:b,closed:e.closed,regions:E,jitter:r()});if("stop"in M){d(ad,b,x);return}if(P+=1,d(ks.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(ks.Rejoined,{code:B.code,url:B.url});return}catch(B){k=BM(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(ks.Draining,{closesInMs:typeof R=="number"?R:DM})}),b.on(ad,(x,R)=>{b!==a||c||(gS(x)?h(x,R):d(ad,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 Qt={EXTRAPOLATE:"extrapolate",HOLD:"hold",INPUT_DECAY:"inputDecay"};var FM=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}),mU=Object.freeze(Object.keys(FM)),yU=Object.freeze(["worldExtent","maxSpeed"]),gU=Object.freeze(["worldExtent","maxSpeed","maxAngularSpeed"]);var xS=Object.freeze({[xr.FIRSTPERSON]:39.37,[xr.VEHICLE]:100}),bU=Object.freeze([10,15,20,30,60]);var _r={DEFAULT_REMOTE_PREDICT:Qt.EXTRAPOLATE,DEFAULT_REMOTE_DECAY_MS:50,MAX_REMOTE_DECAY_MS:1e3,DEFAULT_LEAD_MS:250,MIN_LEAD_MS:50,MAX_LEAD_MS:1e3},wU=Object.values(Qt);var _S=64,RS=64;var SU=Object.freeze({20:3,30:2,60:1,120:1});var zM=Object.freeze(["qx","qy","qz","qw","lvx","lvy","lvz","avx","avy","avz","sleep"]),UM=Object.freeze(["x","y","z",...zM]),cd={BITS:16,SPAN:65534,ORIENTATION:Object.freeze({min:-1,max:1}),VELOCITY:Object.freeze({min:-64,max:64})};function en(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)*cd.SPAN+.5)}var ES=250,kS=1,AS=100,PS=1;var Mh=[0,0,0,1];function Wn(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?Mh:[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function TS(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 Mh;let r=2*Math.atan2(n,t[3]);return TS(t[0]/n,t[1]/n,t[2]/n,e*r)}function vS(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 VM(t,e,n){if(t.sleep||!(n.tickHz>0))return 0;let s=((e-n.tickOrigin)*n.tickHz/1e3-t.tick)/n.tickHz,o=-kS/n.tickHz,i=ES/1e3;return s<o?o:s>i?i:s}function MS(t,e,n){let r=VM(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(Wn(TS(i/u,a/u,c/u,u*r),t.q))}}var Th={SPAWNED:"spawned",EPOCH:"epoch",DISTANCE:"distance"},vh=(t,e)=>({state:t,arrivedAt:e,dp:[0,0,0],dq:Mh});function Ch(t,e,n){let r=MS(t.state,e,n),s=e-t.arrivedAt,o=Math.exp(-(s<0?0:s)/AS),{dp:i}=t;return{p:[r.p[0]+i[0]*o,r.p[1]+i[1]*o,r.p[2]+i[2]*o],q:Wn(Fi(t.dq,o),r.q)}}function CS(t,e,n,r){if(t===null)return{drawing:vh(e,n),snap:Th.SPAWNED};if(e.epoch!==t.state.epoch)return{drawing:vh(e,n),snap:Th.EPOCH};let s=Ch(t,n,r),o=MS(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])>PS*r.lengthUnit)return{drawing:vh(e,n),snap:Th.DISTANCE};let a=Wn(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 OS(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 IS=2**32-1,wc=1e3,jr=t=>typeof t.t0=="number"&&t.t0>0;function Oh(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 Ih(t,e,n){return(t-e)*n/1e3}function ud(t,e,n){return e+t*1e3/n}var bn={Predicted:"predicted",Separate:"separate",Timeline:"timeline"},go={Shared:"shared",Mover:"mover"},qn={Shooter:"shooter",Platformer:"platformer",VehicleArena:"vehicle-arena",PhysicsSandbox:"physics-sandbox",Party:"party"},it={Stand:"stand",Slide:"slide",Bounce:"bounce",Ghost:"ghost"},Gn={Box:"box",Hull:"hull"},bo={Slide:"slide",Carry:"carry"};var Dh=(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=Dh(300,150,1),Wr=Dh(950,480,1),HM=Dh(600,null,.5),$M=.25,PU=Object.freeze({speed:300,step:150}),TU={policy:it.Bounce,stompMin:150,bounceSpeed:450,jumpBoost:150,slide:zi},DS={[qn.Shooter]:{character:xc(!1,$M,zi),vehicle:Sc(Wr),restitution:0,passes:16,vehicleOffWall:Wr,stopSpin:!1,drawing:bn.Separate,push:go.Mover,headFriction:bo.Slide},[qn.Platformer]:{character:xc(!0,null,zi),vehicle:Sc(Wr),restitution:0,passes:16,vehicleOffWall:Wr,stopSpin:!1,drawing:bn.Separate,push:go.Mover,headFriction:bo.Slide},[qn.VehicleArena]:{character:Sc(zi),vehicle:Sc(Wr),restitution:.6,passes:32,vehicleOffWall:HM,stopSpin:!0,drawing:bn.Predicted,push:go.Shared,headFriction:bo.Carry},[qn.PhysicsSandbox]:{character:xc(!0,null,zi),vehicle:xc(!0,null,Wr),restitution:.2,passes:16,vehicleOffWall:Wr,stopSpin:!1,drawing:bn.Separate,push:go.Shared,headFriction:bo.Carry},[qn.Party]:{character:xc(!0,null,zi),vehicle:Sc(Wr),restitution:.3,passes:16,vehicleOffWall:Wr,stopSpin:!1,drawing:bn.Separate,push:go.Shared,headFriction:bo.Slide}},vU=Object.freeze({supportCos:.7,entrySpeed:1,entryWindow:1/60,slop:.1,roofSkin:.01});var MU={[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 jM=[[-1,0,0],[1,0,0],[0,-1,0],[0,1,0],[0,0,1],[0,0,-1]],WM=[0,3,1,4,5,2];function qM(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 FS(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&&qM(c,(d-s.length)*28,f,e,n)}let u={count:i,boxCount:s.length,bounds:a,rampPlanes:c,skin:r},l=GM(u);return l===null?u:{...u,grid:l}}function NS(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 As(t,e,n,r){let s=Math.floor((t-e)/n);return s<0?0:s>r-1?r-1:s}function GM(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(!NS(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(!NS(n,A)){x(A);continue}let E=A*6,P=As(n[E]-1,s,c,u),k=As(n[E+3]+1,s,c,u),M=As(n[E+1]-1,o,c,l),B=As(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 BS(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 zS(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=As(e,o.x0,o.size,o.nx),a=n===e?i:As(n,o.x0,o.size,o.nx),c=As(r,o.y0,o.size,o.ny),u=s===r?c:As(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=BS(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=BS(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=jM[n],i=WM[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 ld=(t,e)=>e<t.boxCount?6:7;function Rc(t,e,n,r,s,o){let i=ld(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 US=(t,e,n)=>zS(t,e,e,n,n);function YM(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 KM(t,e,n,r,s,o){let i=ld(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 VS=(t,e)=>n=>n[2]>=e&&n[0]*t[0]+n[1]*t[1]+n[2]*t[2]>=e;function XM(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 KM(t,e,n,r,s,i);let a=0,c=o,u=Number.NEGATIVE_INFINITY,l=-1,d=ld(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(!YM(t,f,e,n,o.t))return;let h=XM(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=zS(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 dd(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 LS=[0,0,1],JM=[0,0,-1];function Nh(t,e,n,r,s){if(t===null)return LS;let o=Ec(t,[e,n,r],JM,s);return o.face===null||!(o.face[2]>0)?LS:[o.face[0],o.face[1],o.face[2]]}function ZM(t,e,n,r,s,o){let{count:i,skin:a}=t,c=US(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 QM(t,e,n,r,s){let o=null,i=ld(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&&ZM(t,e,n,r,s,[n+c*f,r+u*f,s+l*f])||(o=[c,u,l,f])}return o}function eC(t,e,n,r){let{count:s,skin:o}=t,i=US(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 QM(t,u,e,n,r)}return null}function HS(t,e,n){let{x:r,y:s,z:o}=e,i=0;for(let a=0;a<4;a++){let c=eC(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 So={Side:"side",Top:"top"},hd={Free:"free",LowerYields:"lower-yields",Pinned:"pinned"},tC={Stomp:"stomp"},Bh={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],xo=(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 nC(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 Nh(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=Nh(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=nC(t,e,n);if(r.kind===Gn.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 md=t=>Math.sqrt(t.hl*t.hl+t.hw*t.hw),fd=(t,e,n)=>t.hl*Math.abs(t.c*e+t.s*n)+t.hw*Math.abs(t.c*n-t.s*e);function rC(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=md(t)+md(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=fd(t,f,h)+fd(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=>fd(t,d[0],d[1])+fd(e,d[0],d[1])}}function Fh(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 sC(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=Fh(t.c,t.s,s),d=Fh(e.c,e.s,s),f=xo(s,l),h=xo(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 oC=1e-6;function $S(t){let e=Fh(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,xo(t.up,e),t.up],half:[t.hl,t.hw,n]}}function iC(t,e,n){let r=$S(t),s=$S(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=xo(f,h),y=Math.sqrt(Fe(p,p));y>oC&&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 zh(t,e){let n=md(t)+md(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 rC(t,e);if(t.up[0]===e.up[0]&&t.up[1]===e.up[1]&&t.up[2]===e.up[2])return sC(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:iC(t,e,[o[0]/i,o[1]/i,o[2]/i])}var yd=(t,e,n)=>-((e.vx-t.vx)*n[0]+(e.vy-t.vy)*n[1]+((e.vz??0)-(t.vz??0))*n[2]);function aC(t,e,n,r){let s=t.across.depth/Math.max(yd(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(yd(e.b,n.b,t.side.n),r.entrySpeed);return{across:s<a||s===a&&t.across.depth<t.side.depth,landed:i}}function jS(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 _o(t,e,n){if(t.pairs.length===0)return t.top;let r=jS(e),s=jS(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 gd(t,e,n){let r=zh(t,e);if(r===null)return cC(t,e,n);let s=aC(r,t,e,n);if(!s.across){let l=Fe(r.d,r.plane)>=0;return{contact:{kind:So.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?So.Top:So.Side,n:o,depth:r.across.depth,upperIsB:i},g:r}}function cC(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?zh(t,s(e)):zh(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-yd(u,c,i)>n.entrySpeed?null:{contact:{kind:So.Top,n:o.across.n,depth:o.across.depth-n.groundTrace,upperIsB:r},g:o}}function uC(t,e,n,r){return bd(t,e,n)?null:gd(qr(t,n,r),qr(e,n,r),n)?.contact??null}function lC(t){let e=t.shape;return e.kind===Gn.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 bd(t,e,n){let r=2*lC(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},Gr=t=>[t.x,t.y,t.z],dC=.7,fC=.5,WS=.5;function Ui(t,e,n,r,s,o){let i=Ec(t,e,n,r,Fe(n,o)<-fC?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=pC(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 pC(t,e,n){if(Fe(t,n)>=dC){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>=WS?[c[0]/u,c[1]/u,c[2]/u]:null}let r=xo(t,n),s=Math.hypot(r[0],r[1],r[2]),o=s>0?Fe(r,e)/s:0;if(!(Math.abs(o)>=WS))return null;let i=o>0?1/s:-1/s;return[r[0]*i,r[1]*i,r[2]*i]}function qS(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 hC(t,e,n=.5){let r=Math.min(e,1-Math.min(t,n));return[Math.min(t,1-r),r]}function mC(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 hC(l.sep/r,d.sep/r,u)}function ZS(t,e,n,r){if(r.push!==go.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 Uh(t,e,n,r,s,o){let[i,a]=mC(t.b,e.b,n,r,o.world,wo(t,s),wo(e,s),t.support,e.support,ZS(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,wo(e,s),e.support).sep/r]:e.b.id===o.fixed?[o.world===null?1:Ui(o.world,Gr(t.b),ft(n),r,wo(t,s),t.support).sep/r,0]:[i,a]}var wo=(t,e)=>VS(t.support,e.supportCos);function yC(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]=Uh(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]=Uh(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 GS(t,e){t.x+=e[0],t.y+=e[1],e[2]!==0&&(t.z+=e[2])}function gC(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,wo(t,i),t.support),h=l===null?{d:n,straight:r,slide:null,cos:1,sep:r}:Ui(l,Gr(u),n,r,wo(e,i),e.support);GS(c,qS(f,r*s)),GS(u,qS(h,r*o))}function bC(t,e,n,r,s,o,i){let a=JS(s),[c,u]=[t.b,e.b],[l,d]=Uh(t,e,n.n,n.depth,s,o),f=l+d<1?yC(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=ZS(c,u,p,s),k=2*E*P,M=2*E*(1-P);return gC(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 QS(t,e){let n=e?t.side.n:ft(t.side.n),r=e?t.d:ft(t.d),s=xo(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 YS=(t,e,n)=>t.half(n)-Fe(e?t.d:ft(t.d),n);function wC(t,e,n,r,s){let o=[];for(let i of n){if(i===t.b||i===e||bd(t.b,i,r)||_o(r,t.b,i).policy===it.Ghost)continue;let a=gd(t,qr(i,r,s),r);a!==null&&a.contact.kind===So.Top&&!a.contact.upperIsB&&o.push(a.g)}return o}function SC(t,e,n){if(n.length===0)return QS(t,e);let r=e?t.side.n:ft(t.side.n),s=xo(t.plane,r);return[r,ft(r),s,ft(s)].map(i=>({w:i,move:n.reduce((a,c)=>Math.max(a,YS(c,!1,i)),YS(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 KS=(t,e,n,r)=>n.move<=0||dd(t,Gr(e.b),n.w,n.move,wo(e,r))>=n.move;function Lh(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 XS(t,e){if(!(e<t.speed))return 0;let n=t.speed-e;return t.step===null?n:Math.min(n,t.step)}function pd(t,e,n,r,s,o,i,a){let[c,u]=[t.b,e.b],l=JS(o),d=QS(n,r),f=SC(n,r,wC(t,u,a,o,i)).find(S=>KS(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=XS(s,S);return Lh(c,f.w,b*s.share,l),s.share!==1&&Lh(u,f.w,-b*(1-s.share),l),{j:b,way:hd.Free,w:f.w}}let h=d.map(S=>({w:ft(S.w),move:S.move})).find(S=>KS(i.world,e,S,o));if(h===void 0)return{j:0,way:hd.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=XS(s,p);return Lh(u,h.w,y,l),{j:y,way:hd.LowerYields,w:h.w}}function xC(t,e,n,r,s,o,i,a){let c=r+i.roofSkin;if(!(c>0))return;let u=t.id===a.fixed?0:dd(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:dd(a.world,Gr(e),ft(n),c-u);e.x-=n[0]*l,e.y-=n[1]*l,e.z-=n[2]*l}function _C(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 RC(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 Vh(t,e,n){let r=t.x-e.x,s=t.y-e.y,o=n.shape;if(o.kind===Gn.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 EC(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 kC=100,Ps={Stand:"stand",Release:"release",Slide:"slide"};function ex(t,e,n,r){if(n.center===null)return Ps.Stand;let s=Vh(t,e,r);return s<=n.center?Ps.Stand:(e.vz??0)-(t.vz??0)>kC?Ps.Slide:EC(t,e,n.ride)>=(n.slide.step??n.slide.speed)/2?Ps.Release:s>1?Ps.Slide:Ps.Stand}var tx=(t,e,n,r)=>n.policy===it.Stand&&ex(t,e,n,r)===Ps.Stand;function AC(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=yd(d,l,f),p=s.policy===it.Stand&&ex(l,d,s,o)===Ps.Slide;return xC(l,d,f,n.depth,r,u.top,o,i),_C(l,d,f),u.support[2]<o.supportCos?pd(c,u,r,n.upperIsB,o.offWall,o,i,a):s.policy===it.Stand?p?pd(c,u,r,n.upperIsB,s.slide,o,i,a):Bh:s.policy===it.Slide?pd(c,u,r,n.upperIsB,s,o,i,a):s.policy===it.Bounce&&h>=s.stompMin?(RC(l,f,s.bounceSpeed+(l.jump?s.jumpBoost:0)),i.onContact?.(l,d,tC.Stomp),Bh):s.policy===it.Bounce?pd(c,u,r,n.upperIsB,s.slide,o,i,a):Bh}function nx(t,e,n,r,s=!1,o=[]){let i=_o(n,t,e);if(i.policy===it.Ghost||bd(t,e,n))return null;let a=qr(t,n,r),c=qr(e,n,r),u=gd(a,c,n);return u===null?null:rx(a,c,u,i,n,r,s,o)}function rx(t,e,n,r,s,o,i,a){let{contact:c,g:u}=n;return c.kind===So.Side?{...c,...bC(t,e,c,u,s,o,i),way:null,w:null}:{...c,...AC(t,e,c,u,r,s,o,a)}}function PC(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?nx(t,e,r,s,a,i):c}var sx=(t,e)=>t!==null&&(t.depth>e.slop||t.kind===So.Top&&t.depth>0),TC=t=>({moves:new Int32Array(t),still:new Int32Array(t*t).fill(-1)});function vC(t,e,n,r,s){if(bd(t,e,n))return null;let o=_o(n,t,e);if(o.policy===it.Ghost)return null;let i=qr(t,n,r),a=qr(e,n,r),c=gd(i,a,n);return c===null||!sx(c.contact,n)?null:rx(i,a,c,o,n,r,!1,s)}function MC(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=vC(d,f,n,r,t);else{if(e>0&&!sx(uC(d,f,n,r),n))continue;p=PC(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===hd.Pinned&&(o.pinned+=1),s.onPair?.(d,f,p)}return a}function CC(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?TC(t.length):null;for(let i=0;i<e.passes&&MC(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=HS(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 Hh=(t,e)=>(n,r)=>{nx(n,r,t,e)},ox=(t,e)=>n=>{CC(n,t,e)};function ix(t){return t.top.policy===it.Stand||t.pairs.some(e=>e.top.policy===it.Stand)}function OC(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===Gn.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 ax=t=>t.shape.kind===Gn.Hull?t.shape.height:t.shape.top,cx=2;function IC(t,e,n,r){let s=_o(n,t,e);if(s.policy!==it.Stand)return!1;let o=ax(n);return t.z<e.z+o-n.groundTrace||t.z>e.z+2*o||!(Vh(t,e,n)<cx)||qr(e,n,r).support[2]<n.supportCos?!1:tx(t,e,s,n)}var DC=t=>cx*(t.shape.kind===Gn.Hull?t.shape.radius:Math.hypot(t.shape.length,t.shape.width)/2);function NC(t,e,n=0){let r=ax(e),s=DC(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 NC(t,e)?t.map(s=>{let o=[],i=[];for(let a of t)a===s||!IC(s,a,e,n)||(o.push(OC(a,e,r)),i.push(a.id));return{solids:o,lowers:i}}):t.map(()=>({solids:[],lowers:[]}))}function $h(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 ux(t,e,n,r){let s=[];for(let o of n){let[i,a]=[o.p[0],o.p[1]],c=$h(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 Ro={Box:"box",Disc:"disc"},lx={PingPong:"pingpong",Loop:"loop"},dx={Linear:"linear",Smooth:"smooth"},fx={All:"all",None:"none"},px=Object.freeze({platforms:Object.freeze([]),bodies:!1});var HU=2**24;var $U=2*Math.PI;var yx=2*Math.PI,Nt=Math.fround,gx=(t,e)=>(t%e+e)%e;function BC(t,e,n,r,s){if(s===dx.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 LC(t,e){let n=t.legs.length,r=t.mode===lx.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 BC(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 FC(t,e,n,r){return t.called?r===void 0||n<r||n-r>=e.period?0:n-r:gx(n+e.phase,e.period)}function Ts(t,e,n){let r=t.path===null?t.at:LC(t.path,FC(t,t.path,e,n)),s=t.spin;return s===null?{c:r,yaw:0}:{c:r,yaw:Nt(s.dir*(yx*gx(e+s.phase,s.period)/s.period))}}function hx(t,e,n){return t.platforms.map(r=>Ts(r,e,n?.get(r.id)))}var jh=t=>t.spin===null?0:t.spin.dir*yx/t.spin.period;function Sd(t,e,n,r,s){let o=Ts(t,n,s),i=Ts(t,n+1,s),a=jh(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 wd(t,e){return t.platforms.map((n,r)=>{let{c:s,yaw:o}=e[r],i=n.shape;if(i.kind===Ro.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 bx=4;function xd(t,e,n){return{now:wd(t,hx(t,e,n)),next:wd(t,hx(t,e+1,n))}}var wx=(t,e)=>t?.get(e.id);function mx(t,e){t.x=Nt(e.x),t.y=Nt(e.y),t.z=Nt(e.z)}function zC(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?_o(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 UC(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 Sd(h,l,s,o,wx(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>=bx?[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 Sx(t,e,n,r,s,o,i,a=xd(t,n,s),c){let{now:u,next:l}=a,d=e.map(b=>({...b})),{bases:f,on:h}=zC(t,d,u,o,c),p=UC(t,d,f,h,n,r,s),y=[],S=[];return e.forEach((b,x)=>{let R=f[x],A=p[x]??null;A!==null&&(mx(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=Sd(E,b,n,r,wx(s,E)),M=o.pushOut({...b,x:k.x,y:k.y,z:k.z},l);mx(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 xx(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>=bx)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 VC(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 _x(t,e,n,r,s,o,i=xd(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(VC(c,l,h,i,o,a))return}else if(d<0||t.platforms[d].impart!==fx.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 HC(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 Ax(t,e,n,r){if(!t)return null;let s;try{s=JSON.parse(t)}catch{return null}if(!Pc(s)||s.name!==xr.FIRSTPERSON&&s.name!==xr.VEHICLE)return null;let o=HC(s.lifts)?s.lifts:null;if(o===null&&n===void 0)return null;let i=Ni(s.name,s.params);return{policy:o??px,ops:rS(s.name,i,e),vehicle:s.name===xr.VEHICLE,heads:n,tickHz:r}}function Px(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 $C=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=xd(e,n,r),a={solids:i,next:gc(i.next)};return this.kept.size>=$C&&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=Sx(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 Tx(t,e){e.report=xx(e.seats,e.report,t.tickHz)}function vx(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){_x(t.policy,e.seats,e.report,e.tick,n,t.ops,e.solids.next,t.heads)}function jC(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=Ts(s,o,r?.get(s.id)),a=Ts(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},wd(t.policy,jC(t.policy,n,r)))}function Wh(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 Mx(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 qh(t,e,n,r){let s=t.platforms[e];if(s===void 0)return 0;let o=s.shape.kind===Ro.Box?s.shape.half[2]:s.shape.half;return Tc(t,e,n,r).c[2]+o}var Rx=["x","y","z"],Ex=["vx","vy","vz"];function Cx(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 Rx)s[l]=c[l];t.vehicle&&(s.yaw=c.yaw),r(s,Mc(u,c.id));for(let l of[...Rx,...Ex])c[l]=s[l]??0;Cc(a,u,e);for(let l of Ex)s[l]=c[l]}var Ic=t=>`lift.${t}`,kx=16;function WC(t){let e=t.surface===null?{}:{friction:0};if(t.shape.kind===Ro.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<kx;o++){let[i,a]=Ut(2*Math.PI*o/kx);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 _d(t,e,n){let r=Ts(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 Ox(t,e,n){return{key:Ic(t.id),type:"kinematic",pose:_d(t,e,n),colliders:[WC(t)]}}var qC=20;function GC(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===Ro.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 YC=(t,e)=>e+(t.shape.kind===Ro.Disc?t.shape.half:t.shape.half[2]);function Gh(t,e,n,r){let s=t.platforms.filter(i=>i.surface!==null),o=s.map(i=>Ts(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-YC(l,f.c[2]);return h>0&&h<=r&&GC(l,f,a,c)})}}function Ix(t,e,n,r,s,o){let i=Gh(t,e,n,o),a=Math.min(1,qC/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=Sd(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 Eo=15,KC=65535;var XC=Object.values(Qt),Dx=(t,e,n)=>typeof t=="number"&&Number.isFinite(t)&&t>=e&&t<=n,Yr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Nx=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)||!Nx(r)||!Nx(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=XC.includes(e.remotePredict)?e.remotePredict:_r.DEFAULT_REMOTE_PREDICT,u=e.remoteDecayMs,l=Dx(u,0,_r.MAX_REMOTE_DECAY_MS)?u:_r.DEFAULT_REMOTE_DECAY_MS,d=e.leadMs,f=Dx(d,_r.MIN_LEAD_MS,_r.MAX_LEAD_MS)?d:_r.DEFAULT_LEAD_MS;return{world:e.world,keyframeTicks:n,maxLinear:r,maxAngular:s,presetBody:a,remotePredict:c,remoteDecayMs:l,leadMs:f}}function Yh(t){return Math.fround(Math.fround(t.dt)/t.substeps)}function JC(t,e){let n=Math.floor(t/e+.5);return Number.isNaN(n)||n<0?0:Math.min(n,KC)}var Dc=cd.ORIENTATION,vs=cd.VELOCITY,Hi=t=>t===0?0:t;function Fx(t,e,n){e[n]=Hi(t.x),e[n+1]=Hi(t.y),e[n+2]=Hi(t.z),e[n+3]=en(t.qx,Dc),e[n+4]=en(t.qy,Dc),e[n+5]=en(t.qz,Dc),e[n+6]=en(t.qw,Dc),e[n+7]=en(t.lvx,vs),e[n+8]=en(t.lvy,vs),e[n+9]=en(t.lvz,vs),e[n+10]=en(t.avx,vs),e[n+11]=en(t.avy,vs),e[n+12]=en(t.avz,vs),e[n+13]=t.sleep?1:0,e[n+14]=t.rest}function Kh(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]=en(t[e+i],Dc);for(let i=7;i<10;i++)s[o+i]=en(t[e+i]/n,vs);for(let i=10;i<13;i++)s[o+i]=en(t[e+i],vs);s[o+13]=t[e+13]===1?1:0,s[o+14]=JC(t[e+14],r)}function zx(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 Kh(r,0,e,n,s,0),s}function Bx(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 Ux(t,e,n,r=_S,s=RS){let o=Bx(t,r*n),i=Bx(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 cV=16*1024;function Vx(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 Hx=.5,Rd=t=>{if(!Array.isArray(t)||t.length!==3)return 0;let[e,n,r]=t;return Math.sqrt(e*e+n*n+r*r)},Lx=t=>Array.isArray(t)?t.reduce((e,n)=>Math.max(e,Rd(n)),0):0;function ZC(t){switch(t.kind){case"box":return Rd(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 Lx(t.points);case"trimesh":return Lx(t.vertices);case"heightfield":return Rd(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)?Rd(r.offset.p):0;n=Math.max(n,s+ZC(r.shape))}return n}function $x(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 QC(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 kd(t,e,n,r){let s=QC(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 eO(t,e){let n=Math.max(t,0)/e;return(1+n)*Math.exp(-n)}function Ad(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 Ed=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=Wn(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=eO(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:Wn(Fi(r.dq,s),e.q)}}};function Pd(t){return typeof t=="string"&&Rt.PLAYER_KINDS.includes(t)?Rt.SNAP_PLAYER_METRES:Rt.SNAP_OTHER_METRES}function Yx(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 tO=.1,nO=30,vd={desktop:4,mobile:5};function Kx(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:e}var em=Object.freeze([128,64,32]),Xh=60,rO=20,sO=2,jx=.5,oO=500,iO=4;function aO(t,e){for(let n=t+1;n<em.length;n++)if(em[n]<e)return n;return null}function Wx(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 qx=500,cO=.02,uO=200,We={ON:"on",OFF:"off",LOADING:"loading",UNAVAILABLE:"unavailable",MISMATCH:"mismatch",SELF_TEST:"self_test",DIVERGED:"diverged",CPU:"cpu"},lO=600;function Gx(t,e){return[Ad(t.dp[0],t.dv[0],e,t.tau),Ad(t.dp[1],t.dv[1],e,t.tau),Ad(t.dp[2],t.dv[2],e,t.tau)]}var Lc=[0,0,0,1],dO=[32767,32767,32767,65534,32767,32767,32767,32767,32767,32767,0,0],fO=[32767,32767,32767,32767,32767,32767,0,0],pO=t=>Math.floor((t+1)/2*65534+.5),ji=[0,0,0],Wi=(t,e)=>t<e?-1:t>e?1:0,hO=(t,e)=>{for(let n=0;n<Eo;n++)if(!Object.is(t[n],e[n]))return!1;return!0},Td=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=Yh(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===Qt.INPUT_DECAY||n.desc.remotePredict===Qt.HOLD;this.remoteStep=s?n.remoteStep:void 0,this.seatPose=n.seatPose,this.contactPass=n.contactPass,this.budgetMs=n.budgetMs??vd.desktop,this.clock=n.clock??(()=>performance.now()),this.hashesKept=n.hashesKept??lO,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<oO||!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=yO(r.q,r.av,s),c=Math.max(n-r.since,0),u=Gx(r,c);return{p:[i[0]+u[0][0],i[1]+u[1][0],i[2]+u[2][0]],q:Wn(Fi(r.dq,Math.exp(-c/r.tau)),a)}}choose(e){let n=Hx*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=$x(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=em[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=>mO(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&&hO(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===Jh(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>qx&&this.canary.splice(0,this.canary.length-qx),this.canary.length<uO)return;this.canary.filter(Boolean).length/this.canary.length>cO&&this.stop(We.DIVERGED)}judgeBudget(e){if(this.costs.push(e),this.costs.length>Xh&&this.costs.splice(0,this.costs.length-Xh),this.costs.length<rO)return;let n=Wx(this.costs,.5),r=Wx(this.costs,.9);if(n>this.budgetMs||r>sO*this.budgetMs){this.costs=[];let i=aO(this.setSize,this.chosenCount);if(i!==null){this.setSize=i;return}this.fallBack();return}this.costs.length>=Xh&&r<=jx*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<=jx*this.budgetMs?this.calmProbes+1:0,this.calmProbes<iO){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&&Jh(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:Jh(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<Eo;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),...dO);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(Ox(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}=_d(o,n+1,r.starts);return[Ic(o.id),[...i,...a.map(pO),...fO]]})}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?gO(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),_d(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===Qt.HOLD;i(u,h?e.input:kd(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:Gh(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 Ix(a.policy,n,a.starts,this.tickHz,l,2*u[2]))e.setVelocity(d.key,d.v);if(o!==null)for(let d of ux(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&&$h(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*Eo,c=[s[a+7],s[a+8],s[a+9]],u=[s[a+10],s[a+11],s[a+12]],l=Ux(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,zx(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)>nO)return this.ruledClock={at:e,tick:s},s;let i=(e-o.at)/1e3*this.tickHz,a=o.tick+i,c=tO*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*Eo,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=Gx(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:Wn(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 Pd(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=Wn(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)})}}},Jh=t=>t===null?"":JSON.stringify(t);function mO(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 yO(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(Wn([e[0]*o,e[1]*o,e[2]*o,Math.cos(s)],t))}function gO(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 Zh={contract:"1.0",dt:1/60,substeps:1,gravity:[0,0,-9.81],upAxis:"z",lengthUnit:1},Qh=12;function bO(){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 Xx(t){let n=[t.World.create(Zh),t.World.create(Zh)].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 bO())if(!r.spawn(l).ok||!s.spawn(l).ok)return!1;for(let l=0;l<Qh;l++)r.step();s.canonicalize({});for(let l=0;l<Qh;l++)s.step();if(!r.canonicalize({quantize:!0}).ok)return!1;let{keys:i,data:a}=r.exportChanged(r.tick,{rest:!0}),c=[],u=Yh(Zh);for(let l=0;l<i.length;l++)Kh(a,l*Eo,1,u,c,l*Eo);if(i.length!==3||!s.importWire(i,c).ok||!s.canonicalize({quantize:!0}).ok)return!1;for(let l=0;l<Qh;l++)if(r.step(),s.step(),r.stateHash()!==s.stateHash())return!1;return!0}finally{for(let r of n)r.free()}}var yV=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 ko=["x","y","z","vx","vy","vz","yaw","spin"],wO=(t,e)=>t.body.id<e.body.id?-1:t.body.id>e.body.id?1:0,Md=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(wO)});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 ko){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 Ao(t,e,n){let r={x:n.x,y:n.y,z:n.z};for(let s=0;s<SO;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&&Cd(t,e,n,r)<=xO))break}return Cd(t,e,n,r)>t_?kO(t,e,n,r):r}var SO=8,xO=.01,t_=.001,_O=30,RO=8,EO=1;function kO(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:n_(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=>Cd(t,e,n,u(h))>0,d=a,f=a+Math.max(EO,a);for(let h=0;h<RO&&l(f);h++)d=f,f=a+(f-a)*2;if(l(f))return r;for(let h=0;h<_O;h++){let p=(d+f)/2;l(p)?d=p:f=p}return u(f)}function n_(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 Cd(t,e,n,r){let s=n_(t,e,n,r);return Math.hypot(s.x,s.y,s.z)}var AO=3*Math.PI,PO=Math.PI/2,TO=.05,vO=8,Jx=16,MO=30,CO=8,r_=(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 rm(t,e,n,r){let s=r_(e,n,r),o=Ao(t,e,s);return Math.hypot(o.x-s.x,o.y-s.y,o.z-s.z)}function Od(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(rm(t,e,n,u)>Math.min(TO*i,vO))return!0}return!1}function nm(t,e,n,r,s,o){let i=Math.cos(r),a=Math.sin(r),c=d=>rm(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<CO&&c(l);d++)u=l,l*=2;for(let d=0;d<MO;d++){let f=(u+l)/2;c(f)?u=f:l=f}return l}var Zx=4,OO=20;function IO(t,e,n){let r=n.z>=e.z?1:-1,s=a=>rm(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(Zx))return n;let o=0,i=Zx;for(let a=0;a<OO;a++){let c=(o+i)/2;s(c)?o=c:i=c}return{...n,z:n.z+r*i}}var Qx=2*Math.PI,DO=t=>t-Qx*Math.floor((t+Math.PI)/Qx);function e_(t,e,n,r,s,o=!1){let i=IO(t,e,n),a=Ao(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(NO(t,e,i,j),!0);if(r===void 0||!(o||Od(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=nm(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=DO(Math.atan2(c.dy,c.dx)-S),x=p>0?PO*Math.hypot(l-r.bx,d-r.by)/p:0,R=Math.max(x,AO*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,nm(t,e,i,P,B,Math.max(p,y)));return h({dx:K*Math.cos(P),dy:K*Math.sin(P),dz:B})}function NO(t,e,n,r){let s=r_(e,n,r);return Cd(t,e,s,s)>t_?qi(e,Ao(t,e,s)):r}function BO(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(Od(t,l,n,d(o),d(a)))return!0}return!1}var Fc=(t,e)=>t<e?`${t}\0${e}`:`${e}\0${t}`,LO=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}),Id=(t,e)=>t.x===e.x&&t.y===e.y&&t.z===e.z,FO=720,zO=.1,UO=24,VO=8,HO=64;function sm(t,e,n,r,s){return!Id(Ao(t,Kr(e,r),Kr(n,s)),s)}var s_=(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 $O(t,e,n,r,s,o,i){let a=l=>sm(t,e,n,...s_(r,s,o,l));if(!a(i))return i;let c=i,u=i+HO;for(let l=0;l<VO&&a(u);l++)c=u,u=i+(u-i)*2;for(let l=0;l<UO;l++){let d=(c+u)/2;a(d)?c=d:u=d}return u}function tm(t,e){let n=Math.hypot(t,e);return n>0?{nx:t/n,ny:e/n}:null}function jO(t,e,n,r,s,o){let i=Ao(t,Kr(e,r),Kr(n,s)),a=(o===void 0?null:tm(o.dx,o.dy))??tm(s.x-r.x,s.y-r.y),c=tm(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 WO(t,e,n,r){let s=r.get(e.id),o=r.get(n.id),i=Ao(t,Kr(e,s),Kr(n,o));if(Id(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 o_(t,e,n,r){return r.nx*(n.x-e.x)+r.ny*(n.y-e.y)<0&&!sm(t,e,n,e,n)}var i_=(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 qO(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?!sm(t,e,n,e,n):o_(t,e,n,y))return WO(t,e,n,r);l=y??jO(t,e,n,c,u,o),s.set(a,l);let S=y===void 0?0:y.push-FO*Math.min(i,zO);d=Math.max(0,S-i_(e,n,c,u,l))}let f=$O(t,e,n,c,u,l,d);if(f<=0)return!1;let[h,p]=s_(c,u,l,f);return r.set(e.id,h),r.set(n.id,p),!0}function GO(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(!Od(t,u,l,s,c))return;let d=Math.atan2(s.dy,s.dx),f=nm(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 YO(t,e,n,r,s){let o=Kr(n,r),i=Ao(t,e,o);return Id(i,r)?r:Od(t,e,o,qi(e,s),qi(e,i))?s:i}function KO(t){return t.flatMap((e,n)=>t.slice(n+1).map(r=>[e,r]))}function a_(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=e_(t,e,h,p,s),b=p?.held===!0&&!y.side.held&&BO(t,e,h,o,r,p,y)?e_(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=KO(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||o_(t,h,p,y.pair))&&GO(t,h,p,i,y,c)}let d=new Map;for(let h=0;;h++){for(let y of o)i.set(y.id,YO(t,e,y,i.get(y.id),a.get(y.id)));if(h===LO)break;let p=!1;for(let[y,S]of u){let b=l(y,S);p=qO(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:!Id(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:i_(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 XO(t){if(!Yi(t)||typeof t.preset!="string"||!Object.hasOwn(DS,t.preset))return!1;let e=t.shape,n=t.hull;return!Yi(e)||e.kind!==Gn.Box&&e.kind!==Gn.Hull||!Yi(n)?!1:Yi(t.top)&&Yi(t.offWall)&&Array.isArray(t.pairs)&&typeof t.passes=="number"}function c_(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(!XO(r))return null;let s={world:FS(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=Hh(r,{...s,fixed:a});return o.set(a,u),u};return{policy:r,rule:Hh(r,s),pass:ox(r,s),env:s,drawRule:i}}var Dd=[.5,1,5,20],JO=new Set(["x","y","z"]),ZO=new Set(["mstate","cap","spin","fuel"]),u_=2*Math.PI;function l_(t,e,n){let r=0,s=0;return t.forEach((o,i)=>{if(ZO.has(o))return;let a=(n[i]??0)-(e[i]??0);JO.has(o)?r+=a*a:s=Math.max(s,Math.abs(o==="yaw"?a-u_*Math.floor((a+Math.PI)/u_):a))}),{place:Math.sqrt(r),state:s}}var d_=(t,e)=>t>.05*e;function f_(t,e){let n=Dd.findIndex(r=>t<r*e);return n<0?Dd.length:n}function p_(t){return Number.isSafeInteger(t)?(t%65536+65536)%65536:0}var S_=500;function QO(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=Ms(s.yaw-o.yaw),f=i===void 0?0:d-Ms(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:Ms(u(s.yaw,d,f))}}function eI(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+Ms(i.yaw-o.yaw)*a}}var h_=8,tI=3,om=.5,im=(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,m_=2*Math.PI,Ms=t=>t-m_*Math.floor((t+Math.PI)/m_),y_=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)}),g_=(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}:{}}),b_=(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)}),w_=(t,e)=>ko.every(n=>t[n]===e[n]),Bd=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 QO(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+Ms(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-om,r),i=this.poseAt(e,n+om,r);if(s===void 0||o===void 0||i===void 0||r===null)return;let a=r.tickHz/1e3/(2*om);return{pose:s,rate:{vx:(i.x-o.x)*a,vy:(i.y-o.y)*a,vz:(i.z-o.z)*a,vyaw:Ms(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=eI(r,n);if(o===void 0||i===void 0||a===void 0)return;let c={...g_(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<=h_;l++){let d=l/h_*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(im),o=new Map([[e,new Map(s.map(a=>[a.id,y_(a.body)]))]]);this.serial+=1,this.current!==null&&(this.recent=[this.current,...this.recent].slice(0,tI));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=>g_(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(im);if(this.contactPass(f),e.seats.forEach((p,y)=>{let S=l[y];for(let b of ko)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 ko){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,y_(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))}Tx(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=>b_(c.id,c.body));s!==void 0&&o.push(b_(s.id,s)),o.sort(im);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===Qt.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===Qt.INPUT_DECAY?kd(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),!w_(r,e)||!w_(s,n)}};function x_(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 __(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 nI=.01;function R_(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<nI;return{dx:t.dx*n,dy:t.dy*n,dz:t.dz*n,done:r}}var rI=t=>t?Rt.SEAT_CONTACT_TAU_MS:Rt.SEAT_TAU_MS;function Nd(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 E_(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=rI(i),f=Math.max(0,o),[h,p]=Nd(t.dx,t.vx,f,d),[y,S]=Nd(t.dy,t.vy,f,d),[b,x]=Nd(t.dz,t.vz,f,d),[R,A]=Nd(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:Ms(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?sI(t,B)||t.stopFound&&t.stillMs>0:t.stopFound,L=oI(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:Ms(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 iI({...L,...se,...v,...u},s.rate,f)}function sI(t,e){return e.vx*t.hx+e.vy*t.hy+e.vz*t.hz>Rt.SEAT_MOVING_UNITS_PER_MS}function oI(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 iI(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 aI(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 k_=1e3/60,cI=k_,uI=0,vt=t=>typeof t=="number"&&Number.isFinite(t)?t:uI;function A_(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(!Xx(x))return l(We.SELF_TEST);let R=Nc(c.physDesc);if(R===null)return l(We.MISMATCH);let A=t.staticWorld();n=new Td(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:Vx(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)};Fx(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:aI(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>k_&&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>=cI){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 Ld={min:-1,max:1,bits:16,mode:"clamp"},Ki={min:-64,max:64,bits:16,mode:"clamp"},P_=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"),lI=1,T_=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(Ld).optional()),qy:t(Y.quantized(Ld).optional()),qz:t(Y.quantized(Ld).optional()),qw:t(Y.quantized(Ld).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())}),dI=zt(T_(t=>t),"AuthorityEntity"),fI=zt(T_(t=>t.view(lI)),"AuthorityEntity"),pI=zt({type:Y.string().default(""),kind:Y.string().default(""),colliders:Y.string().default(""),desc:Y.string().optional()},"AuthorityBody"),hI=zt({data:Y.string().default("")},"AuthorityShape"),mI=zt({desc:Y.string().default(""),motor:Y.string().default("")},"AuthorityJoint"),yI=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"),v_={players:Y.map(yI),entities:Y.map(dI),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(pI).optional(),physDesc:Y.string().optional(),keyframe:Y.number().optional(),shapes:Y.map(hI).optional(),joints:Y.map(mI).optional(),lifts:Y.string().optional(),matchKey:Y.string().optional()},FV=zt(v_,"AuthorityRoomState"),zV=zt({...v_,entities:Y.map(fI).view()},"AuthorityRoomState");var gI=(t,e)=>t+Math.atan2(Math.sin(e-t),Math.cos(e-t)),bI=(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}),Fd=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?gI(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:bI(a.pose,c.pose,(n-a.t)/(c.t-a.t))}forget(e){this.rings.delete(e)}};var gt={On:"on",Off:"off"};var jV={[qn.Shooter]:{repeat:gt.On},[qn.Platformer]:{repeat:gt.On},[qn.VehicleArena]:{repeat:gt.Off},[qn.PhysicsSandbox]:{repeat:gt.On},[qn.Party]:{repeat:gt.On}},WV={repeat:gt.On};var M_=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);function C_(t){let e;try{e=JSON.parse(t)}catch{return gt.On}let n=M_(e)?e.inputs:void 0;return M_(n)&&n.repeat===gt.Off?gt.Off:gt.On}var O_={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},YV={idleSeatS:O_.IDLE_SEAT_S,maxRoomAgeS:O_.ROOM_AGE_S};var w3={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:IS,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:$n(t.moveX),moveY:$n(t.moveY),moveZ:$n(t.moveZ),yaw:Es(t.yaw)??0,pitch:Es(t.pitch)??0,buttons:fo(t.buttons)}}var S3=2**31-1;var P3=xs.INPUT_REPEAT_MAX_MS,T3=xs.INPUT_REPEAT_RUN_MS;function D_(t,e,n,r=gt.On){return r===gt.Off?t:Math.max(t,Math.min(t+B_(e),n))}function N_(t,e,n=gt.On){return n===gt.Off?t:t+B_(e)}var wI=(t,e,n)=>e<=n?e:Math.min(t,n),B_=t=>typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;function L_(){return{shown:0,heldFrom:null}}function F_(t,e,n,r,s){let o=wI(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 SI=.03,xI=1,I_=.5;function z_(){return{seenRuns:null,owedMs:0,accMs:0,aheadMs:0}}function U_(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)<=xI&&(t.owedMs=Math.max(t.owedMs,r))}function V_(t,e,n,r,s){let o=r>0?n.accMs/r:0;return{raw:t+e+I_*o,at:s+I_*n.aheadMs}}function H_(t,e,n){if(!(n>0)||!(e>0)||t.owedMs<=0)return 0;let r=Math.min(t.owedMs,e*SI);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 q_=1,G_=1200,um=8,_I=170,RI=3,Y_=32,lm=8;var EI=5e3,kI=32,AI=32,PI=4,TI=1024,To=1e3,K_=2e3,X_=250,zd=50,J_=32,Z_=20,Q_=65536,eR=250,Ud=2,tR=3,vI=1e3,MI=6e4,nR=3e4;function rR(t,e){let n=Math.min(MI,vI*2**Math.min(t,16));return n/2+n/2*e}var vo={Bind:"__fast",Off:"__fast:off",Again:"__fast:again",On:"__fast:on"},sR={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 oR=29,$_=29,Vd=24,dm=1,fm=2,pm=4,C3=dm|fm|pm,j_=255,iR=10,CI=4+Vd,zc=4294967295,aR=65536,am=1;var hm=t=>({ok:!0,value:t}),An=t=>({ok:!1,fault:t}),cR=(t,e)=>Math.ceil(t*(Number.isFinite(e)&&e>0?e:0)/1e3),Po=(t,e)=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=e;function Uc(t){return Math.min(Y_,Math.max(RI,cR(_I,t)))}function uR(t){return oR+lm*(iR+Vd)+Uc(t)*CI}var Vc=t=>cR(EI,t);function OI(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function mm(t){return/^(?:[0-9a-fA-F]{2})*$/.test(t)?Uint8Array.from(t.match(/../g)??[],e=>Number.parseInt(e,16)):new Uint8Array(0)}var II=t=>typeof t=="string"&&t.length===2*um&&/^[0-9a-f]+$/.test(t),DI=(t,e)=>(e.buttons&~(t?.buttons??0))!==0,NI=t=>[t.moveX,t.moveY,t.moveZ,t.yaw,t.pitch].every(e=>typeof e=="number"&&Number.isFinite(Math.fround(e)))&&Po(t.buttons,zc),BI=t=>Po(t.seq,zc)&&t.seq>=1&&Po(t.tick,aR-1)&&Po(t.render,zc)&&NI(t.input),LI=t=>t.reduce((e,n)=>Math.max(e,n.render),0),FI=(t,e)=>e.render===0||t-e.render>=j_?j_:t-e.render;function zI(t){let{window:e,actions:n}=t;if(!Po(t.sid,zc)||!II(t.key)||!Po(t.ackSnap,zc))return!1;if(e.length===0)return t.fresh===0&&n.length===0;if(e.length>Y_||n.length>lm||!Po(t.fresh,e.length)||t.fresh<1||![...n,...e].every(BI))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 cm(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+Vd}var W_=t=>{let e=new Uint8Array(Vd);return cm(new DataView(e.buffer),0,t),OI(e)};function UI(t,e){if(t===null)return 0;let n=W_(t.input)===W_(e.input)?dm:0;return e.tick===t.tick?n|=fm:e.tick===(t.tick+1)%aR&&(n|=pm),n}function ym(t){if(!zI(t))return An(Te.Field);let e=new Uint8Array(G_),n=new DataView(e.buffer);e[0]=q_,e[1]=sR.Uplink,n.setUint32(2,t.sid,!0),e.set(mm(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=LI(t.window);n.setUint32(25,r,!0);let s=oR;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=cm(n,s+iR,o.input);return t.window.forEach((o,i)=>{let a=UI(i===0?null:t.window[i-1],o);e[s]=a,s+=1,(a&(fm|pm))===0&&(n.setUint16(s,o.tick,!0),s+=2),e[s]=FI(r,o),s+=1,(a&dm)===0&&(s=cm(n,s,o.input))}),hm(e.slice(0,s))}function VI(t,e,n){return t.length>G_?Te.Oversized:t.length<2?Te.Truncated:t[0]!==q_?Te.Version:t[1]!==e?Te.Kind:t.length<n?Te.Truncated:null}function lR(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&&DI(i>0?t[i-1].input:null,o.input)).slice(0,lm);return{sid:e.sid,key:e.key,ackSnap:e.ackSnap,fresh:Math.min(e.fresh,n.length),actions:s,window:n}}var HI=t=>[...t].sort((e,n)=>e.key-n.key);var O3=new Uint8Array(4096);function $I(t,e){let n=VI(t,sR.Snapshot,$_);if(n!==null)return An(n);let r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(r.getUint32(2,!0)!==e)return An(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>AI||a>=c)return An(Te.Fragment);if(!((i&~am)===0&&i===am==(o===0))||s<1||o>=s)return An(Te.Keyframe);let l=t.slice($_);return hm({snap:s,base:o,tick:r.getUint32(14,!0),inputAck:r.getUint32(18,!0),sent:r.getUint32(25,!0),keyframe:i===am,frag:a,frags:c,chunk:l})}function jI(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<2)return An(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 An(Te.Body);let c=e.getUint16(r,!0);if(a>0&&c<=s[a-1])return An(Te.Body);s.push(c),r+=2}if(r+2>t.length)return An(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 An(Te.Body);let c=e.getUint16(r,!0),u=e.getUint16(r+2,!0);if(u>TI||r+4+u>t.length||a>0&&c<=i[a-1].key)return An(Te.Body);i.push({key:c,bytes:t.slice(r+4,r+4+u)}),r+=4+u}return r===t.length?hm({removed:s,records:i}):An(Te.Body)}function WI(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 HI([...r.values()])}var dR=()=>({partials:[],history:[],newest:0}),qI=(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 fR(t,e,n){let r=$I(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&&!qI(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(-PI);return{rx:{...t,partials:u},applied:null}}return GI({...t,partials:c},t,a)}function GI(t,e,n){let r=t.partials.length===e.partials.length?e:t,s=jI(YI(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=WI(o?.records??[],s.value),a=[...e.history,{snap:n.snap,tick:n.tick,inputAck:n.inputAck,sent:n.sent,records:i}].slice(-kI);return{rx:{partials:t.partials.filter(u=>u.snap>n.snap),history:a,newest:n.snap},applied:n.snap}}function YI(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"},KI=[["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]],XI=[["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]],JI=64,Ji=2,gm=4;var bm=65534,ZI=bm/2,QI={[_e.Orientation]:1,[_e.Velocity]:64},Hd=()=>({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}),$d=()=>({inMoveX:0,inMoveY:0,inMoveZ:0,inYaw:0,inPitch:0,inButtons:0,inRep:0,inStarve:0,inBuf:0,inAck:0});var e1=(t,e)=>-t+e/bm*(2*t),t1=t=>t===Ht.Entity?KI:t===Ht.Seat?XI:null;var hR={f32:4,u32:4,u16:2,"q-orientation":2,"q-velocity":2,flag:0},n1=255,r1=4,s1=32,o1=new Uint8Array(Ji+n1+gm+s1*r1),N3=new DataView(o1.buffer);var B3=new TextEncoder;function i1(t,e,n){if(e+hR[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!==ZI&&r<=bm?{ok:!0,value:e1(QI[n],r)}:{ok:!1,fault:Te.Field}}}}var a1=new TextDecoder("utf-8",{fatal:!0});function c1(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=a1.decode(t.subarray(Ji,Ji+e));return n.length<=JI?{ok:!0,value:n}:{ok:!1,fault:Te.Field}}catch{return{ok:!1,fault:Te.Field}}}function mR(t){if(t.length<Ji)return{ok:!1,fault:Te.Truncated};let e=t1(t[0]);if(e===null)return{ok:!1,fault:Te.Kind};let n=c1(t);if(!n.ok)return n;let r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=Ji+t[1];if(s+gm>t.length)return{ok:!1,fault:Te.Truncated};let o=r.getUint32(s,!0);if(s+=gm,e.length<32&&o>>>e.length)return{ok:!1,fault:Te.Flags};if(t[0]===Ht.Entity){let a=pR(r,s,o,Hd(),e);return a.ok?{ok:!0,value:{kind:Ht.Entity,id:n.value,motion:a.value}}:a}let i=pR(r,s,o,$d(),e);return i.ok?{ok:!0,value:{kind:Ht.Seat,id:n.value,motion:i.value}}:i}function pR(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=i1(t,i,u);if(!l.ok)return l;o[c]=l.value,i+=hR[u]}return i!==t.byteLength?{ok:!1,fault:Te.Trailing}:{ok:!0,value:Object.assign(r,o)}}var u1=4294967295,l1=4,at={Unreachable:"unreachable",Handshake:"handshake",Stall:"stall",Server:"server",NoWebTransport:"no-webtransport",NoRelay:"no-relay",NotOffered:"not-offered"},d1=(t,e)=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=e;function wm(t){if(typeof t!="object"||t===null)return!1;let{sid:e,key:n,url:r}=t,s=typeof n=="string"&&n.length===2*um&&/^[0-9a-f]+$/.test(n);return d1(e,u1)&&s&&typeof r=="string"&&r.length>0}function f1(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 yR=(t,e)=>`${t}:${e}`;function Sm(t){let e=dR(),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>=Ud,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||m1(K.bytes,B.bytes)),L=j?K.record:h1(B.bytes);P.set(B.key,{bytes:B.bytes,record:L}),L!==null&&(k.set(yR(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=fR(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=f1(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>=J_&&(c===null||t.now()-c>=Z_);return(k.snap-M>=Q_||K)&&b(),{applied:B}}function b(){if(o||!l||R===null)return;let E=ym({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=uR(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);p1(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=lR(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=ym(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<=eR)&&(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?zd:X_;(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(yR(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>K_?at.Stall:null;if(i===null)return null;let k=R.opening?.();if(k===!0){let B=Math.max(To,l1*(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>To?at.Handshake:null},receive:S,close(){o||(o=!0,R.close())}}}function p1(t,e){for(let n of t.keys()){if(n>=e)return;t.delete(n)}}function h1(t){let e=mR(t);return e.ok?e.value:null}var m1=(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"},y1=To,g1={[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"},b1=t=>`genex transport: udp fast@1 ${t}`,jd=t=>`genex transport: websocket, ${t}: ${g1[t]??"unknown"}`;function gR(){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(jd(n.fallback)):n.url!==null?n.snapshots>0?e(b1(n.url)):null:n.joinedMs>=y1?e(jd(Zi.NotOffered)):null:e(jd(Zi.NoUdp)):e(jd(Zi.Off))},reset(){t.clear()}}}var w1=19,S1=3,x1=31,_1=Object.keys(Hd()),R1=Object.keys($d()).filter(t=>t!=="inAck"),E1=t=>t===Ht.Entity?_1:R1,k1=["tick","keyframe"],bR=64;function A1(){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>bR&&(t=t.slice(-bR)))},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 xR(t){let e=globalThis.process?.stderr;e?.write!==void 0?e.write(`${t}
|
|
15
|
+
`):console.info(t)}var P1=(t,e)=>{let n=setInterval(e,t);return n.unref?.(),()=>clearInterval(n)};function T1(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 v1(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 _R(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=gR(),i=null,a=null,c=0,u=null,l=null,d=0,f=A1(),h=[],p=null,y=null,S=0,b=t.open===void 0?null:O1(e,()=>u?.client??null),x=t.open===void 0?null:(t.every??P1)(zd,()=>{u?.client.keepalive(),A?.client.keepalive()}),R=t.random??Math.random,A=null,E=!1,P=0,k=null,M=null,B=T1(n),K=v1(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()+rR(P,R()),P+=1)},v=ee=>{if(l!==null)return;M!==null&&t.now()-M>=nR&&(P=0),ee===at.Server&&(P=Math.max(P,S1)),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(vo.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(vo.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(vo.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=[],!wm(ee))return $(at.Unreachable),se();a=ee.url;let ue={client:null,applied:0},Ae=Sm({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>=tR&&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)),Rr=-1;if(Bt>d){let Yn=ue.client.sentAt(ue.seqBase+Bt);Yn!==void 0&&(Rr=t.now()-Yn),d=Bt}f.snapshot(ee.tick,d),e.clock.sample(ee.sent,Rr),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,!wm(ee))return v(at.Unreachable);a=ee.url,E=typeof ee.rev=="number"&&ee.rev>=Ud;let Ae=Sm({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>To&&(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(vo.Bind,ee=>ne(ee)),e.onMessage(vo.Off,()=>v(at.Server)),e.onStateChange(()=>{p!==null&&t.stateCurrent()&&ne(p)}),B!==null&&M1(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(vo.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 M1(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]&x1)===w1||r(s)}}var C1={...Hd(),...$d()};function O1(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]??C1[R]}):k.fast=A,SR(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&&wR(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&&wR(P,E,(k,M,B)=>h(k,M,B,R))}let A=t.state.keyframe===void 0?["tick"]:k1;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)SR(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 wR(t,e,n){let r=e.motion;for(let s of E1(e.kind)){let o=r[s];(o===0||o===!1)&&t[s]===void 0||n(t,s,o)}}function SR(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 RR=new Map,I1="udp:",D1=65535,N1=32,B1=["","/"],L1=t=>t.username===""&&t.password===""&&B1.includes(t.pathname)&&t.search===""&&t.hash==="";function F1(t){let e;try{e=new URL(t)}catch{return null}let n=Number(e.port),r=Number.isInteger(n)&&n>=1&&n<=D1;return e.protocol!==I1||!r||e.hostname===""||!L1(e)?null:{host:e.hostname.replace(/^\[(.*)\]$/,"$1"),port:n}}var ER=({createSocket:t,lookup:e,isIP:n})=>(r,s)=>{let o=F1(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=(RR.get(o.host)??0)%p.length;RR.set(o.host,y+1),l(p[y].address,p[y].family)}),{send(h){c||(a?i?.send(h):u=[...u,h].slice(-N1))},close(){c||(c=!0,i?.close())}}};function kR(){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 ER({createSocket:e.createSocket,lookup:n.lookup,isIP:r.isIP})}var z1=64,U1=4,V1="https:",H1=32,$1=/^[0-9a-f]+$/,j1="reliable-only";function AR(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>U1)return null;let s=a=>typeof a=="string"&&a.length===z1&&$1.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!==V1||o.hostname===""||!i?null:{url:n,hashes:r.map(a=>mm(a))}}function W1(t){return{serverCertificateHashes:t.hashes.map(e=>({algorithm:"sha-256",value:e})),requireUnreliable:!0,allowPooling:!1,congestionControl:"low-latency"}}var q1=t=>t.reliability!==j1;function G1(t){return(t.datagrams.createWritable?.()??t.datagrams.writable)?.getWriter()??null}var $t={Connecting:"connecting",Open:"open",Failed:"failed",Closed:"closed"};function PR(t){let e=(n,r,s)=>{let o=s===void 0?null:AR(s);if(o===null||t===void 0)return null;let i;try{i=new t(o.url,W1(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(!q1(i))return l();let p=G1(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(-H1))},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:AR(n)===null?at.NoRelay:at.Unreachable,e}var xm=t=>typeof t.WebTransport=="function"?t.WebTransport:void 0,TR=(t,e,n)=>PR(xm(globalThis))(t,e,n);TR.whyNull=t=>PR(xm(globalThis)).whyNull?.(t)??at.Unreachable;function vR(t,e=globalThis){return t===!1?{open:void 0,fallback:null}:t!==void 0?{open:t,fallback:null}:xm(e)!==void 0?{open:TR,fallback:null}:{open:void 0,fallback:e.document!==void 0||typeof e.importScripts=="function"?at.NoWebTransport:null}}var MR=100,Wd=["x","y","z","yaw"],Y1=.001;function CR(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 K1=[1e3,2e3,4e3],OR=8,X1=250,IR=600,J1=["x","y","z","vx","vy","vz","yaw"],qd={Reconnecting:"reconnecting",Reconnected:"reconnected",Disconnect:"disconnect",...ks},Z1=new Set(Object.values(qd)),_m={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."},$c=t=>t&&typeof t=="object"?t.code:void 0,Q1=t=>t&&typeof t=="object"?t.message:void 0,eD=t=>$c(t)===pn.ROOM_QUOTA&&Q1(t)===O0;function Am(t){throw fc(t)?console.error(_m.protocol):$c(t)===pn.NOT_ENTITLED?console.error(_m.notEntitled):eD(t)&&console.error(_m.freeQuota),t}var LR=t=>t.physicsCore!==void 0&&t.predictPhysics!==!1;function tD(){let t=typeof navigator>"u"?"":String(navigator.userAgent??"");return/Mobi|Android|iPhone|iPad/i.test(t)?vd.mobile:vd.desktop}async function nD(t,e){if(t.url)return{search:[],create:[t.url]};let n=aS(t.regions,t.urls);if(n.length===0)throw new Error("genex multiplayer: `urls` must contain at least one authority server URL");let r=e===Zt.JoinOrCreate,s=await lS(n,{rule:r?t.regionRule:_h.Nearest,maxPingMs:t.maxPingMs,...e===Zt.JoinById?{}:{region:t.region}},t.probe===void 0?{}:{probe:t.probe});return{search:s.search.map(o=>o.url),create:s.create.map(o=>o.url)}}async function rD(t,e,n,r){for(let s of n)try{return{room:await Pm(new yr(s),t,{...e,method:Zt.Join}),url:s,targets:r}}catch(o){cS($c(o))===id.Final&&Am(o)}return null}async function sD(t,e){let n=hS(e);if("refused"in n)throw new TypeError(`genex multiplayer: this room cannot be asked for (${n.refused})`);let{search:r,create:s}=await nD(t,n.method),o=await rD(t,n,r,s);if(o!==null)return o;let i=t.capacityRetryMs??K1,a={region:0,refused:0,step:0};for(;;){let c=s[a.region];try{return{room:await Pm(new yr(c),t,n),url:c,targets:s}}catch(u){if(n.method===Zt.JoinById){let h=mS($c(u),a.region,s.length);h===null&&Am(u),a={region:h,refused:0,step:0};continue}let l=Eh($c(u));if(l===yo.NextRegion&&a.region+1<s.length){a={region:a.region+1,refused:0,step:a.step};continue}let d=l===yo.Capacity?uS(a,s.length,i):null;d===null&&Am(u);let f=d.attempt.waitMs;f>0&&await new Promise(h=>setTimeout(h,f)),a=d.state}}}var FR=t=>vR(t.fast??kR());function Pm(t,e,n){let r=FR(e).open===void 0?[]:[fn.FAST,fn.FAST_RETURN],s={...dc(e.room,e.name,e.auth),...n.options,[qp.CAPS]:LR(e)?[fn.PHYSICS,fn.PHYSICS_PREDICT,fn.INPUT_REPEAT,fn.LIFTS,fn.INPUT_TICK,...r]:[fn.PHYSICS,fn.INPUT_REPEAT,fn.LIFTS,fn.INPUT_TICK,...r],[qp.SDK]:C0,protocol:4};return n.method===Zt.JoinById?t.joinById(n.roomId,s):n.method===Zt.Create?t.create(ws.AUTHORITY,s):n.method===Zt.Join?t.join(ws.AUTHORITY,s):t.joinOrCreate(ws.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=Ni(n,e.params);return{name:n,definition:r,params:s}}function Rm(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 Em=t=>t!==null&&t.definition.world?t.params.world??null:null,fe=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e;function oD(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 km={body:!1,qx:0,qy:0,qz:0,qw:1,sleep:!1},DR=new Map,NR=2*Math.PI,Mo=t=>t-NR*Math.floor((t+Math.PI)/NR),FH=[bn.Predicted,bn.Separate,bn.Timeline],iD=bn.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 zR(t){let e=await sD(t,t.matchKey===void 0?{}:{matchKey:t.matchKey});return aD(UR(_s(e.room),t,e.url),t,e,!1)}function aD(t,e,n,r){if(e.rejoin===!1)return t;let s=n.targets.filter(o=>o!==n.url);return SS(t,{closed:r,targets:[n.url,...s],join:async(o,i,a)=>{let c=await Pm(new yr(o),e,cD(i,a)),u=UR(_s(c),e,o);return await pc(c,mn.firstStateTimeoutMs),u}})}function cD(t,e){return t===Li.Room?{method:Zt.JoinById,roomId:e.roomId,options:{}}:t===Li.Successor?{method:Zt.JoinOrCreate,options:wS({lostRoomId:e.roomId,matchKey:e.matchKey,closed:e.closed})}:{method:Zt.JoinOrCreate,options:e.matchKey===""?{}:{matchKey:e.matchKey}}}function UR(t,e,n){let r=t.state,s=()=>r.entities??DR,o=()=>r.players??DR,i=e.renderDelayMs??xs.RENDER_DELAY_MS,a=t.input({type:P_,mode:"reliable",renderDelay:i}),c=FR(e),u=_R({room:t,handle:a,open:c.open,neverAsked:c.fallback,off:e.fast===!1,log:e.fastLog??xR,now:e.fastClock??(()=>performance.now()),tickHz:()=>X(),stateCurrent:()=>!Zn}),l=null,d=gt.On,f=()=>{let g=r.preset??"";return g!==l&&(l=g,d=C_(g)),d},h=()=>D_(u.ack(),o().get(t.sessionId)?.inRep,a.sentCount,f()),p=g=>a.at(g)??u.inputAt(g),y=L_(),S=()=>{let g=N_(u.ack(),o().get(t.sessionId)?.inRep,f()),_=a.sentCount,T=g<_&&u.inputAt(g+1)!==void 0;return F_(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=co.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:Dd.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 _=Em(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:Rm(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:c_(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 Md(ue,()=>Cs(ne())),Bt=()=>e.seatDrawing??oe()?.policy.drawing??iD,Rr=e.seatDrawing===void 0||e.seatDrawing===bn.Predicted?Gd(ue):null,Yn=()=>ee()?Rr:null,Oo=()=>Bt()===bn.Predicted?Yn():null;function Cs(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=Yn(),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 ko)typeof z[re]=="number"&&(_[re]=z[re]);return U};function Gd(g){let _=null,T=()=>{let H=r.preset??"";if(_!==null&&_.text===H&&_.hash===$.hash)return _;let U=Qi(H),re=Em(U),J=U!==null&&(re===null||re===$.hash)?Rm(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:oD(J)})}return U};return new Bd({rule:g,pass:Ae,others:z,step:()=>T().step,seatRule:e.seatRule,lifts:()=>{let H=wn();return H===null?null:{lifts:H,starts:ct(),cache:Yd}},remote:()=>{let H=Fs();return{predict:H?.remotePredict??Qt.HOLD,decayMs:H?.remoteDecayMs??_r.DEFAULT_REMOTE_DECAY_MS}},maxAheadMs:()=>(Fs()?.leadMs??_r.DEFAULT_LEAD_MS)+S_})}let Pn=null,wn=()=>{let g=r.preset??"",_=oe();if(Pn===null||Pn.text!==g||Pn.hash!==$.hash||Pn.heads!==_){let T=_!==null&&ix(_.policy)?{policy:_.policy,env:_.env}:void 0;Pn={text:g,hash:$.hash,heads:_,lifts:Ax(g,$,T,X())}}return Pn.lifts},Kn={text:void 0,starts:void 0},ct=()=>{let g=r.lifts;return Kn.text!==g&&(Kn={text:g,starts:Px(g)}),Kn.starts},Xn=new Vi,Yd=new Vi,qc=g=>{let _=Yn();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}})},Gc=["x","y","z"],tn=["vx","vy","vz"],Tn=(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?[]:qc(_),re].sort((le,me)=>le.id<me.id?-1:le.id>me.id?1:0),ge=vc(g,J,T,ct(),H,Xn);for(let le of Gc)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=wn(),J=te===null?null:Tn(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&&vx(te,J.t,ge,me);let wt=T;Xr=le;for(let rn of[...Gc,...tn])J.mine[rn]=wt[rn]??0;Cc(te,J.t,ct());for(let rn of tn)wt[rn]=J.mine[rn]},sa=new Vi,oa=(g,_,T,z,H)=>{let U=wn();U===null||U.policy.platforms.length===0?g(_,T,z):Cx(U,ct(),sa,(re,te)=>g(re,T,z,te),_,H,z)},Os=g=>{let{prediction:_,reason:T}=ce();if(G=T,!_)return null;let z=_.fields??J1;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}},Is=()=>{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},Ds=g=>{g.predicted&&(k.reseeds++,Io(g))},Io=g=>{g.predicted?.reconciler.dispose();let _=Os(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,Ds(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:Os(_),reseeded:!1};return}}},tt=g=>{let _=g.reconciler.state;return g.fields.map(T=>_[T]??0)},Do=(g,_,T)=>{if(g.reconciler.reconcileSeq===T)return;let{place:z,state:H}=l_(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=zm();d_(z,U)&&(k.visibleCorrections++,k.correctionBuckets[f_(z,U)]+=1)},Yc=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},Kc=(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=Mo(re)*(U/re))},Xc=g=>{let _=ea(g.reconciler);if(_===null||Number.isNaN(bt))return null;let T=z=>Object.fromEntries(Wd.map(H=>[H,fe(z[H],0)]));return{offset:bt,local:T(_.local),error:T(_.error),prev:T(_.prev)}},Jc=(g,_,T,z)=>{if(z===null||g.reconciler.reconcileSeq===_||z.offset===bt)return T;let H=wn(),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,Sn,tr)=>{let vn=Wh(H.policy,le,ge(qe),Sn,tr,re);return{...vn,yaw:H.vehicle?vn.yaw:qe.yaw??0}},wt=Object.fromEntries(Wd.map(qe=>[qe,(z.local[qe]??0)+(z.error[qe]??0)])),rn=me(wt,te,J),kt=me(z.prev,te-1,J-1),Uo=me(z.local,te,J);for(let qe of Wd){if(typeof U.local[qe]!="number")continue;let Sn=fe(U.local[qe],0),tr=(wt[qe]??0)-Sn,vn=tr===0?0:(U.error[qe]??0)/tr;U.error[qe]=(rn[qe]-Sn)*vn,U.prev[qe]!==void 0&&(U.prev[qe]=kt[qe])}return g.fields.map((qe,Sn)=>Wd.includes(qe)?Uo[qe]:T[Sn]??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+Mo(H-U)*T.renderAlpha()},es=z_(),Ns=Number.NaN,No=g=>{let _=a.stepMs??0,T=o().get(t.sessionId);U_(es,T?.inStarve,T?.inBuf,_,f());let z=Number.isNaN(Ns)?0:g-Ns;return Ns=g,H_(es,z,_)},Jn,Er=g=>{let _=a.stepMs;if(!_)return 0;if(Jn===void 0)return Jn=g,0;let T=Math.floor((g-Jn)/_);return T>OR?(Jn=g,OR):(Jn+=T*_,T)},Bo=()=>Gi(r.tick??0,h(),0),Bs=null,Ls=g=>{if(!K)return k.inputsDropped+=g,0;let _=0,T=p_((Bs??Bo())+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,Zc=()=>Lt.lastServerTime()>0?Lt.lastServerTime():performance.now(),Et=()=>Lt.lastServerTime()>0?Lt.serverNow()-i-Lt.smoothedRtt()/2:performance.now()-i,Lo=new WeakMap,Fo=g=>({x:g.x,y:g.y,z:g.z,yaw:g.yaw,pitch:fe(g.pitch,0),duck:fe(g.duck,0)}),Qc=g=>{let _=Zc(),T=Lo.get(g);if(T===void 0){Lo.set(g,{at:_,epoch:g.epoch,pose:Fo(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=Fo(g)},eu=g=>{let _=Lo.get(g)?.respawns;if(_===void 0||_.length===0)return;let T=Et();for(;_.length>0&&T>=_[0].at;)_.shift();return _[0]},ts=new Fd,ns=new Set,aa={text:"",k:1},tu=g=>(aa.text!==g&&(aa={text:g,k:Nc(g)?.keyframeTicks??1}),aa.k),zo={text:"\0",desc:null},Fs=()=>{let g=r.physDesc??"";return zo.text!==g&&(zo={text:g,desc:Nc(g)}),zo.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=ud(g,we(),X()),z=1e3/X()*tu(r.physDesc??"");for(let H of ns)ts.push(H,T,Fo(H),z,H.epoch)}ns.clear()},V=Ja(t);V(r).entities.onAdd(g=>{se=!0,Qc(g),ns.add(g),V(g).onChange(()=>{Qc(g),ns.add(g)})}),t.onStateChange(C),V(r).entities.onRemove(()=>{se=!0});let X=()=>a.stepMs?Math.round(1e3/a.stepMs):xs.TICK_HZ,we=()=>r.tickOrigin??0,pe=()=>Ih(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=>ud(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,IR);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++)},Zn=!1,Qn=()=>{Zn=!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>IR+nt.ms)&&(nt={ms:g-ze,endedAt:g}),ze=g,Zn&&Qn(),Qe()});let rt=new Map,kr=()=>{let g=fe(r.lengthUnit,0);return{tickHz:X(),tickOrigin:we(),lengthUnit:g>0?g:1}},Kd=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}),nu=()=>{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=kr(),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=vS(Kd(re),z);if(te!==void 0&&OS(te.last,J)){te.entity=re;continue}let{drawing:ge,snap:le}=CS(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 Ed})}};t.onStateChange(nu);let er=A_({enabled:LR(e),loadCore:e.physicsCore,state:r,sessionId:t.sessionId,staticWorld:()=>$,tickHz:X,sent:()=>a.sentCount,acked:()=>h(),ownId:()=>L?.id,ownPath:Is,bodyRule:e.bodyRule,headSlide:()=>{let g=oe()?.policy;return g?.headFriction===bo.Slide?g.propSlide:null},kinematicRule:e.kinematicRule,lifts:()=>{let g=wn();return g===null||g.policy.platforms.length===0?null:{policy:g.policy,starts:ct()}},seatRule:e.seatRule,budgetMs:Kx(e.physicsBudgetMs,tD()),contactPass:g=>oe()?.pass(g),motionKnown:g=>u.motionKnown(g),...typeof e.physicsClock=="function"?{clock:e.physicsClock}:{},...Rr===null?{}:{seatPose:(g,_)=>{let T=Yn()?.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:_}=Rm(g,$);return(T,z,H,U)=>oa(_,T,Xi({...z}),H,U)}});t.onStateChange(()=>er.onState(Lt.serverNow()));let WR=()=>{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]}},Im=g=>(!rt.has(g)&&r.bodies?.has(g)===!0&&nu(),rt.get(g)),Xd=(g,_)=>{let T=kr(),z=Lt.serverNow(),H=er.draw(g,z),U=_.entity,re=_.descriptor?.kind,te=H===null&&e.kinematicRule!==void 0?Yx(e.kinematicRule,g,z,T):null,J=_.handoff.draw(H??te??Ch(_.drawing,z,T),H!==null,U.epoch,z,Pd(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:Mo(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}},ru={epoch:-1,seq:0,n:0},zs=g=>typeof g=="number"&&Number.isFinite(g)?Oe(Math.fround(g)):0,Dm=g=>{let _=Oh(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,...km}},Nm=()=>{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,Zn=!0,B(qd.Reconnecting,{code:g})}),t.onReconnect(()=>{if(j){t.leave(!0).catch(()=>{});return}(async()=>(await pc(t,mn.firstStateTimeoutMs),!j&&(Zn&&Qn(),L?.predicted&&(L.predicted.reconciler.reset(),k.reseeds++),Jn=void 0,K=!0,B(qd.Reconnected))))()});let Bm=()=>{j=!0,K=!1,u.dispose(),v(),R.dispose(),er.dispose()};t.onLeave((g,_)=>{j||(Bm(),B(qd.Disconnect,g,I0(_)))}),t.onMessage("*",(g,_)=>{typeof g=="string"&&(e.onEvent?.(g,_),Z1.has(g)||B(g,_))});let qR=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}},GR=()=>{if(L===null||L.predicted===null)return null;let g=Wm(L.entity);return{id:L.id,x:g.x,y:g.y,z:g.z,vx:0,vy:0,vz:0,yaw:g.yaw}},Lm=g=>{let T=L?.reseeded===!0&&L.predicted===g?1:ea(g.reconciler)?.renderAlpha()??1;return Math.max(0,a.sentCount-h()-1+T)},su=new Map,nn=0,Fm=()=>ee()&&Bt()!==bn.Timeline,Jd=g=>L?.entity!==g&&g.owner!==""&&!jr(g)&&o().has(g.owner),YR=(g,_)=>{let T=su.get(g);return T!==void 0&&T.lives===_&&nn-T.at<=X1?T:void 0},ou=new Map,Zd,iu=new Map,Qd=Number.NaN,ca={tick:Number.NaN,leadMs:Number.NaN},zm=()=>{let g=fe(r.lengthUnit,0);return g>0?g:xS[Qi(r.preset??"")?.name??""]??1},KR=()=>{let g=Oo(),_=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=Lm(L.predicted),H=V_(T,z,es,a.stepMs??0,nn);Zd=x_(Zd,H.raw,H.at,X());let U=Zd.seq,re=T+z,te=Number.isNaN(Qd)?0:nn-Qd;Qd=nn;let J=_.stateTick+(U-_.ack);ca={tick:J,leadMs:ud(J+1,we(),X())-Lt.serverNow()};let ge=Rt.SEAT_SNAP_METRES*zm(),le=new Map;for(let[me,wt]of s()){if(!Jd(wt))continue;let rn=g.motionAt(me,U);if(rn===void 0)continue;let kt=rn.pose,Uo=ou.get(me),qe=Uo?.pass!=null&&Uo.pass!==_?g.changeAt(me,U,Uo.pass):void 0,Sn=E_(Uo,_,wt.epoch,qe,rn,te,g.touchingAt(me,U),ge,g.stateRate(me));ou.set(me,Sn);let tr={x:kt.x+Sn.dx,y:kt.y+Sn.dy,z:kt.z+Sn.dz,yaw:kt.yaw+Sn.dyaw,pitch:fe(wt.pitch,0),duck:fe(wt.duck,0),epoch:wt.epoch},vn=__(iu.get(me),g.touchAheadMs(me,re)!==void 0,te);iu.set(me,vn);let ua=vn>0?g.motionAt(me,re)?.pose:void 0;ua!==void 0&&(tr.x+=(ua.x-kt.x)*vn,tr.y+=(ua.y-kt.y)*vn,tr.z+=(ua.z-kt.z)*vn,tr.yaw+=Mo(ua.yaw-kt.yaw)*vn),le.set(me,{pose:tr,at:kt})}for(let me of[...ou.keys()])le.has(me)||ou.delete(me);for(let me of[...iu.keys()])le.has(me)||iu.delete(me);return le},XR=g=>{if(!ee())return;let _=e.contacts===void 0?oe():null;return _===null||g===null?ue:_.drawRule(g.id)},JR=()=>{let g=new Map,_=Fm()?GR():null,T=XR(_);if(T===void 0||_===null||L===null||L.predicted===null)return su.clear(),ca={tick:Number.NaN,leadMs:Number.NaN},g;let z=Oo()===null?null:KR(),H=[];for(let[J,ge]of s()){if(!Jd(ge))continue;let le=z?.get(J)?.pose??cu(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=YR(J,ge);le!==void 0&&re.set(J,le)}let te=a_(T,_,H,re,nn);su.clear();for(let[J,ge]of te.sides)su.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 ZR(g,_),g},au=new Map,ZR=(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=au.get(z),ge=J===void 0?0:Math.exp(-Math.max(0,nn-J.at)/MR),le=CR(J,re?1:0,te,ge);au.set(z,{k:re?1:0,shift:te,err:le,at:nn}),!(!re&&le.every(me=>Math.abs(me)<Y1))&&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[...au.keys()])g.has(z)||au.delete(z)},ef=0;t.onStateChange(()=>{ef++});let Um,Vm=()=>{let g=Um;if(g!==void 0&&g.at===nn&&g.states===ef)return g.seats;let _=JR();return Um={at:nn,states:ef,seats:_},_},tf=null,Hm=()=>L?.predicted?(Number.isNaN(bt)?(r.tick??0)-h():bt)+h()+Lm(L.predicted)+1:$m(),$m=()=>(Et()-we())*X()/1e3,jm=new WeakMap,QR=(g,_)=>{let T=wn();if(T===null||T.policy.platforms.length===0||!L?.predicted)return _;let z=$m(),H=Hm(),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?_:{..._,...Wh(T.policy,te,_,z,H,U)};te>=0&&(J.z=qh(T.policy,te,H,U)+(g.z-qh(T.policy,te,re,U)));let ge=[J.x-_.x,J.y-_.y,J.z-_.z,J.yaw-_.yaw],le=jm.get(g),me=nn,wt=le===void 0?0:Math.max(0,me-le.at),rn=Math.exp(-wt/MR),kt=CR(le,te,ge,rn);return jm.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]}},nf=null,eE=g=>{let _=cu(g.entity);Io(g);let T=cu(g.entity);nf={dx:_.x-T.x,dy:_.y-T.y,dz:_.z-T.z,at:nn}},cu=g=>{let _=tE(g),T=L?.entity===g?nf:null;if(T===null)return _;let z=R_(T,nn-T.at);return z.done?(nf=null,_):{..._,x:_.x+z.dx,y:_.y+z.dy,z:_.z+z.dz}},tE=g=>{let _=qR(g);if(_)return _;let T=eu(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:QR(g,U),epoch:g.epoch}:{...Et()>T.from?T.pose:U,epoch:T.epoch}},Wm=(g,_,T)=>(_!==void 0&&Fm()&&Jd(g)?(T??Vm()).get(_):void 0)??cu(g),nE=(g,_)=>{let T=Ne.entryFor(_),z=T?.local!==void 0&&_.src===t.sessionId?T.leadMs*X()/1e3:0,H=Oh(Me(_),pe()+z,X());return{id:g,kind:_.kind,owner:_.owner,...H,yaw:Mo(_.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),...km}},rf={text:"",limit:Math.PI},rE=()=>{let g=r.preset??"";if(rf.text!==g){let _=Qi(g)?.params.pitchLimit;rf={text:g,limit:_===void 0?Math.PI:Math.fround(_)}}return rf.limit},sE=g=>{let _=rE(),T=Mo(g);return T<-_?-_:T>_?_:T},sf=(g,_,T)=>L?.entity===g&&L.predicted?.fields.includes(_)?fe(L.predicted.reconciler.state[_],T):fe(g[_],T),of=(g,_,T)=>{let z=Im(g);if(z!==void 0)return Xd(g,z);if(jr(_))return nE(g,_);let H=Wm(_,g,T);return{id:g,kind:_.kind,owner:_.owner,x:H.x,y:H.y,z:H.z,yaw:Mo(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:sE(H.pitch),duck:H.duck<0?0:H.duck>1?1:H.duck,mstate:sf(_,"mstate",0),cap:fe(_.cap,1),spin:sf(_,"spin",0),fuel:sf(_,"fuel",0),...km,...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;nn=g,u.poll(),er.settle(),Qr();let _=L?.predicted??null,T=_?tt(_):[],z=_?Yc(_):null,H=_?Xc(_):null,U=_?.reconciler.reconcileSeq??0,re=No(g),te=R.tick(g)+re;if(!_){let ge=Ls(Er(g)+re);return er.afterSend(void 0,Lt.serverNow()),Bs=Bo(),ge}Jn=void 0,Do(_,Jc(_,U,T,H),U),Kc(_,U,z);let J=Ls(te);return er.afterSend(WR(),Lt.serverNow()),Bs=Bo(),J>0&&L&&(L.reseeded=!1),(Rr?.takeMissed()??[]).length>0&&L!==null&&eE(L),J},me(){return j||Qr(),L?of(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&&Io(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 er.status},drawTick(){return ca.tick},drawLead(){return ca.leadMs},liftPose(g){let _=wn();return _===null?void 0:Mx(_.policy,g,Hm(),ct())},viewCarry(){let g=wn(),_=L?.predicted?L.predicted.reconciler.state:void 0;if(g===null||_===void 0)return tf=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=tf;return tf=H===void 0?null:{k:z,tick:T},H===void 0||U===null||U.k!==z?0:jh(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:Em(Qi(r.preset??""))}},predictProjectile(g){if(!K)return"";let _=a.sentCount+1;(ru.epoch!==a.epoch||ru.seq!==_)&&(ru={epoch:a.epoch,seq:_,n:0});let T=o().get(t.sessionId)?.seqBase??0,z=`${t.sessionId}.${T+_}.${ru.n++}`,H=Lt.serverNow(),U=zs(g.g),re={x:zs(g.x),y:zs(g.y),z:zs(g.z),vx:zs(g.vx),vy:zs(g.vy),vz:zs(g.vz),g:U<0?0:U>wc?wc:U,t0:Ih(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 of(g,_);let T=Im(g);if(T!==void 0)return Xd(g,T);let z=Nm().get(g);return z?Dm(z):void 0},entities(){let g=new Map,_=Vm();for(let[T,z]of s())g.set(T,of(T,z,_));for(let[T,z]of rt)g.has(T)||g.set(T,Xd(T,z));for(let[T,z]of Nm())g.has(T)||g.set(T,Dm(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||(Bm(),t.reconnection.enabled=!1,await t.leave(!0))}}}var uD=3,VR={ready:t=>ga.ready(t),auth:()=>Pu(),urls:()=>Iy(),regions:()=>Dy()},jc=VR;function lD(t){jc=t??VR}var HR;function dD(t){HR=t??void 0}var fD=xs.MAX_REWIND_MS,pD=5,hD=3e4,mD=["moveX","moveY","moveZ","yaw","pitch","buttons"],ta=t=>typeof t=="number"&&Number.isFinite(t);function yD(t){return!Array.isArray(t)||t.length>pD?void 0:t.every(n=>ta(n)&&n>=0&&n<=hD)?t:void 0}function gD(t){let e=rr(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<=fD;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:yD(e.capacityRetryMs),fast:e.fast===!1?!1:void 0}}var Mm=new Map,bD=2**30,wD=bD,Wc=t=>typeof t=="number"?Mm.get(t):void 0,Co=t=>{let e=Wc(t);return e&&!e.closed?e.session:null};function Cm(t){t.closed=!0;for(let e of t.unwire.splice(0))e();t.session=null}function SD(t,e,n){Ss(e)?e===xe.SERVER_RESTART&&ye(t,{type:"serverRestart"}):ye(t,{type:"message",kind:e,data:n??null})}async function xD(t){let e=t.opts;if(await jc.ready(e.gameId),t.closed)return;let n=e.urls.length?e.urls:jc.urls(),r=e.urls.length?[]:jc.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 zR({urls:n,regions:r,room:e.gameId,name:e.name,auth:()=>jc.auth(),predict:e.predict?void 0:!1,physicsCore:HR,predictPhysics:e.predictPhysics,renderDelayMs:e.renderDelayMs,capacityRetryMs:e.capacityRetryMs,fast:e.fast,onEvent:(o,i)=>{t.closed||SD(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=>{Cm(t),ye(t,{type:"disconnected",code:o,reason:""})})),ye(t,{type:"joined",sessionId:s.id})}function _D(t){let e=gD(t),n=++wD,r={opts:e,q:[],overflowed:!1,session:null,unwire:[],roster:new Set,sessionId:"",closed:!1,world:null};return Mm.set(n,r),xD(r).catch(s=>{r.closed||(Cm(r),ye(r,{type:"joinFailed",code:Zo(s),message:nr(s)}))}),n}function RD(t,e){let n=rr(e,"input"),r=Co(t);if(!r)return!1;for(let s of mD){let o=n[s];ta(o)&&(r.input[s]=o)}return!0}function ED(t,e){let n=rr(e,"projectile"),r=Co(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 kD(t,e){let n=rr(e,"world"),r=Wc(t);if(!r||r.closed)return!1;let s;try{s=mo(n)}catch(o){return ye(r,Jo(nr(o))),!1}return r.world=s,r.session?.setWorld(s),!0}var AD=JSON.stringify({tick:0,sent:0,connected:!1,me:null,entities:[]});function PD(t,e){let n=Co(t);if(!n)return AD;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 Tm=8,vm={PREDICTED:1,ASLEEP:2},TD=new Float32Array(0);function $R(t){return[...t.entities().values()].filter(e=>e.body).sort((e,n)=>e.id<n.id?-1:e.id>n.id?1:0)}function vD(t){let e=Co(t);if(!e)return TD;let n=$R(e),r=new Float32Array(n.length*Tm);return n.forEach((s,o)=>{let i=o*Tm;r.set([s.x,s.y,s.z,s.qx,s.qy,s.qz,s.qw],i),r[i+7]=(s.predicted?vm.PREDICTED:0)|(s.sleep?vm.ASLEEP:0)}),r}function MD(t){let e=Co(t);return JSON.stringify(e?$R(e).map(n=>n.id):[])}function CD(t){let e=Wc(t),n=Co(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 OD(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 ID(t){let e=Wc(t);if(!e)return"[]";try{let n=Co(t);n&&OD(e,n)}catch(n){ye(e,Jo(nr(n)))}return Cu(e)}function jR(t){let e=Wc(t);if(!e||e.closed)return;let n=e.session;Cm(e),n?.leave().catch(()=>{}),ye(e,{type:"disconnected",code:hn.CONSENTED,reason:"left"})}function DD(t){jR(t),typeof t=="number"&&Mm.delete(t)}var ND=Object.freeze({...sh,...Om,initEmbed:Au});globalThis.GenexMultiplayerBridge=ND;})();
|