@genex-ai/multiplayer 0.16.1 → 0.17.0
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 +624 -0
- package/README.md +191 -27
- package/dist/bridge.d.ts +89 -0
- package/dist/bridge.global.js +14 -0
- package/dist/bridge.js +558 -0
- package/dist/chunk-C52XFIB6.js +312 -0
- package/dist/chunk-CTDU4IJ5.js +2191 -0
- package/dist/index.d.ts +110 -18
- package/dist/index.js +7 -1778
- package/dist/protocol.d.ts +419 -0
- package/dist/protocol.js +58 -0
- package/dist/schema.d.ts +122 -68
- package/dist/schema.js +95 -16
- package/package.json +27 -10
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";(()=>{var ap=Object.create;var fi=Object.defineProperty;var cp=Object.getOwnPropertyDescriptor;var lp=Object.getOwnPropertyNames;var up=Object.getPrototypeOf,dp=Object.prototype.hasOwnProperty;var Ol=n=>{throw TypeError(n)};var fp=(n,e,t)=>e in n?fi(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Oe=(n,e)=>()=>(n&&(e=n(n=0)),e);var hp=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ml=(n,e)=>{for(var t in e)fi(n,t,{get:e[t],enumerable:!0})},pp=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lp(e))!dp.call(n,s)&&s!==t&&fi(n,s,{get:()=>e[s],enumerable:!(r=cp(e,s))||r.enumerable});return n};var mp=(n,e,t)=>(t=n!=null?ap(up(n)):{},pp(e||!n||!n.__esModule?fi(t,"default",{value:n,enumerable:!0}):t,n));var l=(n,e,t)=>fp(n,typeof e!="symbol"?e+"":e,t),ha=(n,e,t)=>e.has(n)||Ol("Cannot "+t);var H=(n,e,t)=>(ha(n,e,"read from private field"),t?t.call(n):e.get(n)),he=(n,e,t)=>e.has(n)?Ol("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),pe=(n,e,t,r)=>(ha(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t),On=(n,e,t)=>(ha(n,e,"access private method"),t);var _e,pr,Ja,Mi,Di,Bn,Ne,Ou=Oe(()=>{"use strict";_e={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},pr={TIMED:128,UNRELIABLE:64},Ja=31,Mi={OK:0,REJECTED:1,ERROR:2},Di={INPUT_REFLECTION:1,INPUT_OPTIONS:2},Bn={RENDER_TIME:1,FIXED_TIMESTEP:2,PATCH_RATE:4,SUB_STEPS:8,RECKON_TIME:16},Ne={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 Yt=Oe(()=>{"use strict";Ou()});function Rd(n){Object.defineProperty(n,Symbol.metadata,{value:void 0,writable:!0,configurable:!0,enumerable:!1})}function kd(n,e,t){for(var r=0,s=0,i=e.length;s<i;s++)r=e.charCodeAt(s),r<128?n[t.offset++]=r:r<2048?(n[t.offset]=192|r>>6,n[t.offset+1]=128|r&63,t.offset+=2):r<55296||r>=57344?(n[t.offset]=224|r>>12,n[t.offset+1]=128|r>>6&63,n[t.offset+2]=128|r&63,t.offset+=3):(s++,r=65536+((r&1023)<<10|e.charCodeAt(s)&1023),n[t.offset]=240|r>>18,n[t.offset+1]=128|r>>12&63,n[t.offset+2]=128|r>>6&63,n[t.offset+3]=128|r&63,t.offset+=4)}function vd(n,e,t){n[t.offset++]=e&255}function zm(n,e,t){n[t.offset++]=e&255}function Ad(n,e,t){n[t.offset++]=e&255,n[t.offset++]=e>>8&255}function oc(n,e,t){n[t.offset++]=e&255,n[t.offset++]=e>>8&255}function en(n,e,t){n[t.offset++]=e&255,n[t.offset++]=e>>8&255,n[t.offset++]=e>>16&255,n[t.offset++]=e>>24&255}function Un(n,e,t){let r=e>>24,s=e>>16,i=e>>8,o=e;n[t.offset++]=o&255,n[t.offset++]=i&255,n[t.offset++]=s&255,n[t.offset++]=r&255}function Cd(n,e,t){let r=Math.floor(e/Math.pow(2,32)),s=e>>>0;Un(n,s,t),Un(n,r,t)}function Id(n,e,t){let r=e/Math.pow(2,32)>>0,s=e>>>0;Un(n,s,t),Un(n,r,t)}function Wm(n,e,t){Sd[0]=BigInt.asIntN(64,e),en(n,Fn[0],t),en(n,Fn[1],t)}function Jm(n,e,t){Sd[0]=BigInt.asIntN(64,e),en(n,Fn[0],t),en(n,Fn[1],t)}function Pd(n,e,t){Za[0]=e,en(n,Fn[0],t)}function Od(n,e,t){Gm[0]=e,en(n,Fn[0],t),en(n,Fn[1],t)}function Km(n,e,t){n[t.offset++]=e?1:0}function Ym(n,e,t){e||(e="");let r=Td(e,"utf8"),s=0;if(r<32)n[t.offset++]=r|160,s=1;else if(r<256)n[t.offset++]=217,n[t.offset++]=r,s=2;else if(r<65536)n[t.offset++]=218,oc(n,r,t),s=3;else if(r<4294967296)n[t.offset++]=219,Un(n,r,t),s=5;else throw new Error("String too long");return kd(n,e,t),s+r}function ec(n,e,t){if(isNaN(e))return ec(n,0,t);if(isFinite(e)){if(e!==(e|0))return Math.abs(e)<=34028235e31&&(Za[0]=e,Math.abs(Math.abs(Za[0])-Math.abs(e))<1e-4)?(n[t.offset++]=202,Pd(n,e,t),5):(n[t.offset++]=203,Od(n,e,t),9)}else return ec(n,e>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER,t);return e>=0?e<128?(n[t.offset++]=e&255,1):e<256?(n[t.offset++]=204,n[t.offset++]=e&255,2):e<65536?(n[t.offset++]=205,oc(n,e,t),3):e<4294967296?(n[t.offset++]=206,Un(n,e,t),5):(n[t.offset++]=207,Id(n,e,t),9):e>=-32?(n[t.offset++]=224|e+32,1):e>=-128?(n[t.offset++]=208,vd(n,e,t),2):e>=-32768?(n[t.offset++]=209,Ad(n,e,t),3):e>=-2147483648?(n[t.offset++]=210,en(n,e,t),5):(n[t.offset++]=211,Cd(n,e,t),9)}function Md(n,e,t){t>n.length-e.offset&&(t=n.length-e.offset);for(var r="",s=0,i=e.offset,o=e.offset+t;i<o;i++){var a=n[i];if((a&128)===0){r+=String.fromCharCode(a);continue}if((a&224)===192){r+=String.fromCharCode((a&31)<<6|n[++i]&63);continue}if((a&240)===224){r+=String.fromCharCode((a&15)<<12|(n[++i]&63)<<6|(n[++i]&63)<<0);continue}if((a&248)===240){s=(a&7)<<18|(n[++i]&63)<<12|(n[++i]&63)<<6|(n[++i]&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 "+i+". Skip to end of string: "+(e.offset+t));break}return e.offset+=t,r}function Dd(n,e){return ys(n,e)<<24>>24}function ys(n,e){return n[e.offset++]}function Nd(n,e){return Qi(n,e)<<16>>16}function Qi(n,e){return n[e.offset++]|n[e.offset++]<<8}function xt(n,e){return n[e.offset++]|n[e.offset++]<<8|n[e.offset++]<<16|n[e.offset++]<<24}function yr(n,e){return xt(n,e)>>>0}function Bd(n,e){return $n[0]=xt(n,e),Xm[0]}function Ld(n,e){return $n[0]=xt(n,e),$n[1]=xt(n,e),Qm[0]}function Fd(n,e){let t=yr(n,e);return xt(n,e)*Math.pow(2,32)+t}function Ud(n,e){let t=yr(n,e);return yr(n,e)*Math.pow(2,32)+t}function tg(n,e){return $n[0]=xt(n,e),$n[1]=xt(n,e),eg[0]}function ng(n,e){return $n[0]=xt(n,e),$n[1]=xt(n,e),Zm[0]}function rg(n,e){return ys(n,e)>0}function sg(n,e){let t=n[e.offset++],r;return t<192?r=t&31:t===217?r=ys(n,e):t===218?r=Qi(n,e):t===219&&(r=yr(n,e)),Md(n,e,r)}function ig(n,e){let t=n[e.offset++];if(t<128)return t;if(t===202)return Bd(n,e);if(t===203)return Ld(n,e);if(t===204)return ys(n,e);if(t===205)return Qi(n,e);if(t===206)return yr(n,e);if(t===207)return Ud(n,e);if(t===208)return Dd(n,e);if(t===209)return Nd(n,e);if(t===210)return xt(n,e);if(t===211)return Fd(n,e);if(t>223)return(255-t+1)*-1}function og(n,e){let t=n[e.offset];return t<192&&t>160||t===217||t===218||t===219}function nn(n,e){e.constructor&&(Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor[Symbol.metadata]==null&&Rd(e.constructor),ag.set(e.constructor,n),ac[n]=e),e.encode&&(Q[n]=e.encode),e.decode&&(te[n]=e.decode)}function $d(n){return ac[n]}function tn(){return{pendingByView:new Map,sentByView:new Map,broadcastPending:new Set,sentBroadcast:new Set,broadcastDeletes:new Set,maxPerTick:32}}function lc(n){return n._stream??(n._stream=tn())}function Zi(n,e,t){e.activeViews.size===0&&lc(n).broadcastPending.add(t)}function eo(n,e,t,r){let s=n._stream;if(s===void 0)return!0;let i=!1;return s.broadcastPending.delete(r)?i=!0:s.sentBroadcast.delete(r)&&s.broadcastDeletes.add(r),e.forEachActiveView(o=>{let a=s.pendingByView.get(o.id);if(a?.has(r)){a.delete(r),i=!0;return}let c=s.sentByView.get(o.id);if(c?.has(r)){c.delete(r);let u=o.changes.get(t);u===void 0&&(u=new Map,o.changes.set(t,u)),u.set(r,R.DELETE)}}),i}function cg(n,e,t){let r=n._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 i=r.sentByView.get(s.id);if(i!==void 0&&i.size>0){let o=s.changes.get(t);o===void 0&&(o=new Map,s.changes.set(t,o));for(let a of i)o.set(a,R.DELETE);i.clear()}})}}function lg(n,e){let t=n._stream?.pendingByView;if(t===void 0)return!1;for(let[r,s]of t)if(s.size>0&&e.activeViews.get(r)?.deref()!==void 0)return!0;return!1}function ug(n){let e=n._stream;return e!==void 0&&(e.broadcastPending.size>0||e.broadcastDeletes.size>0)}function dg(n,e,t){let r=lc(n),s=r.pendingByView.get(e);s===void 0&&(s=new Set,r.pendingByView.set(e,s)),s.add(t)}function to(n,e){let t=n._stream;t!==void 0&&(t.pendingByView.delete(e),t.sentByView.delete(e),t.priorityByView?.delete(e))}function uc(n){if(n==null||typeof n!="object")throw new Error("t.quantized(): options object with { min, max } is required.");let{min:e,max:t}=n;if(typeof e!="number"||typeof t!="number"||!(t>e)||!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`t.quantized(): require finite min < max (got min=${e}, max=${t}).`);let r=n.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=n.mode??"clamp";if(s!=="clamp"&&s!=="wrap")throw new Error(`t.quantized(): mode must be "clamp" or "wrap" (got ${JSON.stringify(s)}).`);let i=s==="wrap",o=Math.pow(2,r);return{min:e,max:t,bits:r,wrap:i,wire:fg[r],range:t-e,span:i?o:e===-t?o-2:o-1}}function Vn(n){return n!==null&&typeof n=="object"&&n.quantized!==void 0}function jd(n,e){if(n.wrap){if(!Number.isFinite(e))return 0;let r=n.range,s=(e-n.min)%r;s<0&&(s+=r);let i=n.span;return Math.floor(s/r*i+.5)%i}if(e!==e)return 0;let t=e<n.min?n.min:e>n.max?n.max:e;return Math.floor((t-n.min)/n.range*n.span+.5)}function qd(n,e){return n.min+e/n.span*n.range}function hg(n){let e=Q[n.wire];return(t,r,s)=>e(t,jd(n,r),s)}function pg(n,e,t){let r=te[n.wire];return qd(n,r(e,t))}function mg(n){let e=typeof Object.keys(n)[0]=="string"&&$d(Object.keys(n)[0]);return{complexTypeKlass:e,childType:e?Object.values(n)[0]:n}}function br(n){if(Array.isArray(n))return{array:br(n[0])};if(Vn(n))return typeof n.quantized.wire=="string"?n:{quantized:uc(n.quantized)};if(typeof n.type<"u")return n.type;if(gg(n))return Object.keys(n).every(e=>typeof n[e]=="string")?"string":"number";if(typeof n=="object"&&n!==null){let e=Object.keys(n).find(t=>ac[t]!==void 0);if(e)return n[e]=br(n[e]),n}return n}function gg(n){if(typeof n=="function"&&n[Symbol.metadata])return!1;let e=Object.keys(n),t=e.filter(r=>/\d+/.test(r));return!!(t.length>0&&t.length===e.length/2&&n[n[t[0]]]==t[0]||e.length>0&&e.every(r=>typeof n[r]=="string"&&n[r]===r))}function Bi(n,e,t){n[e]||Object.defineProperty(n,e,{value:[],enumerable:!1,configurable:!0,writable:!0}),n[e].push(t)}function qi(n){return n=n-(n>>>1&1431655765),n=(n&858993459)+(n>>>2&858993459),(n+(n>>>4)&252645135)*16843009>>>24}function Li(n){if(n===void 0)return 0;let e=0;for(let t=0,r=n.length;t<r;t++){let s=n[t];s<32&&(e|=1<<s)}return e}function bg(n){let e=[],t=[],r=[],s=[],i=n?.[Fe];if(i===void 0)return{names:e,types:t,tags:r,encoders:s};let o=n[Qt];for(let a=0;a<=i;a++){let c=n[a];if(c===void 0){e[a]=void 0,t[a]=void 0,r[a]=void 0,s[a]=void 0;continue}e[a]=c.name,t[a]=c.type,r[a]=c.tag,s[a]=o?.[a]}return{names:e,types:t,tags:r,encoders:s}}function dc(n){let e=n.constructor;if(Object.prototype.hasOwnProperty.call(e,cs))return e[cs];let t=e[Symbol.metadata],r=ce.isValidInstance(n),s=(t?.[bt]?.length??0)>0,i=bg(t),o=r&&!s?void 0:e[qn],a={encoder:e[Nt],filter:o,metadata:t,isSchema:r,filterBitmask:r?Li(t?.[bt]):0,hasAnyFullStateOnly:(t?.[gr]?.length??0)>0,hasAnyUnreliable:(t?.[Ln]?.length??0)>0,hasAnyStream:(t?.[at]?.length??0)>0,hasAnyView:s,fullStateOnlyBitmask:Li(t?.[gr]),unreliableBitmask:Li(t?.[Ln]),streamBitmask:Li(t?.[at]),names:i.names,types:i.types,tags:i.tags,encoders:i.encoders};return Object.defineProperty(e,cs,{value:a,enumerable:!1,writable:!0,configurable:!0}),a}function wg(n,e,t){if(n.parentRef){if(n.parentRef[_]===e[_]){n._parentIndex=t;return}if(Hd(n,(r,s)=>r[_]===e[_])){n._parentIndex=t;return}}n.parentRef===void 0?(n.parentRef=e,n._parentIndex=t):(n.extraParents={ref:n.parentRef,index:n._parentIndex,next:n.extraParents},n.parentRef=e,n._parentIndex=t)}function _g(n,e,t){if(n.extraParents===void 0){n._parentIndex=t;return}if(n.parentRef[_]===e[_]){n._parentIndex=t;return}for(let r=n.extraParents;r!==void 0;r=r.next)if(r.ref[_]===e[_]){r.index=t;return}}function Eg(n,e){if(n.parentRef&&n.parentRef[_]===e[_])return n.extraParents?(n.parentRef=n.extraParents.ref,n._parentIndex=n.extraParents.index,n.extraParents=n.extraParents.next):(n.parentRef=void 0,n._parentIndex=void 0),!0;let t=n.extraParents,r=null;for(;t;){if(t.ref[_]===e[_])return r?r.next=t.next:n.extraParents=t.next,!0;r=t,t=t.next}return n.parentRef===void 0}function Rg(n,e){if(n.parentRef!==void 0&&e(n.parentRef,n._parentIndex))return{ref:n.parentRef,index:n._parentIndex};for(let t=n.extraParents;t!==void 0;t=t.next)if(e(t.ref,t.index))return{ref:t.ref,index:t.index}}function Hd(n,e){if(n.parentRef!==void 0&&e(n.parentRef,n._parentIndex))return!0;for(let t=n.extraParents;t!==void 0;t=t.next)if(e(t.ref,t.index))return!0;return!1}function xg(n,e){if(n.parentRef&&n.parentRef[_]===e[_])return n._parentIndex;for(let t=n.extraParents;t!==void 0;t=t.next)if(t.ref[_]===e[_])return t.index}function Sg(n){let e=[];n.parentRef&&e.push({ref:n.parentRef,index:n._parentIndex});let t=n.extraParents;for(;t;)e.push({ref:t.ref,index:t.index}),t=t.next;return e}function Tg(n,e,t){let r=e.refTarget;if(e.isArray){let i=r.items,o=i[t];if(o!==void 0&&o[_]===n)return!0;for(let a=0,c=i.length;a<c;a++){let u=i[a];if(u!==void 0&&u[_]===n)return!0}return!1}let s=e.getValue(t);return s!==void 0&&s[_]===n}function vg(n,e){fc(n,e,kg)}function fc(n,e,t){let r=n.refTarget;if(r[X]!==void 0){if(n.isPatchOnly)return;if(Array.isArray(r.items)){let s=r.items;for(let i=0,o=s.length;i<o;i++)s[i]!==void 0&&t(e,i)}else if(r.journal!==void 0)for(let[s,i]of r.journal.keyByIndex)r.$items.has(i)&&t(e,s);else if(r.$items!==void 0)for(let s of r.$items.keys())t(e,s)}else{let s=n.metadata;if(!s)return;let i=s[Fe]??-1,o=s[ji],a=n.encDescriptor.names;for(let c=0;c<=i;c++){let u=a[c];if(u===void 0||o&&o.includes(c))continue;let d=r[u];d!=null&&t(e,c)}}}function Wd(n,e,t,r){Ag(n,e,t),!n.isFullStateOnly&&(n.has()&&n.root?.enqueueChangeTree(n),n.unreliableRecorder?.has()&&n.root?.enqueueUnreliable(n),!n.has()&&!n.unreliableRecorder?.has()&&n.root?.enqueueChangeTree(n))}function Ag(n,e,t){if(!e)return;let r=e[_],s=!r._isSchema,i;s?(e=r.parent,t=r.parentIndex,i=e?.[_].metadata):i=r.metadata;let o=(i?.[us]?.includes(t)?ls:0)|(i?.[gr]?.includes(t)?mr:0),a=r.flags&$g|o,c=n.flags;if(n.flags=c|a,a&~c&mr&&(n.reset(),n.unreliableRecorder?.reset()),!n.root?.types?.hasFilters)return;let h=i?.[bt]?.includes(t)??!1,m=i?.[at]?.includes(t)??!1,g=r.isFiltered||h||m;if(n.isFiltered=g,m&&!s){n.isStreamCollection=!0;let p=lc(n.ref);if(p.priority===void 0){let y=ce.getStreamPriority(i,t);y!==void 0&&(p.priority=y)}n.root?.registerStream(n.ref)}if(g){let p=Jd(n);n.isVisibilitySharedWithParent=r.isFiltered&&p&&!m&&(!h||s&&i[t].tag!==io)}}function Nu(n){let e=n.pendingFilterRefresh;for(let t=0;t<e.length;t++){let r=e[t];(r.flags&ds)!==0&&hc(r)}e.length=0}function Jd(n){return n._isSchema||typeof n.refTarget[X]!="string"}function hc(n){n.flags&=~ds;let e=n.root;if(e===void 0||n.parentRef===void 0)return;let t=Jd(n),r=Bu(n,n.parentRef,n._parentIndex,t);for(let i=n.extraParents;i!==void 0&&r!==Cg;i=i.next)r|=Bu(n,i.ref,i.index,t);if(r===0)return;n.isVisibilitySharedWithParent=(r&Hi)!==0;let s=(r&Gi)===0;s!==n.isFiltered&&(n.isFiltered=s,!s&&!n.isFullStateOnly&&(n.forEachLiveWithCtx(n,zd),n.has()&&e.enqueueChangeTree(n),n.unreliableRecorder?.has()&&e.enqueueUnreliable(n)),n.forEachChildWithCtx(n,Ig))}function Bu(n,e,t,r){let s=e[_];if(s.root!==n.root||!Tg(n,s,t))return 0;s.flags&ds&&hc(s);let i=Kd;if(s._isSchema)s.encDescriptor.tags[t]!==void 0||s.isFieldStream(t)||(s.isFiltered?r&&(i|=Hi):i|=Gi);else if(!s.isFiltered)i|=Gi;else if(r&&!s.isStreamCollection){let o=s.parent?.[_];(o?._isSchema?o.encDescriptor.tags[s.parentIndex]:void 0)!==io&&(i|=Hi)}return i}function Pg(n,e,t,r){let s=n.subscribedViews;if(s===void 0)return;let i=n.isStreamCollection,o=i?n.ref:void 0,a=i?void 0:t[_];for(let c=0,u=s.length;c<u;c++){let d=s[c];for(;d!==0;){let h=d&-d;d^=h;let m=c*32+(31-Math.clz32(h)),p=r.activeViews.get(m)?.deref();if(p===void 0){s[c]&=~h;continue}i?dg(o,m,e):a!==void 0&&p.markVisible(a)}}}function Og(n,e){n.root=e;let t=e.add(n);Wd(n,n.parent,n.parentIndex),t&&bs(n,e,Bg)}function Mg(n,e,t,r){if(n.addParent(e,r),!t)return;let s=t.add(n);t!==n.root&&(n.root=t,Wd(n,e,r));let i=e?.[_];if(i!==void 0&&i.subscribedViews!==void 0&&e[X]!==void 0&&Pg(i,r,n.ref,t),s){let o=Lu[Fi];o===void 0&&(o={parentRef:void 0,root:void 0},Lu[Fi]=o),o.parentRef=n.ref,o.root=t,Fi++,bs(n,o,Lg),Fi--}}function Dg(n,e){bs(n,e,Ng)}function Ng(n,e,t){n(e,t)}function bs(n,e,t){let r=n.refTarget;if(r[X]){if(typeof r[X]!="string"){let s=r.items;if(s!==void 0)for(let i=0,o=s.length;i<o;i++){let a=s[i];a&&t(e,a[_],i)}else{let i=r.$items,o=r._collectionIndexes;for(let a of i.keys()){let c=i.get(a);c&&t(e,c[_],o?.[a]??a)}}}}else{let i=n.metadata?.[bn];if(!i)return;let o=n.encDescriptor.names;for(let a=0,c=i.length;a<c;a++){let u=i[a],d=r[o[u]];d&&t(e,d[_],u)}}}function Bg(n,e,t){e.root!==n?e.setRoot(n):n.add(e)}function Lg(n,e,t){if(e.root===n.root){n.root.add(e),n.root.moveNextToParent(e);return}e.setParent(n.parentRef,n.root,t)}function Fg(n,e,t){let r=(t&3)<<3;return t<4?n>>>r&255:e>>>r&255}function Fu(){return{next:void 0,tail:void 0,nextPosition:0}}function Vg(n){return new rc(n)}function _r(n,e=n){Object.defineProperty(n,_,{value:Vg(e),enumerable:!1,writable:!0})}function no(n,e,t,r,s,i,o){o!==void 0?o(e,r,i):typeof t=="string"?Q[t]?.(e,r,i):t[Symbol.metadata]!=null?(Q.number(e,r[$],i),(s&R.ADD)===R.ADD&&n.tryEncodeTypeId(e,t,r.constructor,i)):Q.number(e,r[$],i)}function Yd(n,e,t,r,s,i,o){let a=n.resyncVisited,c=a.get(n.currentRefId);if(c===void 0&&a.set(n.currentRefId,c=new Set),c.add(r),s!==void 0&&t===R.ADD&&s!==i){let u=s[$];u!==void 0&&(n.root.removeRef(u),o?.push({ref:e,refId:n.currentRefId,op:R.DELETE,dynamicIndex:r,value:void 0,previousValue:s}))}}function Hg(n,e){let t=n.resyncVisited;t.has(e)||t.set(e,new Set)}function zg(n,e){if(n.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}gc(n,n.state,new Set,e)}function gc(n,e,t,r){let s=e[$];if(s===void 0||t.has(s))return;t.add(s);let i=e.constructor[Symbol.metadata],o=i?.[bn];if(o===void 0)return;let a=i[us];for(let c=0;c<o.length;c++){let u=o[c];if(a!==void 0&&a.includes(u))continue;let d=i[u],h=e[d.name];h&&(Ee.is(d.type)?gc(n,h,t,r):Wg(n,h,t,r))}}function Wg(n,e,t,r){let s=e[Ce]??e,i=s[$];if(i===void 0||t.has(i))return;t.add(i);let o=n.resyncVisited.get(i);if(o===void 0)return;let a=n.root;s[wr](o,(c,u)=>{r?.push({ref:e,refId:i,op:R.DELETE,dynamicIndex:u,value:void 0,previousValue:c});let d=c?.[$];d!==void 0&&a.removeRef(d)},c=>{Ee.isSchema(c)&&gc(n,c,t,r)})}function yc(n,e,t,r,s,i,o,a,c){let u=n.root,d;if((e&R.DELETE)===R.DELETE){let h=s?.[$];h!==void 0&&u.removeRef(h),e!==R.DELETE_AND_ADD&&t[Rt](r),d=void 0}if(e!==R.DELETE)if(typeof i=="string")d=te[i](o,a);else if(Vn(i))d=pg(i.quantized,o,a);else if(Ee.is(i)){let h=te.number(o,a);if(d=u.refs.get(h),(e&R.ADD)===R.ADD){let m=n.getInstanceType(o,a,i);d||(d=n.createInstanceOfType(m)),u.addRef(h,d,d!==s||e===R.DELETE_AND_ADD&&d===s)}}else{let h=$d(Object.keys(i)[0]),m=te.number(o,a);n.resyncVisited!==null&&Hg(n,m);let g=u.refs.has(m)?s||u.refs.get(m):h.constructor.initializeForDecoder();if(d=g.clone(!0),d[X]=Object.values(i)[0],s){let p=s[$];if(p!==void 0&&m!==p){(e&R.DELETE)!==R.DELETE&&u.removeRef(p);let y=s.entries(),x;for(;(x=y.next())&&!x.done;){let[k,P]=x.value;typeof P=="object"&&(p=P[$]),c?.push({ref:s,refId:p,op:R.DELETE,field:k,value:void 0,previousValue:P})}}}u.addRef(m,d,g!==s||e===R.DELETE_AND_ADD&&g===s)}return d}function so(n,e,t,r){if(!(n instanceof e))throw new fs(`a '${e.name}' was expected, but '${n&&n.constructor.name}' was provided in ${t.constructor.name}#${r}`)}function Qd(n){return n!=null&&n[xd]===!0}function Ge(n){return(()=>new Bt(n))}function ws(n){if(Qd(n)){let e=n._type,t=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 ${t}.`)}return n}function $u(n){return new Bt({quantized:uc(n)})}function ry(n=io){return function(e,t){let r=ce.initialize(e.constructor);ce.setTag(r,t,n)}}function sy(n,e){let t=ce.initialize(n.constructor);ce.setUnreliable(t,e)}function iy(n,e){let t=ce.initialize(n.constructor);ce.setPatchOnly(t,e)}function ay(n,e,t){let r=oy[t],s=t==="string",i=t==="boolean";return function(o){let a=this[Ue],c=a[e];if(o!==c){if(o!=null){if(!i&&r!==void 0&&typeof o!==r&&!(s&&o===null)){let u=o&&o.constructor?` (${o.constructor.name})`:"";throw new fs(`a '${r}' was expected, but '${JSON.stringify(o)}'${u} was provided in ${this.constructor.name}#${n}`)}this.constructor[Dt](this[_],e,R.ADD)}else c!=null&&this[_].delete(e);a[e]=o}}}function cy(n,e,t){return function(r){let s=this[Ue],i=s[e];if(r!==i){if(r!=null){so(r,t,this,n);let o=this[_],a=this.constructor;i!=null&&i[_]?(o.root?.remove(i[_]),a[Dt](o,e,R.DELETE_AND_ADD)):a[Dt](o,e,R.ADD),r[_]?.setParent(this,o.root,e)}else i!=null&&this[_].delete(e);s[e]=r}}}function ly(n,e,t,r){let s=r.constructor===wn,i=r.constructor===_n;return function(o){let a=this[Ue],c=a[e];if(o!==c){if(o!=null){if(s&&!(o instanceof wn)){let h=new wn;h[X]=t,h.push(...o),o=h}else if(i&&!(o instanceof _n)){let h=new _n;if(h[X]=t,o instanceof Map)o.forEach((m,g)=>h.set(g,m));else for(let m in o)h.set(m,o[m]);o=h}else o[X]=t;let u=this[_],d=this.constructor;c!=null&&c[_]?(u.root?.remove(c[_]),d[Dt](u,e,R.DELETE_AND_ADD)):d[Dt](u,e,R.ADD),o[_]?.setParent(this,u.root,e)}else c!=null&&this[_].delete(e);a[e]=o}}}function uy(n,e,t){return function(r){let s=this[Ue],i=s[e];if(r!=null){if(typeof r!="number")throw new fs(`a 'number' was expected, but '${JSON.stringify(r)}' was provided in ${this.constructor.name}#${n}`);if(r=qd(t,jd(t,r)),r===i)return;this.constructor[Dt](this[_],e,R.ADD)}else{if(r===i)return;i!=null&&this[_].delete(e)}s[e]=r}}function dy(n,e,t,r){let s;return r?s=ly(n,e,t,r):typeof t=="string"?s=ay(n,e,t):Vn(t)?s=uy(n,e,t.quantized):s=cy(n,e,t),{get:function(){return this[Ue][e]},set:s,enumerable:!0,configurable:!0}}function fy(n=!0){return function(e,t){let r=ce.initialize(e.constructor);ce.setDeprecated(r,t),n&&(r[ot]??(r[ot]={}),r[ot][t]={get:function(){throw new Error(`${t} is deprecated.`)},set:function(s){},enumerable:!1,configurable:!0},Object.defineProperty(e,t,r[ot][t]))}}function hy(n){if(n&&typeof n=="object"){if(n.array!==void 0)return()=>new wn;if(n.map!==void 0)return()=>new _n;if(n.set!==void 0)return()=>new ps;if(n.collection!==void 0)return()=>new hs;if(n.stream!==void 0)return()=>new Wi}else if(typeof n=="function"&&Ee.is(n)&&(!n.prototype.initialize||n.prototype.initialize.length===0))return()=>new n}function _s(n,e,t=Ee){if(n==null||typeof n!="object")throw new Error(`schema(): first argument must be a fields object (got ${typeof n}).`);let r={},s={},i={},o={},a=(A,I)=>{typeof I=="function"?o[A]=I:I&&typeof I.clone=="function"?o[A]=()=>I.clone():i[A]=I},c=(A,I)=>{if(I.hasDefault)a(A,I.default);else if(!I.optional){let V=hy(I.type);V&&(o[A]=V)}},u={},d=[],h=[],m={},g=[],p=[],y={},x=[];for(let A in n){let I=n[A];if(Qd(I)){let V=I.toDefinition();if(V.noSync){if(V.view!==void 0||V.unreliable||V.patchOnly||V.fullStateOnly||V.stream)throw new Error(`schema(${e?`'${e}'`:""}): field '${A}' uses .noSync() together with a sync-only modifier (.view/.unreliable/.patchOnly/.fullStateOnly/.stream). A local-only field cannot be synchronized.`);c(A,V);continue}if(V.patchOnly&&V.fullStateOnly)throw new Error(`schema(${e?`'${e}'`:""}): field '${A}' 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 Z=br(V.type);if(typeof Z=="function"&&!Ee.is(Z))throw new Error(`schema(${e?`'${e}'`:""}): field '${A}' is a synced ref to non-Schema class '${Z.name||"(anonymous)"}' \u2014 use .noSync(), or Metadata.setFields().`);r[A]=Z,V.view!==void 0&&(u[A]=V.view),V.unreliable&&d.push(A),V.patchOnly&&h.push(A),V.deprecated&&(m[A]=V.deprecatedThrows),V.fullStateOnly&&g.push(A),V.stream&&p.push(A),V.streamPriority!==void 0&&(y[A]=V.streamPriority),V.optional&&x.push(A),c(A,V)}else if(typeof I=="function")Ee.is(I)?(r[A]=br(I),(!I.prototype.initialize||I.prototype.initialize.length===0)&&(o[A]=()=>new I)):s[A]=I;else throw new Error(`schema(${e?`'${e}'`:""}): field '${A}' must be a t.* builder, Schema subclass, or method (got ${typeof I}).`)}let k=A=>{for(let I in i)A[I]=i[I];for(let I in o)A[I]=o[I]()},P=()=>{let A={};return k(A),A},U=A=>{let I=Object.keys(r),V={};for(let Z in A)I.includes(Z)||(V[Z]=A[Z]);return V},N=typeof s.initialize=="function",C=s.initialize??t._initialize,O=class extends t{constructor(...A){let I=A[0];I===void 0?(super(),k(this)):super(Object.assign(P(),N?U(I):I)),C&&new.target===O&&C.apply(this,A)}};e&&Object.defineProperty(O,"name",{value:e}),ce.setFields(O,r),O._getDefaultValues=P,O._initialize=C,Object.assign(O.prototype,s);for(let A in u)ry(u[A])(O.prototype,A);for(let A of d)sy(O.prototype,A);for(let A of h)iy(O.prototype,A);for(let A in m)fy(m[A])(O.prototype,A);if(g.length>0||p.length>0){let A=O[Symbol.metadata];for(let I of g)ce.setFullStateOnly(A,I);for(let I of p)ce.setStream(A,I);for(let I in y)ce.setStreamPriority(A,I,y[I])}if(x.length>0){let A=O[Symbol.metadata];for(let I of x)A[A[I]].optional=!0}return O.extend=(A,I)=>_s(A,I,O),O}function py(n){return new Array(n).fill(0).map((e,t)=>t===n-1?"\u2514\u2500 ":" ").join("")}function my(n,e){if(e===-1||e>=n.length)return!1;let t=n.length-1;for(let r=e;r<t;r++)n[r]=n[r+1];return n.length=t,!0}function gy(n,e,t){let r=~t,s=n.changeTrees;for(let i in s){let o=s[i],a=o.visibleViews;a!==void 0&&e<a.length&&(a[e]&=r);let c=o.subscribedViews;c!==void 0&&e<c.length&&(c[e]&=r);let u=o.tagViews;u!==void 0&&u.forEach(d=>{e<d.length&&(d[e]&=r)})}}function ju(n){n.structSwitchEmitted||(n.shouldEmitSwitch&&(n.buffer[n.it.offset++]=255,Q.number(n.buffer,n.ref[$],n.it)),n.structSwitchEmitted=!0)}function by(n,e){ef(n,e,R.ADD)}function Zd(n,e){if(e._fullSyncGen===n.gen)return;if(e._fullSyncGen=n.gen,!n.hasView||n.view.isChangeTreeVisible(e)){let r=e.encDescriptor;n.changeTree=e,n.ref=e.ref,n.encoder=r.encoder,n.filter=r.filter,n.metadata=r.metadata,n.treeIsFiltered=e.isFiltered,n.isSchema=r.isSchema,n.filterBitmask=r.filterBitmask,n.tags=r.tags,n.structSwitchEmitted=!1,n.shouldEmitSwitch=n.hasView||n.it.offset>n.initialOffset||e!==n.rootChangeTree,e.isArray&&e.collDirty.size>0&&(e.flags|=pc),fc(e,n,by)}bs(e,n,wy)}function wy(n,e,t){Zd(n,e)}function ef(n,e,t){if(e<0){if(n.treeIsFiltered!==n.emitFiltered)return;ju(n),n.buffer[n.it.offset++]=Math.abs(e)&255;return}if((n.isSchema?n.treeIsFiltered||(e<32?(n.filterBitmask&1<<e)!==0:n.tags[e]!==void 0):n.treeIsFiltered)!==n.emitFiltered)return;let s=n.isEncodeAll?R.ADD:t;s!==void 0&&(n.filter!==void 0&&!n.filter(n.ref,e,n.view)||(ju(n),n.encoder(n.self,n.buffer,n.changeTree,e,s,n.it,n.isEncodeAll,n.hasView,n.metadata)))}function Qa(n,e){let t=new Uint8Array(n.length+e.length);return t.set(n,0),t.set(e,n.length),t}function Ki(n){let e=n.root,t=e.callbacks,r=new WeakMap,s;n.triggerChanges=function(a){let c=new Set;for(let u=0,d=a.length;u<d;u++){let h=a[u],m=h.refId,g=h.ref,p=t[m];if(p){if((h.op&R.DELETE)===R.DELETE&&Ee.isSchema(h.previousValue)){let y=t[h.previousValue[$]]?.[R.DELETE];for(let x=y?.length-1;x>=0;x--)y[x]()}if(Ee.isSchema(g)){if(!c.has(m)){let y=p?.[R.REPLACE];for(let x=y?.length-1;x>=0;x--)y[x]()}if(p.hasOwnProperty(h.field)){let y=p[h.field];for(let x=y?.length-1;x>=0;x--)y[x](h.value,h.previousValue)}}else{if((h.op&R.DELETE)===R.DELETE){if(h.previousValue!==void 0){let y=p[R.DELETE];for(let x=y?.length-1;x>=0;x--)y[x](h.previousValue,h.dynamicIndex??h.field)}if((h.op&R.ADD)===R.ADD){let y=p[R.ADD];for(let x=y?.length-1;x>=0;x--)y[x](h.value,h.dynamicIndex??h.field)}}else if((h.op&R.ADD)===R.ADD&&h.previousValue!==h.value){let y=p[R.ADD];for(let x=y?.length-1;x>=0;x--)y[x](h.value,h.dynamicIndex??h.field)}if(h.value!==h.previousValue&&(h.value!==void 0||h.previousValue!==void 0)){let y=p[R.REPLACE];for(let x=y?.length-1;x>=0;x--)y[x](h.value,h.dynamicIndex??h.field)}}c.add(m)}}};function i(a,c){let u=c.instance?.constructor[Symbol.metadata]||a,d=c.instance&&typeof c.instance.forEach=="function"||a&&!Ee.is(a);if(u&&!d){let h=function(m,g,p,y){return y&&c.instance[g]!==void 0&&!r.has(s)&&p(c.instance[g],void 0),e.addCallback(m[$],g,p)};return new Proxy({listen:function(g,p,y=!0){if(c.instance)return h(c.instance,g,p,y);{let x=()=>{};return c.onInstanceAvailable((k,P)=>{x=h(k,g,p,y&&P&&!r.has(s))}),()=>x()}},onChange:function(g){return e.addCallback(c.instance[$],R.REPLACE,g)},bindTo:function(g,p){return p||(p=Object.keys(u).map(y=>u[y].name)),e.addCallback(c.instance[$],R.REPLACE,()=>{p.forEach(y=>g[y]=c.instance[y])})}},{get(m,g){let p=u[u[g]];if(p){let y=c.instance?.[g],x=(k=>{let P=o(c.instance).listen(g,(U,N)=>{k(U,!1),P?.()},!1);y?.[$]!==void 0&&k(y,!0)});return i(p.type,{instance:y?.[$]!==void 0&&y,parentInstance:c.instance,onInstanceAvailable:x})}else return m[g]},has(m,g){return u[g]!==void 0},set(m,g,p){throw new Error("not allowed")},deleteProperty(m,g){throw new Error("not allowed")}})}else{let h=function(p,y,x){return x&&p.forEach((k,P)=>y(k,P)),e.addCallback(p[$],R.ADD,(k,P)=>{r.set(y,!0),s=y,y(k,P),r.delete(y),s=void 0})},m=function(p,y){return e.addCallback(p[$],R.DELETE,y)},g=function(p,y){return e.addCallback(p[$],R.REPLACE,y)};return new Proxy({onAdd:function(p,y=!0){if(c.instance)return h(c.instance,p,y&&!r.has(s));if(c.onInstanceAvailable){let x=()=>{};return c.onInstanceAvailable((k,P)=>{x=h(k,p,y&&P&&!r.has(s))}),()=>x()}},onRemove:function(p){if(c.instance)return m(c.instance,p);if(c.onInstanceAvailable){let y=()=>{};return c.onInstanceAvailable(x=>{y=m(x,p)}),()=>y()}},onChange:function(p){if(c.instance)return g(c.instance,p);if(c.onInstanceAvailable){let y=()=>{};return c.onInstanceAvailable(x=>{y=g(x,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,x){throw new Error("not allowed")},deleteProperty(p,y){throw new Error("not allowed")}})}}function o(a){return i(void 0,{instance:a})}return o}function _y(n,e){n.triggerChanges=e}var R,Mu,$,Dt,Nt,_t,qn,Te,Rt,wr,_,X,Ce,yn,Et,Vi,Ue,xd,ot,cs,Qt,Fe,bn,bt,Xt,Ln,us,ji,gr,at,Ni,qm,Xi,Fn,Za,Gm,Sd,Hm,Td,Q,gs,$n,Xm,Qm,Zm,eg,te,ac,ag,Vd,fg,Pt,jn,Du,yg,ce,Gd,tc,nc,zd,kg,Kd,Gi,Hi,Cg,Ig,Lu,Fi,Ug,Ka,Ya,as,Xa,ls,mr,$i,Ui,ds,pc,$g,En,rc,jg,qg,mc,Gg,Xd,wt,Jg,ro,Kg,fs,Yg,Uu,Gu,Hu,zu,Wu,Ju,Ku,Yu,it,wn,zi,Xu,Qu,Zu,ed,td,Ot,_n,nd,rd,sd,id,od,mn,hs,ad,cd,ld,ud,dd,gn,ps,fd,hd,pd,md,gd,Zt,Wi,yd,Bt,Xg,Qg,Zg,ey,ty,ny,Je,io,oy,bd,wd,_d,Ed,yt,Ee,Vu,sc,$_,yy,Mt,ms,Ji,qu,ic,St,tf,nf,rf,Tt,Yi,bc,He=Oe(()=>{"use strict";(function(n){n[n.ADD=128]="ADD",n[n.REPLACE=0]="REPLACE",n[n.DELETE=64]="DELETE",n[n.DELETE_AND_MOVE=96]="DELETE_AND_MOVE",n[n.MOVE_AND_ADD=160]="MOVE_AND_ADD",n[n.DELETE_AND_ADD=192]="DELETE_AND_ADD",n[n.CLEAR=10]="CLEAR",n[n.REVERSE=15]="REVERSE",n[n.MOVE=32]="MOVE",n[n.DELETE_BY_REFID=33]="DELETE_BY_REFID",n[n.ADD_BY_REFID=129]="ADD_BY_REFID"})(R||(R={}));Symbol.metadata??(Symbol.metadata=Symbol.for("Symbol.metadata"));Mu=(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 n="colyseus.symbolRegistry",e=Mu[n]||(Mu[n]=Object.create(null));Symbol.for=function(t){return e[t]||(e[t]=Symbol(t))},Symbol.keyFor=function(t){for(let r in e)if(e[r]===t)return r}}$=Symbol.for("$refId"),Dt="~track",Nt="~encoder",_t="~decoder",qn="~filter",Te="~getByIndex",Rt="~deleteByIndex",wr="~resyncPrune",_=Symbol.for("$changes"),X=Symbol.for("$childType"),Ce=Symbol.for("$proxyTarget"),yn="~onEncodeEnd",Et="~reset",Vi="~onDecodeEnd",Ue=Symbol.for("$values"),xd="~builder",ot="~descriptors",cs="~__encodeDescriptor",Qt="~encoders",Fe="~__numFields",bn="~__refTypeFieldIndexes",bt="~__viewFieldIndexes",Xt="$__fieldIndexesByViewTag",Ln="~__unreliableFieldIndexes",us="~__patchOnlyFieldIndexes",ji="~__fullSyncSkipIndexes",gr="~__fullStateOnlyFieldIndexes",at="~__streamFieldIndexes",Ni="~__streamPriorities";try{qm=new TextEncoder}catch{}Xi=new ArrayBuffer(8),Fn=new Int32Array(Xi),Za=new Float32Array(Xi),Gm=new Float64Array(Xi),Sd=new BigInt64Array(Xi),Hm=typeof Buffer<"u"&&Buffer.byteLength,Td=Hm?Buffer.byteLength:function(n,e){for(var t=0,r=0,s=0,i=n.length;s<i;s++)t=n.charCodeAt(s),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(s++,r+=4);return r};Q={int8:vd,uint8:zm,int16:Ad,uint16:oc,int32:en,uint32:Un,int64:Cd,uint64:Id,bigint64:Wm,biguint64:Jm,float32:Pd,float64:Od,boolean:Km,string:Ym,number:ec,utf8Write:kd,utf8Length:Td},gs=new ArrayBuffer(8),$n=new Int32Array(gs),Xm=new Float32Array(gs),Qm=new Float64Array(gs),Zm=new BigUint64Array(gs),eg=new BigInt64Array(gs);te={utf8Read:Md,int8:Dd,uint8:ys,int16:Nd,uint16:Qi,int32:xt,uint32:yr,float32:Bd,float64:Ld,int64:Fd,uint64:Ud,bigint64:tg,biguint64:ng,boolean:rg,string:sg,number:ig,stringCheck:og},ac={},ag=new Map;Vd="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.";fg={8:"uint8",16:"uint16",32:"uint32"};Pt=class Pt{constructor(e){l(this,"types",{});l(this,"schemas",new Map);l(this,"hasFilters",!1);e&&this.discoverTypes(e)}static register(e){let t=Object.getPrototypeOf(e);if(t!==Ee){let r=Pt.inheritedTypes.get(t);r||(r=new Set,Pt.inheritedTypes.set(t,r)),r.add(e)}}static cache(e){let t=Pt.cachedContexts.get(e);return t||(t=new Pt(e),Pt.cachedContexts.set(e,t)),t}has(e){return this.schemas.has(e)}get(e){return this.types[e]}add(e,t=this.schemas.size){return this.schemas.has(e)?!1:(this.types[t]=e,e[Symbol.metadata]==null&&ce.initialize(e),this.schemas.set(e,t),!0)}getTypeId(e){return this.schemas.get(e)}discoverTypes(e){if(!this.add(e))return;Pt.inheritedTypes.get(e)?.forEach(s=>{this.discoverTypes(s)});let t=e;for(;(t=Object.getPrototypeOf(t))&&t!==Ee&&t!==Function.prototype;)this.discoverTypes(t);let r=e[Symbol.metadata];(r[bt]||r[at])&&(this.hasFilters=!0);for(let s in r){let o=r[s].type;if(typeof o!="string"&&!Vn(o))if(typeof o=="function")this.discoverTypes(o);else{let a=Object.values(o)[0];if(typeof a=="string")continue;this.discoverTypes(a)}}}debug(){return`TypeContext ->
|
|
2
|
+
Schema types: ${this.schemas.size}
|
|
3
|
+
hasFilters: ${this.hasFilters}`}};l(Pt,"inheritedTypes",new WeakMap),l(Pt,"cachedContexts",new WeakMap);jn=Pt,Du=63;yg=[bn,Ln,us,ji,gr,at,Qt];ce={addField(n,e,t,r,s){if(e>=Du)throw new Error(`Can't define field '${t}'.
|
|
4
|
+
Schema instances may only have up to ${Du} fields.`);n[e]=Object.assign(n[e]||{},{type:br(r),index:e,name:t}),Object.defineProperty(n,ot,{value:n[ot]||{},enumerable:!1,configurable:!0}),s?n[ot][t]=s:n[ot][t]={value:void 0,writable:!0,enumerable:!0,configurable:!0},Object.defineProperty(n,Fe,{value:e,enumerable:!1,configurable:!0}),Object.defineProperty(n,t,{value:e,enumerable:!1,configurable:!0}),typeof n[e].type!="string"&&!Vn(n[e].type)&&(n[bn]===void 0&&Object.defineProperty(n,bn,{value:[],enumerable:!1,configurable:!0}),n[bn].push(e));let i=n[e].type;if(i&&typeof i=="object"&&i.stream!==void 0){if(i.array!==void 0)throw new Error(Vd);n[e].stream=!0,n[at]||Object.defineProperty(n,at,{value:[],enumerable:!1,configurable:!0,writable:!0}),n[at].includes(e)||n[at].push(e);let o=r?.priority;typeof o=="function"&&ce.setStreamPriority(n,t,o)}},setTag(n,e,t){let r=n[e],s=n[r];if(s.tag=t,n[bt]||(Object.defineProperty(n,bt,{value:[],enumerable:!1,configurable:!0}),Object.defineProperty(n,Xt,{value:{},enumerable:!1,configurable:!0})),n[bt].push(r),t<0)n[Xt][t]||(n[Xt][t]=[]),n[Xt][t].push(r);else for(let i=t;i>0;i&=i-1){let o=i&-i;n[Xt][o]||(n[Xt][o]=[]),n[Xt][o].push(r)}},setUnreliable(n,e){let t=n[e];if(typeof n[t].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".`);n[t].unreliable=!0,n[Ln]||Object.defineProperty(n,Ln,{value:[],enumerable:!1,configurable:!0,writable:!0}),n[Ln].push(t)},setPatchOnly(n,e){let t=n[e];if(n[t].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.`);n[t].patchOnly=!0,Bi(n,us,t),Bi(n,ji,t)},setDeprecated(n,e){let t=n[e];n[t].deprecated=!0,Bi(n,ji,t),Object.defineProperty(n,t,{value:n[t],enumerable:!1,configurable:!0})},setFullStateOnly(n,e){let t=n[e];if(n[t].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.`);n[t].fullStateOnly=!0,Bi(n,gr,t)},setStream(n,e){let t=n[e];n[t].stream=!0,n[at]||Object.defineProperty(n,at,{value:[],enumerable:!1,configurable:!0,writable:!0}),n[at].push(t)},setStreamPriority(n,e,t){let r=n[e];n[Ni]||Object.defineProperty(n,Ni,{value:{},enumerable:!1,configurable:!0,writable:!0}),n[Ni][r]=t},getStreamPriority(n,e){return n?.[Ni]?.[e]},defineField(n,e,t,r,s){let i=br(s),{complexTypeKlass:o,childType:a}=mg(i);ce.addField(e,t,r,i,dy(r,t,a,o)),e[ot][r]&&Object.defineProperty(n.prototype,r,e[ot][r]),(typeof i=="string"||Vn(i))&&(e[Qt]||Object.defineProperty(e,Qt,{value:[],enumerable:!1,configurable:!0,writable:!0}),e[Qt][t]=typeof i=="string"?Q[i]:hg(i.quantized))},setFields(n,e){let t=n.prototype.constructor;jn.register(t);let r=Object.getPrototypeOf(t),s=r&&r[Symbol.metadata],i=ce.initialize(t);t[Dt]||(t[Dt]=Ee[Dt]),t[Nt]||(t[Nt]=Ee[Nt]),t[_t]||(t[_t]=Ee[_t]),t.prototype.toJSON||(t.prototype.toJSON=Ee.prototype.toJSON);let o=i[Fe]??(s&&s[Fe])??-1;o++,i[Qt]||Object.defineProperty(i,Qt,{value:s?.[Qt]?[...s[Qt]]:[],enumerable:!1,configurable:!0,writable:!0});for(let a in e){if(i[a]!==void 0)throw new Error(`@colyseus/schema: Duplicate '${a}' definition on '${t.name||"(anonymous)"}'.`);ce.defineField(t,i,o,a,e[a]),o++}return n},isDeprecated(n,e){return n[e].deprecated===!0},initialize(n){let e=Object.getPrototypeOf(n),t=e[Symbol.metadata],r=n[Symbol.metadata]??Object.create(null);if(e!==Ee&&r===t&&(r=Object.create(null),t)){Object.setPrototypeOf(r,t),Object.defineProperty(r,Fe,{value:t[Fe],enumerable:!1,configurable:!0,writable:!0}),t[bt]!==void 0&&(Object.defineProperty(r,bt,{value:[...t[bt]],enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(r,Xt,{value:{...t[Xt]},enumerable:!1,configurable:!0,writable:!0}));for(let s of yg){let i=t[s];i!==void 0&&Object.defineProperty(r,s,{value:[...i],enumerable:!1,configurable:!0,writable:!0})}Object.defineProperty(r,ot,{value:{...t[ot]},enumerable:!1,configurable:!0,writable:!0})}return Object.defineProperty(n,Symbol.metadata,{value:r,writable:!1,configurable:!0}),r},isValidInstance(n){return n.constructor[Symbol.metadata]&&Object.prototype.hasOwnProperty.call(n.constructor[Symbol.metadata],Fe)},getFields(n){let e=n[Symbol.metadata],t={};for(let r=0;r<=e[Fe];r++)t[e[r].name]=e[r].type;return t},hasViewTagAtIndex(n,e){return n?.[bt]?.includes(e)},hasUnreliableAtIndex(n,e){return n?.[Ln]?.includes(e)},hasPatchOnlyAtIndex(n,e){return n?.[us]?.includes(e)},hasFullStateOnlyAtIndex(n,e){return n?.[gr]?.includes(e)},hasStreamAtIndex(n,e){return n?.[at]?.includes(e)}},Gd=(n,e,t)=>n(e,t),tc=class{constructor(e){l(this,"dirtyLow",0);l(this,"dirtyHigh",0);l(this,"ops");this.ops=new Uint8Array(Math.max(e+1,1))}record(e,t){let r=this.ops[e];r===0?this.ops[e]=t:r===R.DELETE?this.ops[e]=R.DELETE_AND_ADD:r===R.ADD&&t===R.DELETE_AND_ADD&&(this.ops[e]=R.DELETE_AND_ADD),e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordDelete(e,t){this.ops[e]=t,e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordRaw(e,t){this.record(e,t)}operationAt(e){let t=this.ops[e];return t===0?void 0:t}setOperationAt(e,t){this.ops[e]=t}forEach(e){this.forEachWithCtx(e,Gd)}forEachWithCtx(e,t){let r=this.dirtyLow,s=this.dirtyHigh,i=this.ops;for(;r!==0;){let o=r&-r,a=31-Math.clz32(o);r^=o,t(e,a,i[a])}for(;s!==0;){let o=s&-s,a=31-Math.clz32(o)+32;s^=o,t(e,a,i[a])}}size(){return qi(this.dirtyLow)+qi(this.dirtyHigh)}has(){return(this.dirtyLow|this.dirtyHigh)!==0}reset(){this.dirtyLow=0,this.dirtyHigh=0,this.ops.fill(0)}},nc=class{constructor(){l(this,"dirty",new Map);l(this,"pureOps",[])}record(e,t){let r=this.dirty.get(e);r===void 0?this.dirty.set(e,t):r===R.DELETE?this.dirty.set(e,R.DELETE_AND_ADD):r===R.ADD&&t===R.DELETE_AND_ADD&&this.dirty.set(e,R.DELETE_AND_ADD)}recordDelete(e,t){this.dirty.set(e,t)}recordRaw(e,t){this.dirty.set(e,t)}recordPure(e){this.pureOps.push([this.dirty.size,e])}operationAt(e){return this.dirty.get(e)}setOperationAt(e,t){this.dirty.has(e)&&this.dirty.set(e,t)}forEach(e){this.forEachWithCtx(e,Gd)}forEachWithCtx(e,t){let r=this.pureOps;if(r.length>0){let s=0,i=0;for(let[o,a]of this.dirty){for(;s<r.length&&r[s][0]<=i;){let c=r[s++][1];t(e,-c,c)}t(e,o,a),i++}for(;s<r.length;){let o=r[s++][1];t(e,-o,o)}}else for(let[s,i]of this.dirty)t(e,s,i)}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 t=new Map;for(let[r,s]of this.dirty)t.set(r+e,s);this.dirty=t}};zd=(n,e)=>{n.isFieldUnreliable(e)?n.ensureUnreliableRecorder().record(e,R.ADD):n.record(e,R.ADD)},kg=(n,e)=>n(e);Kd=1,Gi=2,Hi=4,Cg=Kd|Gi|Hi;Ig=(n,e,t)=>{hc(e)};Lu=[],Fi=0;Ug=(n,e,t)=>n(e,t);Ka=1,Ya=2,as=4,Xa=8,ls=16,mr=32,$i=64,Ui=128,ds=256,pc=512,$g=ls|mr,En=class{constructor(e,t=e){l(this,"ref");l(this,"refTarget");l(this,"metadata");l(this,"encDescriptor");l(this,"root");l(this,"parentRef");l(this,"_parentIndex");l(this,"extraParents");l(this,"flags",as);l(this,"_fullSyncGen",0);l(this,"_isSchema",!1);l(this,"dirtyLow",0);l(this,"dirtyHigh",0);l(this,"opsLow",0);l(this,"opsHigh",0);l(this,"ops");l(this,"collDirty");l(this,"collPureOps");l(this,"unreliableRecorder");l(this,"paused",!1);l(this,"changesNode");l(this,"unreliableChangesNode");l(this,"visibleViews");l(this,"tagViews");l(this,"subscribedViews");this.ref=e,this.refTarget=t;let r=dc(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 i=this.metadata?.[Fe]??0;i>7&&(this.ops=new Uint8Array(i+1))}else this.collDirty=new Map}get isArray(){return this.refTarget!==this.ref}get isFiltered(){return(this.flags&Ka)!==0}set isFiltered(e){this.flags=e?this.flags|Ka:this.flags&~Ka}get isVisibilitySharedWithParent(){return(this.flags&Ya)!==0}set isVisibilitySharedWithParent(e){this.flags=e?this.flags|Ya:this.flags&~Ya}get isNew(){return(this.flags&as)!==0}set isNew(e){this.flags=e?this.flags|as:this.flags&~as}get isUnreliable(){return(this.flags&Xa)!==0}set isUnreliable(e){this.flags=e?this.flags|Xa:this.flags&~Xa}get isPatchOnly(){return(this.flags&ls)!==0}set isPatchOnly(e){this.flags=e?this.flags|ls:this.flags&~ls}get isFullStateOnly(){return(this.flags&mr)!==0}set isFullStateOnly(e){this.flags=e?this.flags|mr:this.flags&~mr}get isStreamCollection(){return(this.flags&$i)!==0}set isStreamCollection(e){this.flags=e?this.flags|$i:this.flags&~$i}get needsRestage(){return(this.flags&Ui)!==0}set needsRestage(e){this.flags=e?this.flags|Ui:this.flags&~Ui}get hasFilteredFields(){return this.isFiltered||this.encDescriptor.hasAnyView}ensureUnreliableRecorder(){return this.unreliableRecorder===void 0&&(this.unreliableRecorder=this._isSchema?new tc(this.metadata?.[Fe]??0):new nc),this.unreliableRecorder}isFieldUnreliable(e){let t=this.encDescriptor;return t.hasAnyUnreliable?e<32?(t.unreliableBitmask&1<<e)!==0:ce.hasUnreliableAtIndex(this.metadata,e):!1}isFieldFullStateOnly(e){if(this.isFullStateOnly)return!0;let t=this.encDescriptor;return t.hasAnyFullStateOnly?e<32?(t.fullStateOnlyBitmask&1<<e)!==0:ce.hasFullStateOnlyAtIndex(this.metadata,e):!1}isFieldStream(e){let t=this.encDescriptor;return t.hasAnyStream?e<32?(t.streamBitmask&1<<e)!==0:ce.hasStreamAtIndex(this.metadata,e):!1}_opAt(e){let t=this.ops;if(t!==void 0)return t[e];let r=(e&3)<<3;return e<4?this.opsLow>>>r&255:this.opsHigh>>>r&255}_opPut(e,t){let r=this.ops;if(r!==void 0){r[e]=t;return}let s=(e&3)<<3,i=~(255<<s);e<4?this.opsLow=this.opsLow&i|t<<s:this.opsHigh=this.opsHigh&i|t<<s}_markDirty(e){e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}record(e,t){if(this._isSchema){let r=this._opAt(e);r===0?this._opPut(e,t):r===R.DELETE?this._opPut(e,R.DELETE_AND_ADD):r===R.ADD&&t===R.DELETE_AND_ADD&&this._opPut(e,R.DELETE_AND_ADD),this._markDirty(e)}else{let r=this.collDirty,s=r.get(e),i;s===void 0?i=t:s===R.DELETE||s===R.ADD&&t===R.DELETE_AND_ADD?i=R.DELETE_AND_ADD:i=s,r.set(e,i)}}recordDelete(e,t){this._isSchema?(this._opPut(e,t),this._markDirty(e)):this.collDirty.set(e,t)}recordRaw(e,t){this._isSchema?(this._opPut(e,t),this._markDirty(e)):this.collDirty.set(e,t)}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 t=this._opAt(e);return t===0?void 0:t}return this.collDirty.get(e)}setOperationAt(e,t){if(this._isSchema)this._opPut(e,t);else{let r=this.collDirty;r.has(e)&&r.set(e,t)}}forEach(e){this.forEachWithCtx(e,Ug)}forEachWithCtx(e,t){if(this._isSchema){let i=this.dirtyLow,o=this.dirtyHigh,a=this.ops;if(a!==void 0){for(;i!==0;){let c=i&-i,u=31-Math.clz32(c);i^=c,t(e,u,a[u])}for(;o!==0;){let c=o&-o,u=31-Math.clz32(c)+32;o^=c,t(e,u,a[u])}}else{let c=this.opsLow,u=this.opsHigh;for(;i!==0;){let d=i&-i,h=31-Math.clz32(d);i^=d,t(e,h,Fg(c,u,h))}}return}let r=this.collDirty,s=this.collPureOps;if(s!==void 0&&s.length>0){let i=0,o=0;for(let[a,c]of r){for(;i<s.length&&s[i][0]<=o;){let u=s[i++][1];t(e,-u,u)}t(e,a,c),o++}for(;i<s.length;){let a=s[i++][1];t(e,-a,a)}}else for(let[i,o]of r)t(e,i,o)}size(){return this._isSchema?qi(this.dirtyLow)+qi(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&=~pc}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=as|Ui,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,t){if(this._isSchema)throw new Error("ChangeTree (Schema): insertAt is not supported");let r=this.collDirty,s=new Map,i=!this.paused&&!this.isFullStateOnly;if(e>0)for(let[o,a]of r)o<e&&s.set(o,a);if(i)for(let o=0;o<t;o++)s.set(e+o,R.ADD);for(let[o,a]of r)o>=e&&s.set(o+t,a);this.collDirty=s,i&&this.root?.enqueueChangeTree(this)}removeAt(e,t){if(this._isSchema)throw new Error("ChangeTree (Schema): removeAt is not supported");let r=this.collDirty,s=e+t,i=!1;for(let a of r.keys())if(a>=s){i=!0;break}if(!i){for(let a=e;a<s;a++)r.delete(a);return}let o=new Map;for(let[a,c]of r)a<e?o.set(a,c):a>=s&&o.set(a-t,c);this.collDirty=o}unshift(e){this.insertAt(0,e)}setRoot(e){Og(this,e)}setParent(e,t,r){Mg(this,e,t,r)}forEachChild(e){Dg(this,e)}forEachChildWithCtx(e,t){bs(this,e,t)}forEachLive(e){vg(this,e)}forEachLiveWithCtx(e,t){fc(this,e,t)}operation(e){this.paused||this.isFullStateOnly||(this.recordPure(e),this.root?.enqueueChangeTree(this))}_routeAndRecord(e,t,r){if(!(this.paused||this.isFieldFullStateOnly(e))){if(this.isFieldUnreliable(e)&&!this.isNew){let s=this.ensureUnreliableRecorder();r?s.recordRaw(e,t):s.record(e,t),this.root?.enqueueUnreliable(this);return}r?this.recordRaw(e,t):this.record(e,t),this.root?.enqueueChangeTree(this)}}change(e,t=R.ADD){this._routeAndRecord(e,t,!1)}indexedOperation(e,t){this._routeAndRecord(e,t,!0)}getChange(e){return this.operationAt(e)}pause(){this.paused=!0}resume(){this.paused=!1}untracked(e){let t=this.paused;this.paused=!0;try{return e()}finally{this.paused=t}}markDirty(e,t=R.ADD){let r=this.paused;this.paused=!1;try{this.change(e,t)}finally{this.paused=r}}getValue(e,t=!1){return this.refTarget[Te](e,t)}delete(e,t){if(e===void 0){try{throw new Error(`@colyseus/schema ${this.ref.constructor.name}: trying to delete non-existing index '${e}'`)}catch(i){console.warn(i)}return}if(this.paused||this.isFieldFullStateOnly(e))return this.getValue(e);let r=this.isFieldUnreliable(e)&&!this.isNew;r?this.ensureUnreliableRecorder().recordDelete(e,t??R.DELETE):this.recordDelete(e,t??R.DELETE);let s=this.getValue(e);return s&&s[_]&&this.root?.remove(s[_]),r?this.root?.enqueueUnreliable(this):this.root?.enqueueChangeTree(this),s}endEncode(){this.reset(),this.changesNode=void 0,this._isSchema||this.refTarget[yn]?.(),this.isNew=!1}endEncodeUnreliable(){this.unreliableRecorder?.reset(),this.unreliableChangesNode=void 0,this._isSchema||this.refTarget[yn]?.()}discard(){this._isSchema||this.refTarget[yn]?.(),this.reset(),this.unreliableRecorder?.reset()}discardAll(){let e=t=>{if(t<0)return;let r=this.getValue(t);r&&r[_]&&r[_].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,t){wg(this,e,t)}setParentIndex(e,t){_g(this,e,t)}removeParent(e=this.parent){return Eg(this,e)}findParent(e){return Rg(this,e)}hasParent(e){return Hd(this,e)}indexInParent(e){return xg(this,e)}getAllParents(){return Sg(this)}},rc=class{constructor(e){l(this,"ref");l(this,"root");l(this,"parentRef");l(this,"paused",!1);l(this,"isNew",!1);l(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 t=this.ref;if(t[X]){if(typeof t[X]!="string")for(let[o,a]of t.entries())a&&e(a[_],t._collectionIndexes?.[o]??o);return}let s=t.constructor?.[Symbol.metadata];if(!s)return;let i=s[bn]??[];for(let o=0;o<i.length;o++){let a=i[o],c=t[s[a].name];c&&e(c[_],a)}}forEachChildWithCtx(e,t){this.forEachChild((r,s)=>t(e,r,s))}forEachLive(){}forEachLiveWithCtx(){}forEach(){}};jg=function(n,e,t,r,s,i,o,a){if(e[i.offset++]=(r|s)&255,s===R.DELETE)return;let c=t.encDescriptor,u=t.ref,d=u[Ue][r]??u[c.names[r]];no(n,e,c.types[r],d,s,i,c.encoders[r])},qg=function(n,e,t,r,s,i){if(e[i.offset++]=s&255,Q.number(e,r,i),s===R.DELETE)return;let o=t.ref;if((s&R.ADD)===R.ADD){let a=o.$indexes.get(r);Q.string(e,a,i)}no(n,e,o[X],o[Te](r),s,i)},mc=function(n,e,t,r,s,i){if(e[i.offset++]=s&255,Q.number(e,r,i),s===R.DELETE)return;let o=t.ref;no(n,e,o[X],o[Te](r),s,i)},Gg=function(n,e,t,r,s,i,o,a){let c=t.refTarget,u=c[X],d=typeof u!="string",h=a&&t.isFiltered&&d,m;if(h){let p=c.tmpItems[r];if(!p)return;if(m=p[$],s===R.DELETE)s=R.DELETE_BY_REFID;else if((s&R.ADD)===R.ADD)s=R.ADD_BY_REFID;else if((s&R.MOVE)===R.MOVE)return}else if(s===R.DELETE&&d){let p=c.tmpItems[r];if(!p)return;m=p[$],s=R.DELETE_BY_REFID}else m=r;if(e[i.offset++]=s&255,Q.number(e,m,i),s===R.DELETE||s===R.DELETE_BY_REFID)return;let g=c[Te](r,o);no(n,e,u,g,s,i)};Xd=-1,wt={Map:1,Array:2,Set:3,Collection:4,Stream:5};Jg=function(n,e,t,r,s){let i=e[t.offset++],o=r.constructor[Symbol.metadata],a=i>>6<<6,c=i%(a||255),u=o[c];if(u===void 0)return console.warn("@colyseus/schema: field not defined at",{index:c,ref:r.constructor.name,metadata:o}),Xd;let d=u.deprecated===!0,h=d?void 0:r[Te](c),m=yc(n,a,r,c,h,u.type,e,t,s);d||(m!=null&&(r[u.name]=m),h!==m&&s?.push({ref:r,refId:n.currentRefId,op:a,field:u.name,value:m,previousValue:h}))},ro=function(n,e,t,r,s){let i=r[Ce]??r,o=e[t.offset++];if(o===R.CLEAR){n.removeChildRefs(i,s),i.clear();return}let a=te.number(e,t),c=i[X],u=i.constructor.COLLECTION_KIND,d;(o&R.ADD)===R.ADD?u===wt.Map?(d=te.string(e,t),i.setIndex(a,d)):d=a:d=i.getIndex(a);let h=i[Te](a),m=yc(n,o,r,a,h,c,e,t,s);if(n.resyncVisited!==null&&Yd(n,r,o,d,h,m,s),m!=null)switch(u){case wt.Map:i.$items.set(d,m);break;case wt.Array:i.$setAt(a,m,n.resyncVisited!==null&&o===R.ADD?R.REPLACE:o);break;case wt.Set:case wt.Collection:case wt.Stream:i.$items.has(a)||(i.$items.set(a,m),typeof i.$refId=="number"&&a>=i.$refId&&(i.$refId=a+1));break;default:console.warn(`@colyseus/schema: missing COLLECTION_KIND on ${i.constructor?.name} \u2014 item at index ${a} was not stored.`);break}h!==m&&s?.push({ref:r,refId:n.currentRefId,op:o,dynamicIndex:d,value:m,previousValue:h})},Kg=function(n,e,t,r,s){let i=r[Ce]??r,o=e[t.offset++],a;if(o===R.CLEAR){n.removeChildRefs(i,s),i.clear();return}else if(o===R.REVERSE){i.items.reverse();return}else if(o===R.DELETE_BY_REFID){let m=te.number(e,t),g=n.root.refs.get(m);if(g===void 0||(n.root.removeRef(m),a=i.findIndex(p=>p===g),a===-1))return;i[Rt](a),s?.push({ref:r,refId:n.currentRefId,op:R.DELETE,dynamicIndex:a,value:void 0,previousValue:g});return}else if(o===R.ADD_BY_REFID){let m=te.number(e,t),g=n.root.refs.get(m);g&&(a=i.findIndex(p=>p===g)),(a===-1||a===void 0)&&(a=i.length)}else a=te.number(e,t);let c=i[X],u=a,d=i.items[a],h=yc(n,o,r,a,d,c,e,t,s);n.resyncVisited!==null&&Yd(n,r,o,a,d,h,s),h!=null&&h!==d&&i.$setAt(a,h,n.resyncVisited!==null&&o===R.ADD?R.REPLACE:o),d!==h&&s?.push({ref:r,refId:n.currentRefId,op:o,dynamicIndex:u,value:h,previousValue:d})},fs=class extends Error{};Yg=(n,e)=>{let t=n.toString(),r=e.toString();return t<r?-1:t>r?1:0},Uu={get:(n,e)=>typeof e!="symbol"&&!isNaN(e)?n.items[e]:Reflect.get(n,e),set:(n,e,t)=>{if(typeof e!="symbol"&&!isNaN(e)){if(t==null)n.$deleteAt(e);else{let r;if(t[_]){so(t,n[X],n,e);let s=n.items[e];n.isMovingItems?(r=n.$wireIndex(Number(e)),s!==void 0?t[_].isNew?n[_].indexedOperation(r,R.MOVE_AND_ADD):(n[_].getChange(r)&R.DELETE)===R.DELETE?n[_].indexedOperation(r,R.DELETE_AND_MOVE):n[_].indexedOperation(r,R.MOVE):t[_].isNew&&n[_].indexedOperation(r,R.ADD),t[_].setParent(n,n[_].root,r)):r=n.$changeAt(Number(e),t),s!==void 0&&s[_].root?.remove(s[_])}else r=n.$changeAt(Number(e),t);n.items[e]=t,r!==void 0&&(n.tmpItems[r]=t)}return!0}return Reflect.set(n,e,t)},deleteProperty:(n,e)=>(typeof e=="number"?n.$deleteAt(e):delete n[e],!0),has:(n,e)=>typeof e!="symbol"&&!isNaN(Number(e))?Reflect.has(n.items,e):Reflect.has(n,e)},it=class it{constructor(...e){l(this,Yu);l(this,Ku);l(this,Ju);l(this,Wu);l(this,"items",[]);l(this,"tmpItems",[]);l(this,"deletedIndexes",[]);l(this,"isMovingItems",!1);l(this,"_needsCompaction",!1);l(this,Gu);this[X]=void 0,this[Ce]=this;let t=new Proxy(this,Uu);return Object.defineProperty(this,_,{value:new En(t,this),enumerable:!1,writable:!0}),e.length>0&&this.push(...e),t}static[(Yu=_,Ku=$,Ju=Ce,Wu=X,zu=Nt,Hu=_t,qn)](e,t,r){if(!r)return!0;let s=e[Ce]??e;return typeof s[X]=="string"||r.isChangeTreeVisible(s.tmpItems[t]?.[_])}static is(e){return Array.isArray(e)||e.array!==void 0}static from(e){return new it(...Array.from(e))}static initializeForDecoder(){let e=Object.create(it.prototype);e.items=[],e.isMovingItems=!1,e._needsCompaction=!1,e[X]=void 0,e[Ce]=e;let t=new Proxy(e,Uu);return _r(e,t),t}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[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}push(...e){let t=this[Ce],r=t.items,s=t.tmpItems,i=t[_],o=t[X],a=s.length;for(let c=0,u=e.length;c<u;c++,a++){let d=e[c];if(d==null)return;typeof d=="object"&&o&&so(d,o,t,c),i.indexedOperation(a,R.ADD),r.push(d),s.push(d),d[_]?.setParent(this,i.root,a)}return a}pop(){let e=this[Ce],t=e.tmpItems,r=e.deletedIndexes,s=-1;for(let o=t.length-1;o>=0;o--)if(r[o]!==!0){s=o;break}if(s<0)return;let i=e.$isUnsentAdd(s);return e[_].delete(s),i?e.$cancelAdd(s):r[s]=!0,e.items.pop()}at(e){return e<0&&(e+=this.length),this.items[e]}$wireIndex(e){let t=this.deletedIndexes;if(t.length===0)return e;let r=this.tmpItems,s=0;for(let i=0;i<r.length;i++)if(t[i]!==!0){if(s===e)return i;s++}return r.length+(e-s)}$isUnsentAdd(e){let t=this[_];return(t.flags&(pc|$i))===0&&!t.paused&&typeof this[X]!="string"&&t.operationAt(e)===R.ADD}$cancelAdd(e,t=!0){let r=this[_],s=this.tmpItems[e];this.tmpItems.splice(e,1),this.deletedIndexes.length>0&&this.deletedIndexes.splice(e,1),r.removeAt(e,1);let i=s?.[_];i!==void 0&&i.root===void 0&&i.removeParent(this),t&&this.$reindexChildren(e)}$reindexChildren(e,t){if(!this[_].hasFilteredFields||typeof this[X]=="string")return;let r=this.tmpItems,s=r.length;if(t!==void 0)for(;e<s&&r[e]===t[e];)e++;for(let i=e;i<s;i++)r[i]?.[_]?.setParentIndex(this,i)}$changeAt(e,t){if(t==null){console.error("ArraySchema items cannot be null nor undefined; Use `splice(index, 1)` instead.");return}if(this.items[e]===t)return;let r=this.items[e]!==void 0?typeof t=="object"?R.DELETE_AND_ADD:R.REPLACE:R.ADD,s=this.$wireIndex(e),i=this[_];return i.change(s,r),t[_]?.setParent(this,i.root,s),s}$deleteAt(e,t){this[_].delete(this.$wireIndex(e),t)}$setAt(e,t,r){r===R.ADD&&this.items[e]!==void 0?this.items.splice(e,0,t):r===R.DELETE_AND_MOVE?(this.items.splice(e,1),this.items[e]=t):(e>this.items.length&&(this._needsCompaction=!0),this.items[e]=t)}clear(){let e=this[Ce];if(e.items.length===0)return;let t=e[_];t.forEachChild((r,s)=>{t.root?.remove(r)}),t.discard(),t.operation(R.CLEAR),e.items.length=0,e.tmpItems.length=0}[Et](){let e=this[Ce]??this,t=e[_];if(t.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]?.[Et]?.();e.items.length=0,e.tmpItems.length=0,e.deletedIndexes.length=0,t.recycle(),e[$]=void 0}concat(...e){return new it(...this.items.concat(...e))}join(e){return this.items.join(e)}reverse(){let e=this[Ce],t=e[_];if(t.has()||e.deletedIndexes.length>0){let r=e.items.slice().reverse();return this.clear(),this.push(...r),this}return t.operation(R.REVERSE),e.items.reverse(),e.tmpItems.reverse(),e.$reindexChildren(0),this}shift(){let e=this[Ce],t=e.items;if(t.length===0)return;let r=e[_],s=e.deletedIndexes,i=0;for(;s[i]===!0;)i++;let o=e.$isUnsentAdd(i);return r.delete(i,R.DELETE),o?e.$cancelAdd(i):s[i]=!0,t.shift()}slice(e,t){let r=new it;return r.push(...this.items.slice(e,t)),r}sort(e=Yg){let t=this[Ce];t.isMovingItems=!0;let r=t[_];return t.items.sort(e).forEach((i,o)=>r.change(o,R.REPLACE)),t.tmpItems.sort(e),t.$reindexChildren(0),t.isMovingItems=!1,this}splice(e,t,...r){let s=this[Ce],i=s[_],o=s.items,a=s.tmpItems,c=s.deletedIndexes,u=o.length,d=a.length,h=r.length,m=[];for(let p=0;p<d;p++)c[p]!==!0&&m.push(p);let g;if(u>e){t===void 0&&(t=u-e);for(let p=e;p<e+t;p++){let y=m[p],x=s.$isUnsentAdd(y);i.delete(y,R.DELETE),x?(g??(g=[])).push(y):c[y]=!0}}else t=0;if(h>0){let p=m[e]??u,y=Math.min(h,t);for(let k=0;k<y;k++){let P=p+k,U,N=g!==void 0?g.indexOf(P):-1;N!==-1?(g.splice(N,1),U=R.ADD):U=c[P]?R.DELETE_AND_ADD:R.ADD,i.indexedOperation(P,U),a[P]=r[k],c[P]=!1,r[k][_]?.setParent(this,i.root,P)}let x=h-y;if(x>0){let k=p+y;i.insertAt(k,x);for(let P=0;P<x;P++)r[y+P][_]?.setParent(this,i.root,k+P);c.length>0&&c.splice(k,0,...new Array(x).fill(!1)),a.splice(k,0,...r.slice(y)),s.$reindexChildren(k+x)}}if(g!==void 0&&g.length>0){for(let p=g.length-1;p>=0;p--)s.$cancelAdd(g[p],!1);s.$reindexChildren(g[0])}return i.root?.enqueueChangeTree(i),o.splice(e,t,...r)}unshift(...e){let t=this[Ce],r=t[_];r.unshift(e.length);for(let i=0;i<e.length;i++)e[i]?.[_]?.setParent(this,r.root,i);let s=t.deletedIndexes;return s.length>0&&s.unshift(...new Array(e.length).fill(!1)),t.tmpItems.unshift(...e),t.$reindexChildren(e.length),t.items.unshift(...e)}indexOf(e,t){return this.items.indexOf(e,t)}lastIndexOf(e,t=this.length-1){return this.items.lastIndexOf(e,t)}every(e,t){return this.items.every(e,t)}some(e,t){return this.items.some(e,t)}forEach(e,t){return this.items.forEach(e,t)}map(e,t){return this.items.map(e,t)}filter(e,t){return this.items.filter(e,t)}reduce(e,t){return this.items.reduce.apply(this.items,arguments)}reduceRight(e,t){return this.items.reduceRight.apply(this.items,arguments)}find(e,t){return this.items.find(e,t)}findIndex(e,t){return this.items.findIndex(e,t)}fill(e,t,r){throw new Error("ArraySchema#fill() not implemented")}copyWithin(e,t,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 it}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}includes(e,t){return this.items.includes(e,t)}flatMap(e,t){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,t){let r=this.items.slice();return e<0&&(e+=this.length),r[e]=t,new it(...r)}toReversed(){return this.items.slice().reverse()}toSorted(e){return this.items.slice().sort(e)}toSpliced(e,t,...r){let s=this.items.slice();return s.splice.apply(s,arguments),s}shuffle(){return this.move(e=>{let t=this.items.length;for(;t!=0;){let r=Math.floor(Math.random()*t);t--,[this[t],this[r]]=[this[r],this[t]]}})}move(e){return this.isMovingItems=!0,e(this),this.isMovingItems=!1,this}[(Gu=Symbol.unscopables,Te)](e,t=!1){let r=this[Ce]??this;return t||r.deletedIndexes[e]?r.items[e]:r.tmpItems[e]||r.items[e]}[Rt](e){let t=this[Ce]??this;t.items[e]=void 0,t._needsCompaction=!0}[yn](){let e=this.tmpItems;this.tmpItems=this.items.slice(),this.deletedIndexes.length>0&&(this.$reindexChildren(0,e),this.deletedIndexes.length=0)}[Vi](){let e=this[Ce]??this;e._needsCompaction&&(e._needsCompaction=!1,e.items=e.items.filter(t=>t!==void 0))}[wr](e,t,r){let s=this[Ce]??this,i=s.items,o=!1;for(let a=0;a<i.length;a++){let c=i[a];if(e.has(a)){r(c);continue}o=!0,t(c,a),s[Rt](a)}o&&s[Vi]()}toArray(){return this.items.slice(0)}toJSON(){return this.toArray().map(e=>typeof e.toJSON=="function"?e.toJSON():e)}clone(e){let t;return e?(t=new it,t.push(...this.items)):t=new it(...this.map(r=>r[_]?r.clone():r)),t}};l(it,zu,Gg),l(it,Hu,Kg),l(it,"COLLECTION_KIND",wt.Array);wn=it;nn("array",{constructor:wn});zi=class{constructor(){l(this,"keyByIndex",new Map);l(this,"indexByKey",Object.create(null));l(this,"nextIndex",0);l(this,"snapshots")}indexOf(e){let t=this.indexByKey[e];return t===void 0?void 0:t}assign(e){let t=this.nextIndex++;return this.indexByKey[e]=t,this.keyByIndex.set(t,e),t}snapshot(e,t){(this.snapshots??(this.snapshots=new Map)).set(e,t)}forgetSnapshot(e){this.snapshots?.delete(e)}snapshotAt(e){return this.snapshots?.get(e)}setIndex(e,t){this.keyByIndex.set(e,t),this.indexByKey[t]=e}keyOf(e){return this.keyByIndex.get(e)}cleanupAfterEncode(){if(this.snapshots!==void 0){for(let[e]of this.snapshots){let t=this.keyByIndex.get(e);t!==void 0&&(delete this.indexByKey[t],this.keyByIndex.delete(e))}this.snapshots.clear()}}reset(){this.indexByKey=Object.create(null),this.keyByIndex.clear(),this.snapshots?.clear(),this.nextIndex=0}},Ot=class Ot{constructor(e){l(this,td);l(this,ed);l(this,"childType");l(this,Zu);l(this,"$items",new Map);l(this,"journal",new zi);l(this,"_stream");if(Object.defineProperty(this,_,{value:new En(this),enumerable:!1,writable:!0}),this[X]=void 0,e)if(e instanceof Map||e instanceof Ot)e.forEach((t,r)=>this.set(r,t));else for(let t in e)this.set(t,e[t])}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=tn())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=tn())).priority=e}get $indexes(){return this.journal.keyByIndex}get _collectionIndexes(){return this.journal.indexByKey}static[(td=_,ed=$,Zu=X,Qu=Nt,Xu=_t,qn)](e,t,r){if(!r||typeof e[X]=="string")return!0;let s=e[Te](t)??e.journal.snapshotAt(t);return r.isChangeTreeVisible(s[_])}static is(e){return e.map!==void 0}static initializeForDecoder(){let e=Object.create(Ot.prototype);return e.$items=new Map,e.journal=new zi,e[X]=void 0,_r(e),e}[Symbol.iterator](){return this.$items[Symbol.iterator]()}get[Symbol.toStringTag](){return this.$items[Symbol.toStringTag]}static get[Symbol.species](){return Ot}set(e,t){if(t==null)throw new Error(`MapSchema#set('${e}', ${t}): trying to set ${t} value on '${e}'.`);typeof t=="object"&&this[X]&&so(t,this[X],this,e),e=e.toString();let r=this[_],s=t[_]!==void 0,i=this.journal,o=i.indexOf(e),a;if(o!==void 0){a=R.REPLACE;let c=this.$items.get(e);if(c===t)return;s&&(a=R.DELETE_AND_ADD,c!==void 0&&c[_].root?.remove(c[_])),i.snapshotAt(o)!==void 0&&i.forgetSnapshot(o)}else o=i.assign(e),a=R.ADD;return this.$items.set(e,t),a===R.ADD&&r.isStreamCollection?r.root!==void 0&&Zi(this,r.root,o):r.change(o,a),s&&t[_].setParent(this,r.root,o),this}get(e){return this.$items.get(e)}getOrInsert(e,t){return this.$items.has(e)?this.$items.get(e):(this.set(e,t),t)}getOrInsertComputed(e,t){if(this.$items.has(e))return this.$items.get(e);let r=t(e);return this.set(e,r),r}delete(e){if(!this.$items.has(e))return!1;let t=this.journal.indexOf(e),r=this.$items.get(e),s=this[_];if(s.isStreamCollection){let i=s.root,o=!1;return i!==void 0&&(o=eo(this,i,this[$],t)),r?.[_]!==void 0&&i?.remove(r[_]),this.$items.delete(e),o||this.journal.snapshot(t,r),!0}return this.journal.snapshot(t,r),s.delete(t),this.$items.delete(e)}clear(){let e=this[_];e.discard(),e.forEachChild((t,r)=>{e.root?.remove(t)}),this.journal.reset(),this.$items.clear(),e.operation(R.CLEAR)}[Et](){let e=this[_];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed MapSchema (pooling not supported).");this.$items.forEach(t=>t?.[Et]?.()),this.$items.clear(),this.journal.reset(),e.recycle(),this[$]=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[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}setIndex(e,t){this.journal.setIndex(e,t)}getIndex(e){return this.journal.keyOf(e)}[Te](e){let t=this.journal.keyOf(e);return t!==void 0?this.$items.get(t):void 0}[Rt](e){let t=this.journal.keyOf(e);t!==void 0&&(this.$items.delete(t),this.journal.keyByIndex.delete(e))}[wr](e,t,r){let s=null;if(this.$items.forEach((i,o)=>{if(e.has(o)){r(i);return}(s??(s=new Set)).add(o),t(i,o)}),s!==null){s.forEach(o=>{this.$items.delete(o),delete this.journal.indexByKey[o]});let i=[];this.journal.keyByIndex.forEach((o,a)=>{s.has(o)&&i.push(a)});for(let o=0;o<i.length;o++)this.journal.keyByIndex.delete(i[o])}}[yn](){this.journal.cleanupAfterEncode()}_dropView(e){to(this,e)}_unregister(){}toJSON(){return Object.fromEntries(Array.from(this,([t,r])=>[t,typeof r.toJSON=="function"?r.toJSON():r]))}clone(e){let t;return e?t=Object.assign(new Ot,this):(t=new Ot,this.forEach((r,s)=>{r[_]?t.set(s,r.clone()):t.set(s,r)})),t}};l(Ot,Qu,qg),l(Ot,Xu,ro),l(Ot,"COLLECTION_KIND",wt.Map);_n=Ot;nn("map",{constructor:_n});mn=class mn{constructor(e){l(this,od);l(this,id);l(this,sd);l(this,"$items",new Map);l(this,"deletedItems",{});l(this,"$refId",0);l(this,"_stream");Object.defineProperty(this,_,{value:new En(this),enumerable:!1,writable:!0}),this[X]=void 0,e&&e.forEach(t=>this.add(t))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=tn())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=tn())).priority=e}static[(od=_,id=$,sd=X,rd=Nt,nd=_t,qn)](e,t,r){return!r||typeof e[X]=="string"||r.isChangeTreeVisible((e[Te](t)??e.deletedItems[t])[_])}static is(e){return e.collection!==void 0}static initializeForDecoder(){let e=Object.create(mn.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[X]=void 0,_r(e),e}add(e){let t=this.$refId++,r=this[_];return this.$items.set(t,e),r.isStreamCollection?r.root!==void 0&&Zi(this,r.root,t):r.change(t),e[_]!==void 0&&e[_].setParent(this,r.root,t),t}at(e){let t=Array.from(this.$items.keys())[e];return this.$items.get(t)}entries(){return this.$items.entries()}delete(e){let t=this.$items.entries(),r,s;for(;(s=t.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let i=this[_];if(i.isStreamCollection){let o=i.root,a=this.$items.get(r);return o!==void 0&&eo(this,o,this[$],r),a?.[_]!==void 0&&o?.remove(a[_]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=i.delete(r),this.$items.delete(r)}clear(){let e=this[_];e.discard(),e.forEachChild((t,r)=>{e.root?.remove(t)}),this.$items.clear(),e.operation(R.CLEAR)}[Et](){let e=this[_];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed CollectionSchema (pooling not supported).");this.$items.forEach(t=>t?.[Et]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[$]=void 0}has(e){return Array.from(this.$items.values()).some(t=>t===e)}forEach(e){this.$items.forEach((t,r,s)=>e(t,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,t){}getIndex(e){return e}[Te](e){return this.$items.get(e)}[Rt](e){this.$items.delete(e)}[wr](e,t,r){let s=null;if(this.$items.forEach((i,o)=>{if(e.has(o)){r(i);return}(s??(s=[])).push(o),t(i,o)}),s!==null)for(let i=0;i<s.length;i++)this[Rt](s[i])}[yn](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){to(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((t,r)=>{e.push(typeof t.toJSON=="function"?t.toJSON():t)}),e}clone(e){let t;return e?t=Object.assign(new mn,this):(t=new mn,this.forEach(r=>{r[_]?t.add(r.clone()):t.add(r)})),t}};l(mn,rd,mc),l(mn,nd,ro),l(mn,"COLLECTION_KIND",wt.Collection);hs=mn;nn("collection",{constructor:hs});gn=class gn{constructor(e){l(this,dd);l(this,ud);l(this,ld);l(this,"$items",new Map);l(this,"deletedItems",{});l(this,"$refId",0);l(this,"_stream");Object.defineProperty(this,_,{value:new En(this),enumerable:!1,writable:!0}),this[X]=void 0,e&&e.forEach(t=>this.add(t))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=tn())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=tn())).priority=e}static[(dd=_,ud=$,ld=X,cd=Nt,ad=_t,qn)](e,t,r){return!r||typeof e[X]=="string"||r.isVisible((e[Te](t)??e.deletedItems[t])[_])}static is(e){return e.set!==void 0}static initializeForDecoder(){let e=Object.create(gn.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[X]=void 0,_r(e),e}add(e){if(this.has(e))return!1;let t=this.$refId++,r=this[_];return this.$items.set(t,e),r.isStreamCollection?r.root!==void 0&&Zi(this,r.root,t):r.change(t,R.ADD),e[_]!==void 0&&e[_].setParent(this,r.root,t),t}entries(){return this.$items.entries()}delete(e){let t=this.$items.entries(),r,s;for(;(s=t.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let i=this[_];if(i.isStreamCollection){let o=i.root,a=this.$items.get(r);return o!==void 0&&eo(this,o,this[$],r),a?.[_]!==void 0&&o?.remove(a[_]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=i.delete(r),this.$items.delete(r)}clear(){let e=this[_];e.discard(),this.$items.clear(),e.operation(R.CLEAR)}[Et](){let e=this[_];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed SetSchema (pooling not supported).");this.$items.forEach(t=>t?.[Et]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[$]=void 0}has(e){let t=this.$items.values(),r=!1,s;for(;(s=t.next())&&!s.done;)if(e===s.value){r=!0;break}return r}forEach(e){this.$items.forEach((t,r,s)=>e(t,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,t){}getIndex(e){return e}[Te](e){return this.$items.get(e)}[Rt](e){this.$items.delete(e)}[wr](e,t,r){let s=null;if(this.$items.forEach((i,o)=>{if(e.has(o)){r(i);return}(s??(s=[])).push(o),t(i,o)}),s!==null)for(let i=0;i<s.length;i++)this[Rt](s[i])}[yn](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){to(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((t,r)=>{e.push(typeof t.toJSON=="function"?t.toJSON():t)}),e}clone(e){let t;return e?t=Object.assign(new gn,this):(t=new gn,this.forEach(r=>{r[_]?t.add(r.clone()):t.add(r)})),t}};l(gn,cd,mc),l(gn,ad,ro),l(gn,"COLLECTION_KIND",wt.Set);ps=gn;nn("set",{constructor:ps});Zt=class Zt{constructor(){l(this,gd);l(this,md);l(this,pd);l(this,"$items",new Map);l(this,"$nextPosition",0);l(this,"_itemIndex",new Map);l(this,"_stream");Object.defineProperty(this,_,{value:new En(this),enumerable:!1,writable:!0}),this[X]=void 0}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=tn())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=tn())).priority=e}static[(gd=_,md=$,pd=X,hd=Nt,fd=_t,qn)](e,t,r){if(!r)return!0;let s=e[Te](t);return s===void 0?!1:r.isVisible(s[_])}static is(e){return e&&e.stream!==void 0}static initializeForDecoder(){let e=Object.create(Zt.prototype);return e.$items=new Map,e.$nextPosition=0,e._itemIndex=new Map,e[X]=void 0,_r(e),e}add(e){if(this._itemIndex.has(e))return-1;let t=this.$nextPosition++;this.$items.set(t,e),this._itemIndex.set(e,t);let s=this[_].root;return e[_]!==void 0&&e[_].setParent(this,s,t),s!==void 0&&Zi(this,s,t),t}remove(e){let t=this._itemIndex.get(e);if(t===void 0)return!1;this._itemIndex.delete(e),this.$items.delete(t);let r=this[_].root;return r!==void 0&&(eo(this,r,this[$],t),e[_]!==void 0&&r.remove(e[_])),!0}has(e){return this._itemIndex.has(e)}clear(){let e=this[_].root;if(e!==void 0){cg(this,e,this[$]);for(let t of this.$items.values())t[_]!==void 0&&e.remove(t[_])}this.$items.clear(),this._itemIndex.clear()}forEach(e){for(let[t,r]of this.$items)e(r,t,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,t){}getIndex(e){return e}[Te](e){return this.$items.get(e)}[Rt](e){let t=this.$items.get(e);t!==void 0&&(this._itemIndex.delete(t),this.$items.delete(e))}[wr](){}[yn](){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach(t=>{e.push(typeof t?.toJSON=="function"?t.toJSON():t)}),e}clone(e){if(e)return Object.assign(new Zt,this);let t=new Zt;return t.maxPerTick=this.maxPerTick,this.forEach(r=>{t.add(typeof r?.clone=="function"?r.clone():r)}),t}_dropView(e){to(this,e)}_unregister(){}};l(Zt,"$isStream",!0),l(Zt,hd,mc),l(Zt,fd,ro),l(Zt,"COLLECTION_KIND",wt.Stream);Wi=Zt;nn("stream",{constructor:Wi});yd=xd;Bt=class{constructor(e){l(this,yd,!0);l(this,"_type");l(this,"_default");l(this,"_hasDefault",!1);l(this,"_view");l(this,"_unreliable",!1);l(this,"_patchOnly",!1);l(this,"_deprecated",!1);l(this,"_deprecatedThrows",!0);l(this,"_fullStateOnly",!1);l(this,"_stream",!1);l(this,"_optional",!1);l(this,"_noSync",!1);l(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(Vd);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}}};Xg=(n=>new Bt({array:ws(n)})),Qg=(n=>new Bt({map:ws(n)})),Zg=(n=>new Bt({set:ws(n)})),ey=(n=>new Bt({collection:ws(n)})),ty=(n=>{let e=new Bt({stream:ws(n)});return e._stream=!0,e}),ny=(n=>new Bt(n));Je=Object.freeze({string:Ge("string"),number:Ge("number"),boolean:Ge("boolean"),int8:Ge("int8"),uint8:Ge("uint8"),int16:Ge("int16"),uint16:Ge("uint16"),int32:Ge("int32"),uint32:Ge("uint32"),int64:Ge("int64"),uint64:Ge("uint64"),float32:Ge("float32"),float64:Ge("float64"),bigint64:Ge("bigint64"),biguint64:Ge("biguint64"),ref:ny,array:Xg,map:Qg,set:Zg,collection:ey,stream:ty,quantized:$u,angle:n=>$u({min:0,max:Math.PI*2,mode:"wrap",bits:n?.bits??16})}),io=-1;oy={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"};yt=class yt{constructor(e){l(this,wd);l(this,bd);yt.initialize(this),e&&yt.assignProps(this,e)}static initialize(e){Object.defineProperty(e,_,{value:new En(e),enumerable:!1,writable:!0}),e[Ue]=[]}static initializeForDecoder(){let e=Object.create(this.prototype);return _r(e),e[Ue]=[],e}static reset(e){let t=e?.[_];if(t===void 0||typeof t.recycle!="function")throw new Error("@colyseus/schema: Schema.reset() requires a tracked (encoder-side) instance.");if(t.extraParents!==void 0)throw new Error(`@colyseus/schema: cannot reset a shared instance (${e.constructor.name}) with multiple parents.`);e[Et]()}[(Ed=Nt,_d=_t,wd=$,bd=Ue,Et)](){let t=this.constructor[Symbol.metadata]?.[bn]??[],r=this[Ue];for(let s=0;s<t.length;s++)r[t[s]]?.[Et]?.();this[_].recycle(),this[$]=void 0}static is(e){let t=e[Symbol.metadata];return typeof t=="object"&&t!==null}static isSchema(e){return typeof e?.assign=="function"}static[Dt](e,t,r=R.ADD){e.change(t,r)}static[qn](e,t,r){let i=e.constructor[Symbol.metadata][t]?.tag;return r===void 0?i===void 0:i===void 0?!0:i===io?r.isChangeTreeVisible(e[_]):r.hasTagOnTree(e[_],i)}assign(e){return yt.assignProps(this,e),this}static assignProps(e,t){let r=e.constructor[Symbol.metadata];if(r&&r[Fe]!==void 0)for(let i=0;i<=r[Fe];i++){let o=r[i];if(!o)continue;let a=t[o.name];a!==void 0&&(e[o.name]=a)}let s=Object.keys(t);for(let i=0;i<s.length;i++){let o=s[i];r&&r[o]!==void 0||(e[o]=t[o])}}restore(e){let t=this.constructor[Symbol.metadata];for(let r in t){let s=t[r],i=s.name,o=s.type,a=e[i];if(a!=null){if(typeof o=="string")this[i]=a;else if(yt.is(o)){let c=new o;c.restore(a),this[i]=c}else if(typeof o=="object"){let c=Object.keys(o)[0],u=o[c];if(c==="map"){let d=this[i];for(let h in a)if(yt.is(u)){let m=new u;m.restore(a[h]),d.set(h,m)}else d.set(h,a[h])}else if(c==="array"){let d=this[i];for(let h=0;h<a.length;h++)if(yt.is(u)){let m=new u;m.restore(a[h]),d.push(m)}else d.push(a[h])}}}}return this}setDirty(e,t){let r=this.constructor[Symbol.metadata];this[_].change(r[r[e]].index,t)}pauseTracking(){this[_].pause()}resumeTracking(){this[_].resume()}untracked(e){return this[_].untracked(e)}get isTrackingPaused(){return this[_].paused}clone(){let e=Object.create(this.constructor.prototype);yt.initialize(e);let t=this.constructor[Symbol.metadata];for(let r in t){let s=t[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={},t=this.constructor[Symbol.metadata];for(let r in t){let s=t[r],i=s.name;!s.deprecated&&this[i]!==null&&typeof this[i]<"u"&&(e[i]=typeof this[i].toJSON=="function"?this[i].toJSON():this[i])}return e}discardAllChanges(){this[_].discardAll()}[Te](e){let t=this.constructor[Symbol.metadata];return this[t[e].name]}[Rt](e){let t=this.constructor[Symbol.metadata];this[t[e].name]=void 0}static debugRefIds(e,t=!1,r=0,s,i=""){let o=t?` - ${JSON.stringify(e.toJSON())}`:"",a=e[_],c=e[$],u=s?s.root:a.root,d=u?.refCount?.[c]>1?` [\xD7${u.refCount[c]}]`:"",h=`${py(r)}${i}${e.constructor.name} (refId: ${c})${d}${o}
|
|
5
|
+
`;return a.forEachChild((m,g)=>{let p=g;typeof g=="number"&&e.$indexes&&(p=e.$indexes.get(g)??g);let y=e.forEach!==void 0&&p!==void 0?`["${p}"]: `:"";h+=this.debugRefIds(m.ref,t,r+1,s,y)}),h}static debugRefIdEncodingOrder(e,t="allChanges"){let r=[],s=e[_];if(t==="changes"){let c=s.root.changes?.next;for(;c;)c.changeTree&&r.push(c.changeTree.ref[$]),c=c.next;return r}let i=t==="allFilteredChanges",o=new Set,a=c=>{o.has(c)||(o.add(c),c.isFiltered===i&&r.push(c.ref[$]),c.forEachChild((u,d)=>a(u)))};return a(s),r}static debugRefIdsFromDecoder(e){return this.debugRefIds(e.state,!1,0,e)}static debugChanges(e,t=!1){let r=e[_],s=t?"allChanges":"changes",i=`${e.constructor.name} (${e[$]}) -> .${s}:
|
|
6
|
+
`;return t?r.forEachLive(o=>{i+=`- [${o}]: ADD (${JSON.stringify(r.getValue(Number(o),!0))})
|
|
7
|
+
`}):r.forEach((o,a)=>{o<0||!a||(i+=`- [${o}]: ${R[a]} (${JSON.stringify(r.getValue(Number(o),!1))})
|
|
8
|
+
`)}),i}};l(yt,Ed,jg),l(yt,_d,Jg);Ee=yt;Rd(Ee);Vu={value:0,enumerable:!1,writable:!0},sc=class{constructor(e,t=0){l(this,"types");l(this,"nextUniqueId",0);l(this,"refCount",{});l(this,"changeTrees",{});l(this,"changes",Fu());l(this,"unreliableChanges",Fu());l(this,"pendingFilterRefresh",[]);l(this,"_nodePool",[]);l(this,"_nextViewId",0);l(this,"_freeViewIds",[]);l(this,"activeViews",new Map);l(this,"streamTrees",new Set);this.types=e,this.nextUniqueId=t}enqueueFilterRefresh(e){this.types.hasFilters&&(e.flags&ds||(e.flags|=ds,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 t=e.id;for(let r of this.streamTrees)r._dropView(t)}forEachActiveView(e){for(let[t,r]of this.activeViews){let s=r.deref();if(s===void 0){this.activeViews.delete(t);for(let i of this.streamTrees)i._dropView(t);continue}e(s)}}registerStream(e){this.streamTrees.add(e)}unregisterStream(e){this.streamTrees.delete(e)}add(e){let t=e.ref;t[$]===void 0&&(Vu.value=this.nextUniqueId++,Object.defineProperty(t,$,Vu));let r=t[$],s=this.changeTrees[r]===void 0;s&&(this.changeTrees[r]=e);let i=this.refCount[r];return(i===0||e.needsRestage)&&(e.needsRestage=!1,e.forEachLiveWithCtx(e,zd)),this.refCount[r]=(i||0)+1,i>0&&this.enqueueFilterRefresh(e),s}remove(e){let t=e.ref[$],r=this.refCount[t]-1;if(r<=0){if(e.root=void 0,delete this.changeTrees[t],e.isStreamCollection){let s=e.ref;s._unregister?.(),this.unregisterStream(s)}this.removeFromQueue(e),this.removeFromUnreliableQueue(e),this.refCount[t]=0,e.forEachChild((s,i)=>{s.removeParent(e.ref)&&(s.parentRef===void 0||s.parentRef&&this.refCount[s.ref[$]]>0?this.remove(s):s.parentRef&&this.moveNextToParent(s))})}else this.refCount[t]=r,this.enqueueFilterRefresh(e),this.recursivelyMoveNextToParent(e);return r}recursivelyMoveNextToParent(e){this.moveNextToParent(e),e.forEachChild((t,r)=>this.recursivelyMoveNextToParent(t))}moveNextToParent(e){e.changesNode&&this._moveNextToParentInList(this.changes,e,e.changesNode,"changesNode"),e.unreliableChangesNode&&this._moveNextToParentInList(this.unreliableChanges,e,e.unreliableChangesNode,"unreliableChangesNode")}_moveNextToParentInList(e,t,r,s){let i=t.parent;if(!i||!i[_])return;let o=i[_][s];!o||o===r||r.position>o.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,t=e.changesNode){t||(e.changesNode=this._appendToList(this.changes,e))}enqueueUnreliable(e,t=e.unreliableChangesNode){t||(e.unreliableChangesNode=this._appendToList(this.unreliableChanges,e))}_appendToList(e,t){let r=this._nodePool,s;return r.length>0?(s=r.pop(),s.changeTree=t,s.next=void 0,s.prev=void 0):s={changeTree:t,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,t,r,s){return!r||r.changeTree!==t?!1:(r.prev?r.prev.next=r.next:e.next=r.next,r.next?r.next.prev=r.prev:e.tail=r.prev,t[s]=void 0,this.releaseNode(r),!0)}};$_=new FinalizationRegistry(({root:n,id:e,slot:t,bit:r})=>{gy(n,t,r),n.activeViews.delete(e);for(let s of n.streamTrees)s._dropView(e);n.releaseViewId(e)}),yy=-1;Mt=class Mt{constructor(e,t){l(this,"sharedBuffer",new Uint8Array(Mt.BUFFER_SIZE));l(this,"context");l(this,"state");l(this,"root");l(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});l(this,"_fullSyncGen",0);this.context=jn.cache(e.constructor),this.root=t??new sc(this.context),this.setState(e)}setState(e){this.state=e,this.state[_].setRoot(this.root)}encode(e={offset:0},t,r=this.sharedBuffer,s=e.offset){return this._encodeChannel(e,t,r,s,!1)}encodeUnreliable(e={offset:0},t,r=this.sharedBuffer,s=e.offset){return this._encodeChannel(e,t,r,s,!0)}_encodeChannel(e,t,r,s,i){this.root.pendingFilterRefresh.length>0&&Nu(this.root);let o=t!==void 0,a=this.state[_],c=this._encodeCtx;c.self=this,c.buffer=r,c.it=e,c.view=t,c.isEncodeAll=!1,c.hasView=o,c.emitFiltered=o;let d=i?this.root.unreliableChanges:this.root.changes;for(;d=d.next;){let h=d.changeTree;if(o&&!t.isChangeTreeVisible(h))continue;let m=i?h.unreliableRecorder:h;if(!m||!m.has())continue;let g=h.encDescriptor;c.changeTree=h,c.ref=h.ref,c.encoder=g.encoder,c.filter=g.filter,c.metadata=g.metadata,c.treeIsFiltered=h.isFiltered,c.isSchema=g.isSchema,c.filterBitmask=g.filterBitmask,c.tags=g.tags,c.structSwitchEmitted=!1,c.isRootTree=h===a,c.shouldEmitSwitch=o||e.offset>s||!c.isRootTree,m.forEachWithCtx(c,ef)}return!i&&!o&&this._isStreamBroadcastMode&&this._emitStreamBroadcast(r,e),e.offset>r.byteLength?(r=this._resizeBuffer(r,e.offset),e.offset=s,this._encodeChannel(e,t,r,s,i)):r.subarray(0,e.offset)}encodeFullSync(e,t,r,s,i=e.offset){this.root.pendingFilterRefresh.length>0&&Nu(this.root);let o=s!==void 0,a=this.state[_],c=this._encodeCtx;return c.self=this,c.buffer=t,c.it=e,c.view=s,c.isEncodeAll=!0,c.hasView=o,c.emitFiltered=r,c.gen=++this._fullSyncGen,c.initialOffset=i,c.rootChangeTree=a,Zd(c,a),e.offset>t.byteLength?(t=this._resizeBuffer(t,e.offset),e.offset=i,this.encodeFullSync(e,t,r,s,i)):t.subarray(0,e.offset)}_resizeBuffer(e,t){let r=Math.ceil(t/Mt.BUFFER_SIZE)*Mt.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
|
+
|
|
10
|
+
import { Encoder } from "@colyseus/schema";
|
|
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},t=this.sharedBuffer){return this.encodeFullSync(e,t,!1)}encodeAllView(e,t,r,s=this.sharedBuffer){let i=r.offset;return s=this.encodeFullSync(r,s,!0,e,i),Qa(s.subarray(0,t),s.subarray(i,r.offset))}ensureCapacity(e,t){if(t+Mt.BUFFER_SIZE<=e.byteLength)return e;let r=Math.ceil((t+Mt.BUFFER_SIZE)/Mt.BUFFER_SIZE)*Mt.BUFFER_SIZE,s=new Uint8Array(r);return s.set(e.subarray(0,t)),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeView(e,t,r,s=this.sharedBuffer){let i=r.offset;this._emitStreamPriority(e);for(let o of e.changes.keys()){let a=e.changes.get(o),c=this.root.changeTrees[o];if(c===void 0){e.changes.delete(o);continue}if(a.size===0)continue;let u=c.encDescriptor,d=u.encoder,h=u.metadata,m=c.ref,g=c.refTarget;s=this.ensureCapacity(s,r.offset),s[r.offset++]=255,Q.number(s,m[$],r);for(let[p,y]of a){let x;if(p===yy){let U=g.tmpItems,N=g.deletedIndexes;for(let C=0;C<U.length;C++)U[C]===void 0||N[C]===!0||d(this,s,c,C,R.ADD,r,!1,!0,h);continue}if(typeof p=="number")x=p;else{let U=p.indexInParent(m);if(U===void 0)continue;if(x=U,y===R.ADD&&c.getChange(x)===R.DELETE){e.changes.delete(p.ref[$]);continue}}let P=g[Te](x)!==void 0&&y||R.DELETE;d(this,s,c,x,P,r,!1,!0,h)}}return e.changes.clear(),s=this.encode(r,e,s),Qa(s.subarray(0,t),s.subarray(i,r.offset))}encodeUnreliableView(e,t,r,s=this.sharedBuffer){let i=r.offset;return s=this.encodeUnreliable(r,e,s,i),Qa(s.subarray(0,t),s.subarray(i,r.offset))}_emitStreamBroadcast(e,t){let r=this.root.streamTrees;for(let s of r){let i=s,o=i[_],a=i[$];if(a===void 0)continue;let c=i._stream,u=c.broadcastDeletes,d=c.broadcastPending,h=c.sentBroadcast,m=u.size>0,g=d.size>0,p=o.encDescriptor,y=p.encoder,x=p.metadata;if(m||g){if(e[t.offset++]=255,Q.number(e,a,t),m){for(let C of u)y(this,e,o,C,R.DELETE,t,!1,!1,x);u.clear()}let k=c.maxPerTick,P=[],U=0,N=[];for(let C of d){if(U>=k)break;let O=i[Te](C);if(O===void 0){N.push(C);continue}y(this,e,o,C,R.ADD,t,!1,!1,x),h.add(C),P.push(O),N.push(C),U++}for(let C of N)d.delete(C);for(let C of P){let O=C[_];if(O===void 0)continue;let A=C[$];if(A===void 0)continue;e[t.offset++]=255,Q.number(e,A,t);let I=O.encDescriptor,V=I.encoder,Z=I.metadata;O.forEachLive(ee=>{ce.hasUnreliableAtIndex(Z,ee)||V(this,e,O,ee,R.ADD,t,!1,!1,Z)})}}for(let k of h){let P=i[Te](k);if(P===void 0)continue;let U=P[_];if(U===void 0||!U.has())continue;let N=P[$];if(N===void 0)continue;e[t.offset++]=255,Q.number(e,N,t);let C=U.encDescriptor,O=C.encoder,A=C.metadata;U.forEach((I,V)=>{I<0||ce.hasUnreliableAtIndex(A,I)||O(this,e,U,I,V,t,!1,!1,A)})}}}_emitStreamPriority(e){let t=this.root.streamTrees;if(t.size===0)return;let r=e.id;for(let s of t){let i=s,o=i._stream,a=o.pendingByView.get(r);if(a===void 0||a.size===0)continue;let c=o.priorityByView?.get(r),u=c!==void 0,d=o.priority,h=o.maxPerTick,m=[],g=[];if(u||d!==void 0){let x=[],k=[],P=0;for(let U of a){let N=i[Te](U);if(N===void 0){g.push(U);continue}let C=u?c(N):d(e,N);if(P<h){let O=P++;for(;O>0&&k[O-1]<C;)k[O]=k[O-1],x[O]=x[O-1],O--;k[O]=C,x[O]=U}else if(C>k[h-1]){let O=h-1;for(;O>0&&k[O-1]<C;)k[O]=k[O-1],x[O]=x[O-1],O--;k[O]=C,x[O]=U}}for(let U=0;U<P;U++)m.push(x[U])}else for(let x of a){if(m.length>=h)break;m.push(x)}for(let x of g)a.delete(x);let p=m.length,y=o.sentByView.get(r);y===void 0&&(y=new Set,o.sentByView.set(r,y));for(let x=0;x<p;x++){let k=m[x],P=i[Te](k);if(P===void 0){a.delete(k);continue}e._addImmediate(P);let U=P[_];if(U!==void 0){let N=P[$],C=e.changes.get(N);C===void 0&&(C=new Map,e.changes.set(N,C));let O=U.metadata;U.forEachLive(A=>{ce.hasUnreliableAtIndex(O,A)||C.set(A,R.ADD)})}a.delete(k),y.add(k)}}}discardChanges(){let e=this.root.changes,t=e.next,r=this.root;for(;t;){let s=t.next;t.changeTree.endEncode(),r.releaseNode(t),t=s}e.next=void 0,e.tail=void 0}discardUnreliableChanges(){let e=this.root.unreliableChanges,t=e.next,r=this.root;for(;t;){let s=t.next;t.changeTree.endEncodeUnreliable(),r.releaseNode(t),t=s}e.next=void 0,e.tail=void 0}tryEncodeTypeId(e,t,r,s){let i=this.context.getTypeId(t),o=this.context.getTypeId(r);if(o===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}i!==o&&(e[s.offset++]=213,Q.number(e,o,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 t=e.activeViews.size===0;for(let r of e.streamTrees)if(t?ug(r):lg(r,e))return!0;return!1}get hasUnreliableChanges(){return this.root.unreliableChanges.next!==void 0}};l(Mt,"BUFFER_SIZE",16*1024);ms=Mt,Ji=class extends Error{constructor(e){super(e),this.name="DecodingWarning"}},qu={value:0,enumerable:!1,writable:!0},ic=class{constructor(){l(this,"refs",new Map);l(this,"refCount",{});l(this,"deletedRefs",new Set);l(this,"callbacks",{});l(this,"nextUniqueId",0)}getNextUniqueId(){return this.nextUniqueId++}addRef(e,t,r=!0){this.refs.set(e,t),t[$]===void 0?(qu.value=e,Object.defineProperty(t,$,qu)):t[$]!==e&&(t[$]=e),r&&(this.refCount[e]=(this.refCount[e]||0)+1),this.deletedRefs.has(e)&&this.deletedRefs.delete(e)}removeRef(e){let t=this.refCount[e];if(t===void 0){try{throw new Ji("trying to remove refId that doesn't exist: "+e)}catch(r){console.warn(r)}return}if(t===0){try{let r=this.refs.get(e);throw new Ji(`trying to remove refId '${e}' with 0 refCount (${r.constructor.name}: ${JSON.stringify(r)})`)}catch(r){console.warn(r)}return}(this.refCount[e]=t-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 t=this.refs.get(e),r=t.constructor[Symbol.metadata];if(r!=null)for(let s in r){let i=r[s].name,o=t[i];if(typeof o=="object"&&o){let a=o[$];a!==void 0&&!this.deletedRefs.has(a)&&this.removeRef(a)}}else typeof t[X]=="function"&&Array.from(t.values()).forEach(s=>{let i=s[$];i!==void 0&&!this.deletedRefs.has(i)&&this.removeRef(i)});this.refs.delete(e),delete this.refCount[e],delete this.callbacks[e]}),this.deletedRefs.clear()}addCallback(e,t,r){if(e===void 0){let s=typeof t=="number"?R[t]:t;throw new Error(`Can't addCallback on '${s}' (refId is undefined)`)}return this.callbacks[e]||(this.callbacks[e]={}),this.callbacks[e][t]||(this.callbacks[e][t]=[]),this.callbacks[e][t].push(r),()=>this.removeCallback(e,t,r)}removeCallback(e,t,r){let s=this.callbacks?.[e]?.[t]?.indexOf(r);s!==void 0&&s!==-1&&my(this.callbacks[e][t],s)}},St=class{constructor(e,t){l(this,"context");l(this,"state");l(this,"root");l(this,"currentRefId",0);l(this,"triggerChanges");l(this,"resyncVisited",null);l(this,"resyncDamaged",!1);this.setState(e),this.context=t||new jn(e.constructor)}setState(e){this.state=e,this.root=new ic,this.root.addRef(0,e)}decode(e,t={offset:0},r=this.state){let s=this.triggerChanges!==void 0?[]:null,i=this.root,o=e.byteLength,a=r.constructor[_t];for(this.currentRefId=0;t.offset<o;){if(e[t.offset]==255){t.offset++,r[Vi]?.();let u=te.number(e,t),d=i.refs.get(u);d?(r=d,a=r.constructor[_t],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,t,o));continue}if(a(this,e,t,r,s)===Xd){console.warn("@colyseus/schema: definition mismatch"),this.skipCurrentStructure(e,t,o);continue}}return r[Vi]?.(),this.resyncVisited!==null&&zg(this,s),s!==null&&this.triggerChanges?.(s),i.garbageCollectDeletedRefs(),s}decodeResync(e,t={offset:0}){this.resyncVisited=new Map,this.resyncDamaged=!1;try{return this.decode(e,t)}finally{this.resyncVisited=null}}skipCurrentStructure(e,t,r){this.resyncVisited!==null&&(this.resyncDamaged=!0);let s={offset:t.offset};for(;t.offset<r&&!(e[t.offset]===255&&(s.offset=t.offset+1,this.root.refs.has(te.number(e,s))));)t.offset++}getInstanceType(e,t,r){let s;if(e[t.offset]===213){t.offset++;let i=te.number(e,t);s=this.context.get(i)}return s||r}createInstanceOfType(e){return e.initializeForDecoder()}removeChildRefs(e,t){let r=typeof e[X]!="string",s=e[$];e.forEach((i,o)=>{t?.push({ref:e,refId:s,op:R.DELETE,field:o,value:void 0,previousValue:i}),r&&this.root.removeRef(i[$])})}},tf=_s({min:Je.float64(),max:Je.float64(),bits:Je.uint8(),mode:Je.uint8()},"QuantizedDescriptor"),nf=_s({name:Je.string(),type:Je.string(),referencedType:Je.number(),childPrimitive:Je.string(),quantized:Je.ref(tf).optional()},"ReflectionField"),rf=_s({id:Je.number(),extendsId:Je.number(),fields:Je.array(nf)},"ReflectionType"),Tt=_s({types:Je.array(rf),rootType:Je.number()},"Reflection");Tt.encode=function(n,e={offset:0}){let t=n.context,r=new Tt,s=new ms(r),i=t.schemas.get(n.state.constructor);i>0&&(r.rootType=i);let o=new Set,a={},c=d=>{if(d.extendsId===void 0||o.has(d.extendsId)){o.add(d.id),r.types.push(d);let h=a[d.id];h!==void 0&&(delete a[d.id],h.forEach(m=>c(m)))}else a[d.extendsId]===void 0&&(a[d.extendsId]=[]),a[d.extendsId].push(d)};t.schemas.forEach((d,h)=>{let m=new rf;m.id=Number(d);let g=Object.getPrototypeOf(h);g!==Ee&&(m.extendsId=t.schemas.get(g));let p=h[Symbol.metadata];if(p!==g[Symbol.metadata]){let y=p[Fe]??-1;for(let x=0;x<=y;x++){let k=p[x];if(k===void 0)continue;let P=k.name;if(!Object.prototype.hasOwnProperty.call(p,P))continue;let U=new nf;U.name=P;let N;if(typeof k.type=="string")N=k.type;else if(Vn(k.type)){let C=k.type.quantized;N="quantized";let O=new tf;O.min=C.min,O.max=C.max,O.bits=C.bits,O.mode=C.wrap?1:0,U.quantized=O}else{let C;Ee.is(k.type)?(N="ref",C=k.type):(N=Object.keys(k.type)[0],typeof k.type[N]=="string"?U.childPrimitive=k.type[N]:C=k.type[N]),U.referencedType=C?t.getTypeId(C):-1}U.type=N,m.fields.push(U)}}c(m)});for(let d in a)a[d].forEach(h=>r.types.push(h));return s.encodeAll(e).slice(0,e.offset)};Tt.decode=function(n,e){let t=new Tt;new St(t).decode(n,e);let s=new jn;t.types.forEach(a=>{let c=s.get(a.extendsId)??Ee,u=class extends c{};jn.register(u),s.add(u,a.id)},{});let i=(a,c,u)=>{c.fields.forEach((d,h)=>{let m=u+h;if(d.quantized!==void 0){let g=d.quantized;ce.addField(a,m,d.name,{quantized:uc({min:g.min,max:g.max,bits:g.bits,mode:g.mode===1?"wrap":"clamp"})})}else if(d.referencedType!==void 0){let g=d.type,p=s.get(d.referencedType)??d.childPrimitive;g==="ref"?ce.addField(a,m,d.name,p):ce.addField(a,m,d.name,{[g]:p})}else ce.addField(a,m,d.name,d.type)})};t.types.forEach(a=>{let c=s.get(a.id),u=ce.initialize(c),d=[],h=a;do d.push(h),h=t.types.find(g=>g.id===h.extendsId);while(h);let m=0;d.reverse().forEach(g=>{i(u,g,m),m+=g.fields.length})});let o=new(s.get(t.rootType||0));return new St(o,s)};Tt.makeEncodable=function(n){let e=n[Symbol.metadata];if(!e)return n;let t=e[Fe];if(t===void 0)return n;for(let r=0;r<=t;r++){let s=e[r];s&&ce.defineField(n,e,r,s.name,s.type)}return Object.prototype.hasOwnProperty.call(n,cs)&&delete n[cs],n};Yi=class{constructor(e){l(this,"decoder");l(this,"uniqueRefIds",new Set);l(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,t,r){return this.decoder.root.addCallback(e,t,r)}addCallbackOrWaitCollectionAvailable(e,t,r,s,i=!0){let o=()=>{},a=()=>o(),c=e[t];if(!c||c[$]===void 0){let u;return u=this.addCallback(e[$],t,(d,h)=>{d!=null&&(u(),o=this.addCallback(d[$],r,s))}),o=u,a}else return i=i&&this.isTriggering===!1,r===R.ADD&&i&&c.forEach((u,d)=>{s(u,d)}),this.addCallback(c[$],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,t,r,s=!0){s=s&&this.isTriggering===!1;let i=e[t];return s&&i!==null&&i!==void 0&&r(i,void 0),this.addCallback(e[$],t,r)}onChange(...e){if(e.length===2&&typeof e[0]!="string"){let t=e[0],r=e[1];return this.addCallback(t[$],R.REPLACE,r)}return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],R.REPLACE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],R.REPLACE,e[2])}onAdd(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],R.ADD,e[1],e[2]!==!1):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],R.ADD,e[2],e[3]!==!1)}onRemove(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],R.DELETE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],R.DELETE,e[2])}bindTo(e,t,r,s=!0){let i=e.constructor[Symbol.metadata];r||(r=Object.keys(i).filter(a=>!isNaN(Number(a))).map(a=>i[a].name));let o=()=>{for(let a of r){let c=e[a];c!==void 0&&(t[a]=c)}};return s&&o(),this.addCallback(e[$],R.REPLACE,o)}triggerChanges(e){this.uniqueRefIds.clear(),this.isTriggering=!0;for(let t=0,r=e.length;t<r;t++){let s=e[t],i=s.refId,o=s.ref,a=this.callbacks[i];if(a){if((s.op&R.DELETE)===R.DELETE&&Ee.isSchema(s.previousValue)){let c=s.previousValue[$],u=this.callbacks[c]?.[R.DELETE];if(u)for(let d=u.length-1;d>=0;d--)try{u[d]()}catch(h){console.error(h)}}if(Ee.isSchema(o)){if(!this.uniqueRefIds.has(i)){let u=a[R.REPLACE];if(u)for(let d=u.length-1;d>=0;d--)try{u[d]()}catch(h){console.error(h)}}let c=a[s.field];if(c)for(let u=c.length-1;u>=0;u--)try{c[u](s.value,s.previousValue)}catch(d){console.error(d)}}else{let c=s.dynamicIndex??s.field;if((s.op&R.DELETE)===R.DELETE){if(s.previousValue!==void 0){let u=a[R.DELETE];if(u)for(let d=u.length-1;d>=0;d--)try{u[d](s.previousValue,c)}catch(h){console.error(h)}}if((s.op&R.ADD)===R.ADD){let u=a[R.ADD];if(u)for(let d=u.length-1;d>=0;d--)try{u[d](s.value,c)}catch(h){console.error(h)}}}else if((s.op&R.ADD)===R.ADD&&s.previousValue!==s.value){let u=a[R.ADD];if(u)for(let d=u.length-1;d>=0;d--)try{u[d](s.value,c)}catch(h){console.error(h)}}if(s.value!==s.previousValue){let u=a[R.REPLACE];if(u)for(let d=u.length-1;d>=0;d--)try{u[d](c,s.value)}catch(h){console.error(h)}}}this.uniqueRefIds.add(i)}}this.isTriggering=!1}},bc={get(n){if(n instanceof St)return new Yi(n);if("decoder"in n.serializer)return new Yi(n.serializer.decoder);throw new Error("Invalid room or decoder")},getLegacy(n){if(n instanceof St)return Ki(n);if("decoder"in n.serializer)return Ki(n.serializer.decoder);throw new Error("Invalid room or decoder")},getRawChanges(n,e){return _y(n,e)}};nn("map",{constructor:_n});nn("array",{constructor:wn});nn("set",{constructor:ps});nn("collection",{constructor:hs})});function $e(){return typeof performance<"u"?performance.now():Date.now()}var Es=Oe(()=>{"use strict"});function ao(n,e){let t=globalThis,r=t.__colyseusDebug;if(!r){let s=[];r=t.__colyseusDebug={__buffer:s,publish(i,o){s.push([i,Ey(o)]),s.length>Ry&&s.shift()}}}r.publish(n,e)}function co(){if(typeof globalThis>"u")return!1;let n=globalThis.__colyseusDebug;return n!=null&&n.__buffer===void 0}var Ey,Ry,Rs=Oe(()=>{"use strict";Ey=typeof WeakRef<"u"?n=>new WeakRef(n):n=>({deref:()=>n}),Ry=64});function Ke(n){return n[$]}function Lt(n){return n.constructor[xy]}function xs(n,e){let t=Lt(n)?.[e];return typeof t=="number"?t:-1}function of(n){let e=Lt(n);if(!e)return[];let t=[];for(let r=0;;r++){let s=e[r];if(!s||typeof s.name!="string")break;typeof s.type=="string"&&t.push(s.name)}return t}function Ss(n){let e=Lt(n),t=[],r=[];if(e)for(let s=0;;s++){let i=e[s];if(!i||typeof i.name!="string")break;typeof i.type=="string"&&(t.push(i.name),Sy[i.type]===void 0&&r.push(i.name))}return{fields:t,numeric:r}}function ky(n){if(Number.isNaN(n))return 0;if(!Number.isFinite(n))return n>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER;if(n!==(n|0)&&Math.abs(n)<=34028235e31){let e=Math.fround(n);if(Math.abs(Math.abs(e)-Math.abs(n))<1e-4)return e}return n}function af(n,e){let t=Lt(n),r=t?.[e];switch((typeof r=="number"?t[r]:void 0)?.type){case"float32":return Math.fround;case"number":return ky;default:return Ty}}function cf(n){if(n.length>vy){let k=n;return P=>{let U={};for(let N=0;N<k.length;N++)U[k[N]]=P[k[N]];return U}}let e=n[0],t=n[1],r=n[2],s=n[3],i=n[4],o=n[5],a=n[6],c=n[7],u=n[8],d=n[9],h=n[10],m=n[11],g=n[12],p=n[13],y=n[14],x=n[15];return k=>{let P={};return e!==void 0&&(P[e]=k[e]),t!==void 0&&(P[t]=k[t]),r!==void 0&&(P[r]=k[r]),s!==void 0&&(P[s]=k[s]),i!==void 0&&(P[i]=k[i]),o!==void 0&&(P[o]=k[o]),a!==void 0&&(P[a]=k[a]),c!==void 0&&(P[c]=k[c]),u!==void 0&&(P[u]=k[u]),d!==void 0&&(P[d]=k[d]),h!==void 0&&(P[h]=k[h]),m!==void 0&&(P[m]=k[m]),g!==void 0&&(P[g]=k[g]),p!==void 0&&(P[p]=k[p]),y!==void 0&&(P[y]=k[y]),x!==void 0&&(P[x]=k[x]),P}}var xy,lo,Sy,Ty,vy,Ts=Oe(()=>{"use strict";He();xy=Symbol.metadata??Symbol.for("Symbol.metadata"),lo=Ue;Sy={string:!0,boolean:!0,bigint64:!0,biguint64:!0};Ty=n=>n;vy=16});var _c,Ay,Cy,Ye,Er,Ec=Oe(()=>{"use strict";He();Yt();Es();Rs();Ts();_c=9,Ay=_c,Cy=(n,e)=>(e?2:1)*(_c+4+_c*n),Ye=class Ye{constructor(e,t,r,s){l(this,"data");l(this,"_host");l(this,"_encoder");l(this,"_scratch",new Uint8Array(2048));l(this,"_framed",null);l(this,"_sentCount",0);l(this,"_lastProcessed",0);l(this,"_epoch",0);l(this,"_sendTimes");l(this,"_inputBufferSize");l(this,"_inputBuffer",null);l(this,"_reckonTimes",null);l(this,"_pendingReckon",0);l(this,"_lastStamp",0);l(this,"_stampRing",null);l(this,"_renderDeltaRing",null);l(this,"_ringSlots",0);l(this,"_warnedUnknownKeys",null);l(this,"_stampRender",!1);l(this,"_stampReckon",!1);l(this,"_allowRewind");l(this,"_sendListeners",null);l(this,"_renderDelay",0);l(this,"_renderDelayExplicit",!1);l(this,"_renderDelayProvider");l(this,"_tickRate");l(this,"_patchRate");l(this,"_subSteps",1);this._host=e,this.data=t,this._encoder=r,this._stampRender=s?.stampRender??!1,this._stampReckon=s?.stampReckon??!1,this._allowRewind=s?.allowRewind,this._allowRewind!==void 0&&r.mode==="unreliable"&&!Ye._warnedAllowRewindIgnored&&(Ye._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 i=this._tickRate?1e3/this._tickRate:1e3/60,o=Ye.BUFFER_RTT_BUDGET_MS+(this._patchRate??0);this._inputBufferSize=Math.max(Ye.BUFFER_FLOOR,Math.ceil(o/i*Ye.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){Ye._warnedBufferOverflow||(Ye._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=Lt(this.data);if(e)for(let t of Object.keys(this.data))e[t]!==void 0||this._warnedUnknownKeys?.has(t)||((this._warnedUnknownKeys??(this._warnedUnknownKeys=new Set)).add(t),console.warn(`@colyseus/sdk input: "${t}" 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;co()&&this._warnUnknownFields();let t=this._encoder.encode(),r=this._encoder.mode==="reliable",s=this._stampReckon||this._stampRender,i=s&&r&&(this._allowRewind===void 0||this._allowRewind(this.data)),o=s&&!r,a=this._stampReckon&&this._stampRender,u=1+(i?Ay+(a?2:0):o?Cy(this._encoder.historySize,a):0)+t.length;u>this._scratch.byteLength&&(this._scratch=new Uint8Array(Math.max(u,this._scratch.byteLength*2)),this._framed=null),this._scratch[0]=(r?_e.ROOM_INPUT_RELIABLE:_e.ROOM_INPUT_UNRELIABLE)|(i||o?pr.TIMED:0);let d={offset:1};if(o)this._writeRingStamps(d);else if(i){let{stamp:p,renderDelta:y}=this._sampleStamp();Q.number(this._scratch,p-this._lastStamp,d),this._lastStamp=p,a&&Q.uint16(this._scratch,y,d)}else this._pendingReckon=0;this._scratch.set(t,d.offset);let h=d.offset+t.length;(this._framed===null||this._framed.byteLength!==h)&&(this._framed=this._scratch.subarray(0,h));let m=this._framed,g;return r?(e.send(m),g=++this._sentCount):(e.sendUnreliable(m),g=this._sentCount=this._encoder.seq),this._recordSent(g),g}_writeRingStamps(e){let{stamp:t,renderDelta:r}=this._sampleStamp(),s=this._encoder.historySize,i=this._encoder.seq,o=this._ringSlots=Math.min(this._ringSlots+1,s),a=this._stampRing??(this._stampRing=new Float64Array(s));if(a[i%s]=t,Q.number(this._scratch,o,e),Q.uint32(this._scratch,t,e),this._writeSeriesDeltas(a,i,o,e),this._stampReckon&&this._stampRender){let c=this._renderDeltaRing??(this._renderDeltaRing=new Uint16Array(s));c[i%s]=r,Q.uint16(this._scratch,r,e),this._writeSeriesDeltas(c,i,o,e)}}_writeSeriesDeltas(e,t,r,s){let i=e.length;for(let o=1;o<r;o++)Q.number(this._scratch,e[(t-o+1)%i]-e[(t-o)%i],s)}_sampleStamp(){let e=this._host.clock,t=(e?.lastServerTime?.()??0)>0,r=t?Math.max(0,Math.round(e.serverNow()))>>>0:0,s=t?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]=$e(),this._stampReckon&&((this._reckonTimes??(this._reckonTimes=new Float64Array(this._inputBufferSize)))[e%this._inputBufferSize]=this._pendingReckon);let t=this._sendListeners;if(t!==null)for(let r=0;r<t.length;r++)t[r](e)}onSend(e){let t=this._sendListeners;return this._sendListeners=t!==null?[...t,e]:[e],()=>{let r=this._sendListeners;if(r===null)return;let s=r.indexOf(e);if(s<0)return;let i=r.slice();i.splice(s,1),this._sendListeners=i.length>0?i:null}}ackInput(e){if(e<=this._lastProcessed)return-1;let t=this._sentCount-e>=this._inputBufferSize;if(this._lastProcessed=e,t)return-1;let r=this._sendTimes[e%this._inputBufferSize];return r>0?$e()-r:-1}};l(Ye,"BUFFER_FLOOR",64),l(Ye,"BUFFER_RTT_BUDGET_MS",1e3),l(Ye,"BUFFER_HEADROOM",1.5),l(Ye,"_warnedBufferOverflow",!1),l(Ye,"_warnedAllowRewindIgnored",!1);Er=Ye});var Rr,Ie,uo,fo=Oe(()=>{"use strict";Es();Rr=Object.freeze({now:()=>$e(),serverNow:()=>$e(),renderNow:()=>$e(),rtt:()=>0,smoothedRtt:()=>0,jitter:()=>0,lastServerTime:()=>0,patchInterval:()=>0,setPatchInterval:n=>{},sample:(n,e)=>{}}),Ie=class Ie{constructor(){l(this,"_clockOffset",0);l(this,"_clockHasSample",!1);l(this,"_offsetCount",0);l(this,"_rttFloorT",[]);l(this,"_rttFloorV",[]);l(this,"_rtt",0);l(this,"_smoothedRtt",0);l(this,"_rttHasSample",!1);l(this,"_jitter",0);l(this,"_lastRecvTime",-1);l(this,"_lastServerTime",0);l(this,"_patchInterval",0);l(this,"_renderTau",Ie.RENDER_TAU);l(this,"_renderSn",0);l(this,"_renderSnAt",0)}serverNow(){return $e()+this._clockOffset}renderNow(){let e=this.serverNow();if(this._renderTau<=0)return e;let t=$e();if(this._renderSn===0)return this._renderSn=e,this._renderSnAt=t,this._renderSn;let r=Math.min(t-this._renderSnAt,100);return r<.5?this._renderSn:(this._renderSnAt=t,this._renderSn+=r,Math.abs(e-this._renderSn)>Ie.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 $e()}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,t){let r=$e(),s=Ie.EMA_ALPHA,i=this._patchInterval;if(this._lastRecvTime>=0&&i>0){let a=r-this._lastRecvTime,c=Math.round(a/i);c>=1&&c<=Ie.JITTER_STALL_X&&(this._jitter+=(Math.abs(a-c*i)-this._jitter)*Ie.JITTER_GAIN)}this._lastRecvTime=r,this._lastServerTime=e,(t<0||this._smoothedRtt>0&&t>this._smoothedRtt*Ie.RTT_OUTLIER_X)&&(t=-1);let o=t>=0?e+t/2-r:e-r;if(!this._clockHasSample)this._clockOffset=o,this._clockHasSample=!0,t>=0&&(this.pushRttFloor(t,r),this._offsetCount=1);else if(t>=0){let a=this.pushRttFloor(t,r),c=this._offsetCount<Ie.RTT_GATE_WARMUP;this._offsetCount++,(c||t<=a*Ie.RTT_GATE_FACTOR)&&(this._clockOffset=this._clockOffset*(1-s)+o*s)}t>=0&&(this._rtt=t,this._rttHasSample?this._smoothedRtt=this._smoothedRtt*(1-s)+t*s:(this._smoothedRtt=t,this._rttHasSample=!0))}pushRttFloor(e,t){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(t);let i=t-Ie.RTT_GATE_WINDOW;for(;r.length>0&&r[0]<i;)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}};l(Ie,"EMA_ALPHA",.1),l(Ie,"RENDER_TAU",250),l(Ie,"RENDER_SNAP",250),l(Ie,"RTT_OUTLIER_X",4),l(Ie,"JITTER_GAIN",1/16),l(Ie,"JITTER_STALL_X",4),l(Ie,"RTT_GATE_FACTOR",1.2),l(Ie,"RTT_GATE_WINDOW",1e4),l(Ie,"RTT_GATE_WARMUP",30);uo=Ie});var Df=hp((HE,Mf)=>{"use strict";Mf.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});function e0(n,e){return{now:()=>n?.serverNow()??performance.now(),ttlMs:typeof e=="function"?()=>e(n?.smoothedRtt()??0):e}}var Hs,Po,Gc=Oe(()=>{"use strict";Hs=n=>Math.max(n*2,600),Po=class n{constructor(){l(this,"entries",new Map);l(this,"accepted",new Set);l(this,"cfg",{});l(this,"dead",!1)}static get(e,t={}){let r=new n;return r.configure(e0(e.clock??null,t.ttlMs??Hs)),t.onReject&&r.configure({onReject:t.onReject}),r}configure(e){this.cfg={...this.cfg,...e}}predict(e,t){return this.entries.set(e,t??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,t){let r=e??this.cfg.now?.()??performance.now(),s=this.cfg.ttlMs,i=t??(typeof s=="function"?s():s)??1/0;for(let[o,a]of this.entries)this.accepted.has(o)||r-a>i&&(this.entries.delete(o),this.cfg.onReject?.(o))}clear(){this.entries.clear(),this.accepted.clear()}get size(){return this.entries.size}dispose(){this.dead=!0,this.entries.clear(),this.accepted.clear()}}});function Qf(){return{ema:0,peak:0}}function Hc(n,e){n.ema+=(e-n.ema)*.1,n.peak=Math.max(e,n.peak*.9)}function Zf(n){n.ema=0,n.peak=0}function Dr(n,e){let t=e!==void 0&&e>Xf?e:Xf;return n.ema>=t?"diverging":n.peak>=t?"jitter":"matched"}var Xf,Oo=Oe(()=>{"use strict";Xf=.001});function zs(){return co()}function th(){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 nh(n,e){console.warn(e===""?`@colyseus/sdk predict: two key-less ctx.memo calls ran in one step (input seq ${n}) \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 ${n}) \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 rh(n,e,t,r){let s=$e();if(s-eh<t0)return;eh=s;let i="",o=-1;for(let c in e){let u=e[c],d=u<0?-u:u;d>o&&(o=d,i=c)}let a=i?e[i]:t;console.warn(`@colyseus/sdk predict: prediction is diverging at input seq ${n} \u2014 rolling drift ${t.toFixed(3)} \u2265 tolerance ${r}; "${i}" 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 eh,t0,zc=Oe(()=>{"use strict";Es();Rs();eh=-1/0,t0=1e3});function sh(){return Jc>0}var Wc,Jc,Nr,Mo=Oe(()=>{"use strict";Oo();zc();Wc=class{constructor(){l(this,"byTick",new Map);l(this,"diagTick",-1);l(this,"diagKeys",new Set);l(this,"warnedKeys",new Set)}run(e,t,r,s){if(t)return this.byTick.get(e)?.get(r);zs()&&(e!==this.diagTick?(this.diagTick=e,this.diagKeys.clear()):this.diagKeys.has(r)&&!this.warnedKeys.has(r)&&(this.warnedKeys.add(r),nh(e,r)),this.diagKeys.add(r));let i=s();if(i!==void 0){let o=this.byTick.get(e);o===void 0&&(o=new Map,this.byTick.set(e,o)),o.set(r,i)}return i}prune(e){for(let t of this.byTick.keys())t<=e&&this.byTick.delete(t)}clear(){this.byTick.clear(),this.diagTick=-1,this.diagKeys.clear()}},Jc=0;Nr=class{constructor(e){l(this,"lastCorrection",{});l(this,"lastCorrectionMag",0);l(this,"reconcileSeq",0);l(this,"drift",Qf());l(this,"error",{});l(this,"prev",{});l(this,"renderedBefore",{});l(this,"lastTick",-1);l(this,"lastAcked",0);l(this,"lastEpoch");l(this,"replayFrom",0);l(this,"predictedSeq",0);l(this,"catching",!1);l(this,"unsubscribeSend",()=>{});l(this,"renderAcc",0);l(this,"tickSeq",0);l(this,"clampedReadTick",-1);l(this,"warnedStaleRead",!1);l(this,"stepCtx");l(this,"ackWatermark",()=>this.input_.lastProcessed);l(this,"memos",new Wc);l(this,"smoothMs");l(this,"snapThreshold");l(this,"stepMs");l(this,"input_");l(this,"onReconcile");l(this,"warnTolerance");l(this,"clock");l(this,"dead",!1);l(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 t=e.stepMs??this.input_.stepMs??(e.stepSeconds!==void 0?e.stepSeconds*1e3:void 0);if(t===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=t;let r=e.stepSeconds??this.input_.stepSeconds??t/1e3,s=e.subSteps??this.input_.subSteps??1;this.stepCtx={dt:r,dtMs:t,tick:0,isReplay:!1,reckonTime:0,lagCompActive:!1,subSteps:s,subDt:r/s,subDtMs:t/s,memo:(i,o)=>typeof i=="string"?this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,i,o):this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,"",i),predict:(i,o)=>{this.stepCtx.isReplay||i._predictFromSim(this.stepCtx.tick,o,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 t=this.lastTick<0?0:e-this.lastTick;this.lastTick=e,t>0&&this.stepMs>0&&(this.renderAcc+=t);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(),t<=0)return;let i=this.smoothMs<=0?1:1-Math.exp(-t/this.smoothMs);for(let o of this.smoothedFields())this.error[o]-=this.error[o]*i}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,th()),this.catching=!0,this.stepCtx.isReplay=!1;for(let t=this.predictedSeq+1;t<=e;t++){let r=this.input_.at(t);r!==void 0&&(this.snapshotPrev(),this.runStep(t,r),this.refreshRender(),this.renderAcc-=this.stepMs,this.renderAcc<0?this.renderAcc=0:this.renderAcc>=this.stepMs&&(this.renderAcc%=this.stepMs)),this.predictedSeq=t}this.catching=!1}}runStep(e,t){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(t)}reconcile(e){let t=this.warnTolerance!==void 0||zs();if(this.truthMatchesAt(e)){if(t){for(let u of this.smoothedFields())this.lastCorrection[u]=0;this.lastCorrectionMag=0,Hc(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,Jc++;try{for(let u=s+1;u<=this.input_.sentCount;u++){let d=this.input_.at(u);d!==void 0&&this.runStep(u,d)}}finally{Jc--}this.catching=!1,this.refreshRender(),this.predictedSeq=this.input_.sentCount;let i=this.smoothMs<=0,o=t||this.snapThreshold>0,a=0;for(let u of this.smoothedFields()){let d=r[u]-this.readCurrent(u);if(this.error[u]=i?0:d,o){let h=d<0?-d:d;h>a&&(a=h)}t&&(this.lastCorrection[u]=d)}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++,t&&(this.lastCorrectionMag=a,c||(Hc(this.drift,a),this.warnTolerance!==void 0&&Dr(this.drift,this.warnTolerance)==="diverging"&&rh(e,this.lastCorrection,this.drift.ema,this.warnTolerance))),this.memos.prune(e),this.onReconcile?.(e)}get pendingCount(){return this.input_.pendingCount}reset(){this.reseedState(),Zf(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 n0,Kc,Br,Yc=Oe(()=>{"use strict";Gc();Mo();n0=0,Kc=10,Br=class{constructor(e,t){l(this,"opts");l(this,"store");l(this,"entries",new Map);l(this,"now");l(this,"cooldownUntil",-1/0);l(this,"warnedReplayPredict",!1);l(this,"dead",!1);l(this,"teardowns",[]);this.opts=e,this.now=()=>t?.serverNow()??performance.now(),this.store=Po.get({clock:t},{ttlMs:e.ttlMs??Hs,onReject:r=>{let s=this.entries.get(r);this.entries.delete(r),s&&this.opts.onReject?.(s.payload)}})}_predictFromSim(e,t,r){this.add(e,t,r)}predict(e){if(sh()){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,t,r){let s=this.opts.uniqueBy!==void 0?this.opts.uniqueBy(t):typeof t=="string"||typeof t=="number"?t:n0;if(this.entries.has(s))return;let i=this.now();if(this.opts.cooldownMs!==void 0){if(i<this.cooldownUntil)return;this.cooldownUntil=i+this.opts.cooldownMs}let o=this.store.predict(s,i);r!==void 0&&o.accept(),this.entries.set(s,{payload:t,seq:e,acked:r}),this.opts.onPredict?.(t)}has(e){return e===void 0?this.entries.size>0:this.entries.has(e)}get pendingCount(){return this.entries.size}confirm(e){let t=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),t++)}return t===0&&this.opts.onUnpredicted?.(e),t}reject(e){let t=0;for(let r of this.settleKeys(e))this.entries.has(r)&&(this.store.reject(r),t++);return t}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??Kc;for(let[t,r]of[...this.entries])r.acked!==void 0&&r.acked()>=r.seq+e&&this.store.reject(t)}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 Kn,Do=Oe(()=>{"use strict";Gc();Kn=class{constructor(e={},t=null){l(this,"opts");l(this,"clock");l(this,"correlate");l(this,"ttl");l(this,"byId",new Map);l(this,"byServer",new Map);l(this,"nextId",1);l(this,"lastTickAt");l(this,"detach");l(this,"dead",!1);l(this,"handleAdd",(e,t)=>{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)}});l(this,"handleRemove",(e,t)=>{let r=this.byServer.get(e);r&&(this.byServer.delete(e),this.byId.delete(r.id))});l(this,"readServer",(e,t)=>e[t]);this.opts=e,this.clock=t,this.correlate=e.correlate??"fifo",this.ttl=e.ttl??Hs}attach(e){this.detach?.(),this.detach=e(this.handleAdd,this.handleRemove)}spawn(e){let t=this.nextId++,r=this.makeData(),s={id:t,server:void 0,local:e,state:"pending",at:this.now(),leadMs:0,accepted:!1,data:r};return this.byId.set(t,s),{id:t,local:e,data:r,cancel:()=>{let i=this.byId.get(t);i&&i.state==="pending"&&this.byId.delete(t)},accept:()=>{let i=this.byId.get(t);i&&(i.accepted=!0)}}}confirmEntry(e,t){e.server=t,e.state="confirmed";let r=this.opts.spawnTime;r!==void 0&&e.at!==void 0&&(e.leadMs=r(t)-e.at),this.byServer.set(t,e)}takeMatch(e){let t=this.correlate;if(typeof t!="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"&&t(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 t=this.opts.step,r=this.clock!==null?this.clock.serverNow():e;if(t!==void 0&&this.lastTickAt!==void 0){let s=Math.max(0,(r-this.lastTickAt)/1e3);if(s>0)for(let i of this.byId.values())i.state==="pending"&&t(i.local,s)}this.lastTickAt=r}prune(){if(this.byId.size===0)return;let e=this.now(),t=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>t&&(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,t){return e.server!==void 0?this.readServer(e.server,t):e.local[t]}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 ih,Yn,No=Oe(()=>{"use strict";Mo();Ts();zc();ih=n=>typeof n=="number"?n:typeof n=="boolean"?n?1:0:NaN,Yn=class extends Nr{constructor(t,r){super(r);l(this,"local",{});l(this,"fields");l(this,"numericFields",[]);l(this,"step");l(this,"instance");l(this,"wireRound",[]);l(this,"history");l(this,"historySeq");l(this,"historySize");l(this,"historyOn");l(this,"undeclared",null);l(this,"devView",null);this.instance=t;let s=r.fields,i=s??Ss(t).fields;if(s===void 0&&i.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=i,this.step=r.step;let o=this.fields.length>0;for(let a of this.fields){let c=t[a];this.local[a]=c,typeof c=="number"?(this.numericFields.push(a),this.prev[a]=c,this.error[a]=0):typeof c!="boolean"&&(o=!1),this.wireRound.push(af(t,a))}if(this.historyOn=o,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=Ss(t).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(t){this.noteRenderRead();let r=this.local[t];if(typeof r!="number")return r;let s=r+(this.error[t]??0),i=this.prev[t]??s;return i+(s-i)*this.renderAlpha()}smoothedFields(){return this.numericFields}readCurrent(t){return this.local[t]}applyStep(t){let r=this.undeclared!==null&&zs()?this.stepView():this.local;if(this.step(this.stepCtx,r,t),this.historyOn){let s=this.stepCtx.tick,i=s%this.historySize,o=i*this.fields.length;for(let a=0;a<this.fields.length;a++)this.history[o+a]=ih(this.local[this.fields[a]]);this.historySeq[i]=s}}stepView(){if(this.devView!==null)return this.devView;let t=this.undeclared,r=new Set,s=(i,o)=>{typeof o!="string"||!t.has(o)||r.has(o)||(r.add(o),console.warn(`@colyseus/sdk predict: step ${i} "${o}" \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 "${o}" 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(i,o,a){return s("read",o),Reflect.get(i,o,a)},set(i,o,a,c){return s("wrote",o),Reflect.set(i,o,a,c)}}),this.devView}truthMatchesAt(t){if(!this.historyOn)return!1;let r=t%this.historySize;if(this.historySeq[r]!==t)return!1;let s=r*this.fields.length,i=this.instance;for(let o=0;o<this.fields.length;o++)if(this.wireRound[o](this.history[s+o])!==ih(i[this.fields[o]]))return!1;return!0}snapshotPrev(){for(let t of this.numericFields)this.prev[t]=this.local[t]+this.error[t]}adoptTruth(){let t=this.instance;for(let r of this.fields)this.local[r]=t[r]}reseedState(){let t=this.instance;for(let r of this.fields)this.local[r]=t[r];for(let r of this.numericFields)this.prev[r]=this.local[r],this.error[r]=0;this.historySeq.fill(-1)}}});var Xn,Bo=Oe(()=>{"use strict";Mo();Ts();Xn=class extends Nr{constructor(t){super(t);l(this,"worldHandle");l(this,"bindings",[]);l(this,"curPose",{});l(this,"poseFields",[]);l(this,"customFields",[]);l(this,"fieldsReady",!1);l(this,"poseA",{});l(this,"poseB",{});l(this,"renderPose",{});l(this,"poseDirty",!0);l(this,"step");l(this,"adopt");l(this,"readPose");l(this,"interpolate");let r=t.world;for(let s of Object.keys(r)){let i=r[s];if(i===null||typeof i!="object")continue;if(Ke(i)===void 0){if(Lt(i)!==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:o,numeric:a}=Ss(i);if(o.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 d of o)c[d]=i[d];r[s]=c;let u=a.map(d=>`${s}.${d}`);this.bindings.push({source:i,mirror:c,fields:o,numeric:a,poseKeys:u})}if(this.bindings.length===0&&t.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=t.world,this.step=t.step,this.adopt=t.adopt,this.readPose=t.pose,this.interpolate=t.interpolate,this.refreshPose();for(let s of this.poseFields)this.prev[s]=this.curPose[s],this.error[s]=0}refreshPose(){let t=this.curPose;for(let r of this.bindings){let{mirror:s,numeric:i,poseKeys:o}=r;for(let a=0;a<i.length;a++)t[o[a]]=s[i[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)t[s]=r[s]}if(!this.fieldsReady){let r=[];for(let s of this.bindings)for(let i of s.poseKeys)r.push(i);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(t=>({source:t.source,fields:t.numeric,poseKeys:t.poseKeys}))}value(t){if(this.noteRenderRead(),this.interpolate)return this.pose()[t];let r=this.curPose[t]+(this.error[t]??0),s=this.prev[t]??r;return s+(r-s)*this.renderAlpha()}pose(){if(this.noteRenderRead(),!this.poseDirty)return this.renderPose;let t=this.renderAlpha(),r=this.poseA,s=this.poseB;for(let i of this.poseFields)r[i]=this.prev[i]??this.curPose[i],s[i]=this.curPose[i]+(this.error[i]??0);if(this.interpolate){let i=this.interpolate(r,s,t);for(let o of this.poseFields)this.renderPose[o]=i[o]}else for(let i of this.poseFields)this.renderPose[i]=r[i]+(s[i]-r[i])*t;return this.poseDirty=!1,this.renderPose}smoothedFields(){return this.poseFields}readCurrent(t){return this.curPose[t]}applyStep(t){this.step(this.stepCtx,this.worldHandle,t)}adoptTruth(){for(let t of this.bindings){let{source:r,mirror:s,fields:i}=t;for(let o=0;o<i.length;o++)s[i[o]]=r[i[o]]}this.adopt?.(this.worldHandle)}refreshRender(){this.refreshPose()}markDirty(){this.poseDirty=!0}snapshotPrev(){for(let t of this.poseFields)this.prev[t]=this.curPose[t]+this.error[t]}reseedState(){this.adoptTruth(),this.refreshPose();for(let t of this.poseFields)this.prev[t]=this.curPose[t],this.error[t]=0}}});function oh(n,e,t,r){let s=[];if(t.field!==void 0){let i=new Map;s.push(n.onAdd(t.collection,(o,a)=>{i.has(o)||i.set(o,n.listen(o,t.field,c=>{c===t.equals&&e.confirm(a)},!1))})),s.push(n.onRemove(t.collection,o=>{i.get(o)?.(),i.delete(o)})),s.push(()=>{for(let o of i.values())o();i.clear()})}else t.event==="remove"?s.push(n.onRemove(t.collection,(i,o)=>{e.confirm(o)})):s.push(n.onAdd(t.collection,i=>{t.mine!==void 0&&i[t.mine]!==r?.()||e.confirm()},!1));return()=>{for(let i of s.splice(0))i?.()}}var ah=Oe(()=>{"use strict"});function lh(n){return n===null||typeof n!="object"?!1:Array.isArray(n.fields)}function a0(){uh||(uh=!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 Me,ct,ht,on,vt,Ws,Js,Lr,Fr,Ur,Ks,je,r0,s0,ch,Qe,$r,Qn,Zn,Vr,jr,qr,Gr,jt,Ys,Uo,$o,Vo,i0,Lo,Xc,kn,Fo,o0,uh,Hr,Xs,Qc=Oe(()=>{"use strict";He();Yc();Do();No();Bo();Ec();Oo();fo();Rs();Ts();ah();Me=16,ct=0,ht=1,on=2,vt=3,Ws=4,Js=5,Lr=6,Fr=7,Ur=8,Ks=9,je=Ks+Me*2,r0=3,s0=1.5,ch=250,Qe=7,$r=0,Qn=1,Zn=2,Vr=3,jr=4,qr=5,Gr=6,jt=0,Ys=0,Uo=1,$o=2,Vo=3,i0=4,Lo=5,Xc={lerp:Ys,extrapolate:Uo,damped:$o,reckon:Vo,raw:i0},kn={mode:"lerp",delay:100,smoothMs:50,maxExtrapolate:200,tickInterval:0,snap:0,angle:!1},Fo={step:void 0,smoothMs:50,substep:16,snap:0};o0=0,uh=!1;Hr=class Hr{constructor(e,t){l(this,"callbacks");l(this,"sessionSource");l(this,"slotBuf",new Float64Array(64*je));l(this,"slotCount",0);l(this,"slotDetach",[]);l(this,"slotAngle",[]);l(this,"freeSlots",[]);l(this,"slotByRef",new Map);l(this,"simByRef",new Map);l(this,"boundBySlot",new Map);l(this,"boundProfileIdx",-1);l(this,"renderTime",0);l(this,"defaultMode");l(this,"reckonDefaults");l(this,"clock");l(this,"useRenderClock",!1);l(this,"fixedStepMs");l(this,"stepAcc",0);l(this,"lastFrameNow",-1);l(this,"profileBuf",new Float64Array(8*Qe));l(this,"profileCount",0);l(this,"profileKeys",new Map);l(this,"profileLabels",[]);l(this,"profileComputers",[]);l(this,"trackListeners",[]);l(this,"name");l(this,"disposeListeners",[]);l(this,"driven",[]);l(this,"computeDamped",e=>{let t=this.slotBuf,r=e*je,s=this.profileBuf,i=(t[r+vt]|0)*Qe,o=this.renderTime,a=t[r+ct],c=t[r+on],u=o-c;t[r+on]=o;let d=t[r+ht];if(u>0){let h=s[i+Zn],m=h>0?1-Math.exp(-u/h):1;d+=(a-d)*m,t[r+ht]=d}return d});l(this,"computeLerp",e=>{let t=this.computeLerpRaw(e),r=this.slotBuf,s=e*je,i=this.profileBuf[(r[s+vt]|0)*Qe+Gr],o=this.renderTime;if(i<=0)return r[s+ht]=t,r[s+Ur]=t,r[s+on]=o,t;let a=r[s+on],c=o-a;if(c<=0)return r[s+ht];let u=r[s+Ur],d=r[s+ht],h=c/i,m=(t-u)/h,g=t-m+(d-u+m)*Math.exp(-h);return r[s+ht]=g,r[s+Ur]=t,r[s+on]=o,g});l(this,"computeExtrapolate",e=>{let t=this.slotBuf,r=e*je,s=this.profileBuf,i=(t[r+vt]|0)*Qe,o=this.renderTime,a=t[r+Fr]|0;if(a===0)return t[r+ct];let c=t[r+Lr]|0,u=r+Ks,d=(c-a+Me)%Me,h=(d+a-1)%Me,m=u+h*2,g=t[m],p=t[m+1],y;if(a===1)y=p;else{let N=a>=3?2:1,C=(d+a-1-N+Me)%Me,O=u+C*2,A=t[O],I=t[O+1],V=g-A;if(V<=0)y=p;else{let Z=(p-I)/V,ee=s[i+Vr],ve=o-g;ve<0?ve=0:ve>ee&&(ve=ee),y=p+Z*ve}}let x=t[r+on];t[r+on]=o;let k=s[i+Zn];if(k<=0)return t[r+ht]=y,y;let P=o-x,U=t[r+ht];if(P>0){let N=1-Math.exp(-P/k);U+=(y-U)*N,t[r+ht]=U}return U});l(this,"computeReckon",e=>{let t=this.slotBuf,r=e*je,s=t[r+Ws],i=t[r+Js]|0,o=this.simByRef.get(s);if(o!==void 0){let a=i<o.posOf.length?o.posOf[i]:-1;if(a>=0)return this.applySimulation(o,a)}return t[r+ct]});l(this,"computeRaw",e=>this.slotBuf[e*je+ct]);l(this,"computeBound",e=>{let t=this.boundBySlot.get(e);return t!==void 0?t.ctrl.value(t.key):this.slotBuf[e*je+ct]});this.callbacks=bc.get(e),this.sessionSource=e;let{clock:r,...s}=t;this.defaultMode=s.mode??"lerp";let i=this.defaultMode!=="reckon"&&this.defaultMode!=="raw",o=i?(()=>{let u=s;return{mode:u.mode??kn.mode,delay:u.delay??kn.delay,smoothMs:u.smoothMs??kn.smoothMs,maxExtrapolate:u.maxExtrapolate??kn.maxExtrapolate,tickInterval:u.tickInterval??kn.tickInterval,snap:u.snap??kn.snap,angle:u.angle??kn.angle}})():{...kn},a=i?s.smoothMs??0:0;if(this.allocProfile(this.defaultMode,o.delay,o.smoothMs,a,o.maxExtrapolate,o.tickInterval,o.snap,!1)!==jt)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??Fo.smoothMs,substep:u.substep??Fo.substep,snap:u.snap??Fo.snap}}else this.reckonDefaults={...Fo};this.clock=r??e.clock??void 0,this.useRenderClock=s.renderPresent!==!1,this.clock===Rr&&a0(),this.name=s.name??`predict#${++o0}`,ao("predict",this.makeCoreHandle())}static get(e,t={}){return new Hr(e,t)}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,t)=>this.setProfile(e,t),onTrack:e=>(this.trackListeners.push(e),()=>{let t=this.trackListeners.indexOf(e);t>=0&&this.trackListeners.splice(t,1)}),onDispose:e=>(this.disposeListeners.push(e),()=>{let t=this.disposeListeners.indexOf(e);t>=0&&this.disposeListeners.splice(t,1)})}}snapshotReconcilers(){let e=[],t=0;for(let r of this.driven){let s=r;if(!s.drift)continue;let i=s.warnTolerance;e.push({label:`reconciler #${t++}`,status:Dr(s.drift,i),severity:i!==void 0&&i>0?s.drift.ema/i: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,t=jt*Qe,r=e[t+$r]|0;return{mode:r===Ys?"lerp":r===Uo?"extrapolate":r===$o?"damped":r===Vo?"reckon":"raw",delay:e[t+Qn],smoothMs:e[t+Zn],lerpSmoothMs:e[t+Gr],maxExtrapolate:e[t+Vr],tickInterval:e[t+jr],snap:e[t+qr]}}allocProfile(e,t,r,s,i,o,a,c,u){let d=typeof e=="number"?e:Xc[e],h="";if(c){h=`${u??""}|${d}|${t}|${r}|${s}|${i}|${o}|${a}`;let y=this.profileKeys.get(h);if(y!==void 0)return y}let m=this.profileCount++;if((m+1)*Qe>this.profileBuf.length){let y=new Float64Array(this.profileBuf.length*2);y.set(this.profileBuf),this.profileBuf=y}let p=m*Qe;return this.profileBuf[p+$r]=d,this.profileBuf[p+Qn]=t,this.profileBuf[p+Zn]=r,this.profileBuf[p+Gr]=s,this.profileBuf[p+Vr]=i,this.profileBuf[p+jr]=o,this.profileBuf[p+qr]=a,this.profileLabels[m]=u,this.profileComputers[m]=this.computerForMode(d),c&&this.profileKeys.set(h,m),m}computerForMode(e){return e===Ys?this.computeLerp:e===Uo?this.computeExtrapolate:e===$o?this.computeDamped:e===Vo?this.computeReckon:e===Lo?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 jt;let t=this.readSmoothingDefaults(),r=e.mode??t.mode,s=e.delay??t.delay,i=e.smoothMs??t.smoothMs,o=e.smoothMs??t.lerpSmoothMs,a=e.maxExtrapolate??t.maxExtrapolate,c=e.tickInterval??t.tickInterval,u=e.snap??t.snap;return r===t.mode&&s===t.delay&&i===t.smoothMs&&o===t.lerpSmoothMs&&a===t.maxExtrapolate&&c===t.tickInterval&&u===t.snap?jt:this.allocProfile(r,s,i,o,a,c,u,!0)}groupProfile(e,t){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,t)}setDefaults(e){let t=e.mode;if(t!==void 0){this.defaultMode=t;let a=jt*Qe,c=Xc[t];this.profileBuf[a+$r]=c,this.profileComputers[jt]=this.computerForMode(c)}let r=e,s=jt*Qe,i=this.profileBuf;r.delay!==void 0&&(i[s+Qn]=r.delay),r.smoothMs!==void 0&&(i[s+Zn]=r.smoothMs,i[s+Gr]=r.smoothMs),r.maxExtrapolate!==void 0&&(i[s+Vr]=r.maxExtrapolate),r.tickInterval!==void 0&&(i[s+jr]=r.tickInterval),r.snap!==void 0&&(i[s+qr]=r.snap,this.reckonDefaults.snap=r.snap);let o=e;o.step!==void 0&&(this.reckonDefaults.step=o.step),o.smoothMs!==void 0&&(this.reckonDefaults.smoothMs=o.smoothMs),o.substep!==void 0&&(this.reckonDefaults.substep=o.substep)}snapshotProfiles(){let e=[];for(let t=0;t<this.profileCount;t++){let r=t*Qe,s=this.profileBuf[r+$r]|0;if(s===Lo)continue;let i=s===Ys?"lerp":s===Uo?"extrapolate":s===$o?"damped":s===Vo?"reckon":"raw";e.push({id:t,isDefault:t===jt,label:this.profileLabels[t],mode:i,delay:this.profileBuf[r+Qn],smoothMs:this.profileBuf[r+(s===Ys?Gr:Zn)],maxExtrapolate:this.profileBuf[r+Vr],tickInterval:this.profileBuf[r+jr],snap:this.profileBuf[r+qr]})}return e}setProfile(e,t){if(e<0||e>=this.profileCount)return;let r=e*Qe,s=this.profileBuf;if((s[r+$r]|0)!==Lo){if(t.mode!==void 0){let i=Xc[t.mode];s[r+$r]=i,this.profileComputers[e]=this.computerForMode(i),e===jt&&(this.defaultMode=t.mode)}t.delay!==void 0&&(s[r+Qn]=t.delay),t.smoothMs!==void 0&&(s[r+Zn]=t.smoothMs,s[r+Gr]=t.smoothMs),t.maxExtrapolate!==void 0&&(s[r+Vr]=t.maxExtrapolate),t.tickInterval!==void 0&&(s[r+jr]=t.tickInterval),t.snap!==void 0&&(s[r+qr]=t.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,t,r={}){return this.trackWithProfile(e,t,this.profileFromOpts(r),r.angle??!1)}trackWithProfile(e,t,r,s=!1){let i=Ke(e);if(i===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 o=xs(e,t),a=e[t]??0,c,u=this.slotByRef.get(i)?.get(t);u!==void 0&&(c=this.boundBySlot.get(u),c!==void 0?this.freeStash(c):this.untrackSlot(i,t));let d=this.allocSlot(),h=this.slotBuf,m=d*je;if(h[m+ct]=a,h[m+ht]=a,h[m+on]=performance.now(),h[m+Ur]=a,h[m+vt]=r,h[m+Ws]=i,h[m+Js]=o,h[m+Lr]=0,h[m+Fr]=0,this.slotAngle[d]=s,c!==void 0)c.stash=d;else{let p=this.slotByRef.get(i);p===void 0&&(p=new Map,this.slotByRef.set(i,p)),p.set(t,d)}for(let p=0;p<this.trackListeners.length;p++)this.trackListeners[p](r,t);let g=this.callbacks.listen(e,t,p=>{let y=this.clock&&this.clock.lastServerTime()>0?this.clock.lastServerTime():performance.now(),x=this.slotBuf,k=d*je;if(s){let ee=x[k+ct];p=ee+Math.atan2(Math.sin(p-ee),Math.cos(p-ee))}let P=(x[k+vt]|0)*Qe,U=this.profileBuf[P+jr],N=x[k+Lr]|0,C=x[k+Fr]|0,O=this.profileBuf[P+qr];O>0&&C>0&&Math.abs(p-x[k+ct])>O&&(N=0,C=0,x[k+ht]=p,x[k+Ur]=p);let A=C===0?Number.NEGATIVE_INFINITY:x[k+Ks+(N===0?Me-1:N-1)*2],I=y;if(U>0&&isFinite(A)){let ee=y-A,ve=ee>0?Math.max(1,Math.round(ee/U)):1;I=A+ve*U;let Pe=y+U;I>Pe&&(I=Pe)}x[k+ct]=p;let V=k+Ks;if(C>=2&&isFinite(A)){let ee=N===0?Me-1:N-1,ve=ee===0?Me-1:ee-1,Pe=A-x[V+ve*2],S=this.clock?.patchInterval?this.clock.patchInterval():0,L=S>0?S:Pe,B=S>0?s0*S:r0*Pe;if(L>0&&I-A>B){let D=L<ch?L:ch,M=V+N*2;x[M]=I-D,x[M+1]=x[V+ee*2+1],N=N+1>=Me?0:N+1,C<Me&&C++}}let Z=V+N*2;x[Z]=I,x[Z+1]=p,x[k+Lr]=N+1>=Me?0:N+1,C<Me&&(x[k+Fr]=C+1)},!0);return this.slotDetach[d]=g,()=>this.untrackSlot(i,t)}untrack(e,t){let r=Ke(e);r!==void 0&&this.untrackSlot(r,t)}untrackSlot(e,t){let r=this.slotByRef.get(e),s=r?.get(t);if(s===void 0)return;let i=this.boundBySlot.get(s);if(i!==void 0){this.freeStash(i);return}this.slotDetach[s]?.(),this.slotDetach[s]=void 0,this.freeSlots.push(s),r.delete(t),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)*je>this.slotBuf.length){let r=new Float64Array(this.slotBuf.length*2);r.set(this.slotBuf),this.slotBuf=r}return e}registerBound(e,t,r,s,i){let o=Ke(t),a=this.slotByRef.get(o);a===void 0&&(a=new Map,this.slotByRef.set(o,a));let c=[];for(let u=0;u<r.length;u++){let d=r[u],h=a.get(d),m=-1;if(h!==void 0){let k=this.boundBySlot.get(h);k!==void 0?(console.warn(`@colyseus/sdk Predict: "${d}" (refId ${o}) is already bound to a controller \u2014 the newer registration wins.`),m=k.stash,this.boundBySlot.delete(h),this.freeSlots.push(h)):m=h}let g=this.allocSlot(),p=this.slotBuf,y=g*je,x=t[d]??0;p[y+ct]=x,p[y+ht]=x,p[y+on]=0,p[y+Ur]=x,p[y+vt]=i,p[y+Ws]=o,p[y+Js]=xs(t,d),p[y+Lr]=0,p[y+Fr]=0,this.slotAngle[g]=!1,this.boundBySlot.set(g,{ctrl:e,key:s[u],stash:m}),a.set(d,g),c.push(g);for(let k=0;k<this.trackListeners.length;k++)this.trackListeners[k](i,d)}return()=>{for(let u=0;u<c.length;u++){let d=c[u],h=this.boundBySlot.get(d);if(h===void 0||h.ctrl!==e)continue;this.boundBySlot.delete(d),this.freeSlots.push(d);let m=this.slotByRef.get(o);m?.get(r[u])===d&&(h.stash>=0?m.set(r[u],h.stash):(m.delete(r[u]),m.size===0&&this.slotByRef.delete(o)))}}}installBoundOverlay(e){let t=[];for(let r of e.boundRegistrations)r.fields.length===0||Ke(r.source)===void 0||(this.boundProfileIdx<0&&(this.boundProfileIdx=this.allocProfile(Lo,0,0,0,0,0,0,!1,"bound")),t.push(this.registerBound(e,r.source,r.fields,r.poseKeys,this.boundProfileIdx)));t.length>0&&e.onDisposed(()=>{for(let r of t)r()})}trackStepped(e,t){let r=t.substep??16,s=t.fields,i=s.map(p=>xs(e,p)),o=t.step,a=this.clock,c=this.presentFn(),u=t.forwardMs??(c?()=>{let p=a.lastServerTime();return p>0?Math.max(0,c()-p):0}:()=>0),d=t.elapsedMs??c??(()=>performance.now()),h=e[lo],m=t.snapshot===void 0&&Array.isArray(h)&&i.every(p=>p>=0&&p<h.length),g;if(m){let p=new e.constructor,y=p[lo];g=(x,k,P,U)=>{let N=x[lo];for(let A=0;A<N.length;A++)y[A]=N[A];let C=k,O=U-k;for(;C>0;){let A=C<r?C:r;O+=A,o(p,A/1e3,O),C-=A}for(let A=0;A<i.length;A++)P[A]=y[i[A]]}}else{let p=of(e),y=t.snapshot??(p.length>0?cf(p):k=>({...k})),x=[...s];g=(k,P,U,N)=>{let C=y(k),O=P,A=N-P;for(;O>0;){let I=O<r?O:r;A+=I,o(C,I/1e3,A),O-=I}for(let I=0;I<x.length;I++)U[I]=C[x[I]]}}return this.trackSimulated(e,{fields:s,forwardMs:u,elapsedMs:d,smoothMs:t.smoothMs,snap:t.snap,advance:g})}trackSimulated(e,t){let r=Ke(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=t.fields,i=s.length,o=s.map(g=>xs(e,g)),a=0;for(let g of o)g>a&&(a=g);let c=new Int8Array(a+1).fill(-1);for(let g=0;g<i;g++)o[g]>=0&&(c[o[g]]=g);let u=new Float64Array(i);for(let g=0;g<i;g++)u[g]=e[s[g]]??0;let d=this.presentFn(),h=t.elapsedMs??d??(()=>performance.now()),m={instance:e,fieldIds:o,posOf:c,forwardMs:t.forwardMs,elapsedMs:h,advance:t.advance,smoothMs:t.smoothMs??50,snap:t.snap??0,smoothed:u,out:new Float64Array(i),valueOut:new Float64Array(i),offset:new Float64Array(i),outPrev:new Float64Array(i),frameVel:new Float64Array(i),lastBaseT:NaN,lastApplyTime:-1/0};return this.simByRef.set(r,m),()=>this.untrackSimulated(r)}untrackSimulated(e){this.simByRef.delete(e)}attach(e,t){let r=this.makeGroup("(attach)",t);return this.attachWithPlan(e,this.planFor(r,e))}makeGroup(e,t){return{label:e,config:t,basePlan:this.buildGroupPlan(t,e),planByCtor:new Map}}planFor(e,t){let r=t.constructor,s=e.planByCtor.get(r);return s===void 0&&(s=this.resolveCtorPlan(e,t),e.planByCtor.set(r,s)),s}resolveCtorPlan(e,t){let r=Lt(t),s=t.constructor?.name||"?",i=e.config;if(!lh(i)){if(r===void 0)return e.basePlan;let c=Object.keys(i).filter(d=>i[d]!==void 0);if(c.every(d=>typeof r[d]=="number"))return e.basePlan;let u={};for(let d of c)typeof r[d]=="number"&&(u[d]=i[d]);return this.buildGroupPlan(u,`${e.label}:${s}`)}let o=i,a=o.fields;if(r!==void 0){let c=a.filter(u=>typeof r[u]=="number");c.length!==a.length&&(a=c)}return a===o.fields?e.basePlan:this.buildGroupPlan({...o,fields:a},`${e.label}:${s}`)}buildGroupPlan(e,t){let r=[];if(lh(e)){let i=e;if(!Array.isArray(i.fields))throw new Error("Predict.attach(): `fields` must be a numeric-key array.");let o=i.mode??this.defaultMode,a=i.step??this.reckonDefaults.step,c=o==="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:o,snap:i.snap,smoothMs:i.smoothMs},t);for(let d of i.fields)r.push({field:d,profileIdx:u,angle:i.angle});return{label:t,isReckon:c,reckonFields:c?i.fields:void 0,reckonStep:c?a:void 0,reckonSmoothMs:i.smoothMs??this.reckonDefaults.smoothMs,reckonSubstep:i.substep??this.reckonDefaults.substep,reckonSnap:i.snap??this.reckonDefaults.snap,reckonSnapshot:i.snapshot,fieldProfiles:r}}let s=e;for(let i of Object.keys(s)){let o=s[i];if(o===void 0)continue;let a=typeof o=="string"?{mode:o}:o;r.push({field:i,profileIdx:this.groupProfile(a,t),angle:a.angle})}return{label:t,isReckon:!1,fieldProfiles:r}}attachToGroup(e,t,r){let s=[];t.isReckon&&s.push(this.trackStepped(e,{fields:t.reckonFields,step:t.reckonStep,smoothMs:t.reckonSmoothMs,substep:t.reckonSubstep,snap:t.reckonSnap,snapshot:t.reckonSnapshot,forwardMs:r}));for(let{field:i,profileIdx:o,angle:a}of t.fieldProfiles)s.push(this.trackWithProfile(e,i,o,!!a));return()=>{for(let i of s)i()}}attachWithPlan(e,t){let r=Ke(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,t),()=>this.detachByRef(r)}detach(e){let t=Ke(e);t!==void 0&&this.detachByRef(t)}detachByRef(e){let t=this.slotByRef.get(e);if(t){for(let r of[...t.keys()]){let s=t.get(r);if(s===void 0)continue;let i=this.boundBySlot.get(s);i!==void 0?(this.freeStash(i),this.boundBySlot.delete(s),this.freeSlots.push(s),t.delete(r)):this.untrackSlot(e,r)}t.size===0&&this.slotByRef.delete(e)}this.simByRef.delete(e)}attachAll(...e){let t=typeof e[0]=="string",r=t?void 0:e[0],s=t?e[0]:e[1],i=t?e[1]:e[2],o=this.makeGroup(s,i),a=new Set,c=m=>{this.attachWithPlan(m,this.planFor(o,m)),a.add(m)},u=m=>{a.delete(m),this.detach(m)},d=t?this.callbacks.onAdd(s,c):this.callbacks.onAdd(r,s,c),h=t?this.callbacks.onRemove(s,u):this.callbacks.onRemove(r,s,u);return()=>{d?.(),h?.();for(let m of a)this.detach(m);a.clear()}}tick(e=performance.now()){this.renderTime=e;let t=0,r=this.fixedStepMs;if(r!==void 0&&r>0){let o=this.lastFrameNow<0?0:e-this.lastFrameNow;this.stepAcc+=o,t=Math.floor(this.stepAcc/r),t>Hr.MAX_STEPS_PER_FRAME?(this.stepAcc=0,t=Hr.MAX_STEPS_PER_FRAME):this.stepAcc-=t*r}this.lastFrameNow=e;let s=this.driven,i=0;for(let o=0;o<s.length;o++){let a=s[o];a.dead||(a.tick?.(e),a.prune?.(),i!==o&&(s[i]=a),i++)}return i!==s.length&&(s.length=i),t}defineEvent(e){let{confirmOn:t,...r}=e,s=new Br(r,this.clock??null);if(t!==void 0){if(t.mine!==void 0&&typeof this.sessionSource.sessionId!="string")throw new Error(`Predict.defineEvent: confirmOn.mine ("${t.mine}") requires a Predict built from a Room (it compares against room.sessionId); confirm manually instead.`);s._addTeardown(oh(this.callbacks,s,t,()=>this.sessionSource.sessionId))}return this.driven.push(s),s}spawns(e,t={}){let r=new Kn(t,this.clock??null),s=t.fields,i=t.step,o=s!==void 0&&i!==void 0?this.makeGroup(String(e),{mode:"reckon",fields:s,step:i,smoothMs:t.smoothMs??0,substep:t.substep}):void 0,a=o!==void 0?new Map:void 0,c=this.clock;return r.attach((u,d)=>{let h=this.callbacks.onAdd(e,(g,p)=>{if(u(g,p),o===void 0||a.has(g))return;let y=r.entryFor(g)?.leadMs??0,x=c?()=>{let k=c.lastServerTime(),P=k>0?Math.max(0,c.serverNow()-k):0;return Math.max(0,P+y)}:()=>Math.max(0,y);a.set(g,this.attachToGroup(g,this.planFor(o,g),x))}),m=this.callbacks.onRemove(e,(g,p)=>{a?.get(g)?.(),a?.delete(g),d(g,p)});return()=>{if(h?.(),m?.(),a!==void 0){for(let g of a.values())g();a.clear()}}}),o!==void 0&&r.bindReader((u,d)=>this.value(u,d)),this.driven.push(r),r}canonicalDelay(){return this.profileBuf[jt*Qe+Qn]}bindInputRenderDelay(e){e instanceof Er&&e.bindRenderDelay(()=>this.canonicalDelay())}reconciler(e,t){let r=new Yn(e,{...t,clock:t.clock??this.clock});return this.adoptFixedStep(r.stepMs),this.bindInputRenderDelay(t.input),this.installBoundOverlay(r),this.driven.push(r),r}sim(e){let t=new Xn({...e,clock:e.clock??this.clock});return this.adoptFixedStep(t.stepMs),this.bindInputRenderDelay(e.input),this.installBoundOverlay(t),this.driven.push(t),t}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,t){let r=Ke(e),s=r===void 0?void 0:this.slotByRef.get(r)?.get(t);if(s===void 0)return e[t];let i=this.slotBuf[s*je+vt]|0;return this.profileComputers[i](s)}valueAt(e,t,r){let s=Ke(e),i=s===void 0?void 0:this.slotByRef.get(s)?.get(t);if(i===void 0)return e[t];let o=i*je,a=this.slotBuf[o+vt]|0;if(this.profileComputers[a]!==this.computeReckon)return this.profileComputers[a](i);let c=this.simByRef.get(this.slotBuf[o+Ws]);if(c!==void 0){let u=this.slotBuf[o+Js]|0,d=u<c.posOf.length?c.posOf[u]:-1;if(d>=0){let h=this.clock?.lastServerTime?.()??NaN,m=Number.isNaN(h)?0:Math.max(0,r-h);return c.advance(c.instance,m,c.valueOut,r),c.valueOut[d]}}return this.slotBuf[o+ct]}read(e,t,r){let s=r??{},i=Ke(e),o=i===void 0?void 0:this.slotByRef.get(i);for(let a=0;a<t.length;a++){let c=t[a],u=o?.get(c);s[c]=u===void 0?e[c]:this.profileComputers[this.slotBuf[u*je+vt]|0](u)}return s}readAt(e,t,r,s){let i=s??{},o=Ke(e),a=o===void 0?void 0:this.slotByRef.get(o),c,u=!1;for(let d=0;d<t.length;d++){let h=t[d],m=a?.get(h);if(m===void 0){i[h]=e[h];continue}let g=m*je,p=this.slotBuf[g+vt]|0;if(this.profileComputers[p]!==this.computeReckon){i[h]=this.profileComputers[p](m);continue}if(!u&&(u=!0,c=this.simByRef.get(this.slotBuf[g+Ws]),c!==void 0)){let y=this.clock?.lastServerTime?.()??NaN,x=Number.isNaN(y)?0:Math.max(0,r-y);c.advance(c.instance,x,c.valueOut,r)}if(c!==void 0){let y=this.slotBuf[g+Js]|0,x=y<c.posOf.length?c.posOf[y]:-1;if(x>=0){i[h]=c.valueOut[x];continue}}i[h]=this.slotBuf[g+ct]}return i}computeLerpRaw(e){let t=this.slotBuf,r=e*je,s=this.profileBuf,i=(t[r+vt]|0)*Qe,o=this.renderTime,a=t[r+Fr]|0;if(a===0)return t[r+ct];let c=t[r+Lr]|0,u=r+Ks,d=(c-a+Me)%Me,h=(d+a-1)%Me,m=u+h*2;if(a===1)return t[m+1];let g=s[i+Qn],p=this.clock&&this.clock.lastServerTime()>0?this.clock.serverNow()-g-this.clock.smoothedRtt()/2:o-g,y=u+d*2;if(p<=t[y])return t[y+1];if(p>=t[m])return t[m+1];let x=a-2,k=(d+x)%Me;for(;x>0&&!(t[u+k*2]<=p);)x--,k=k===0?Me-1:k-1;let P=u+k*2,U=k+1>=Me?0:k+1,N=u+U*2,C=t[P],A=t[N]-C;if(A<=0)return t[N+1];let I=(p-C)/A,V=t[P+1],Z=t[N+1];return V+(Z-V)*I}applySimulation(e,t){let r=this.renderTime;if(e.lastApplyTime!==r){let s=e.out,i=e.smoothed,o=e.offset,a=i.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 h=0;h<a;h++)o[h]=0,i[h]=s[h];else if(Number.isNaN(c)){let h=Math.max(0,Math.min(r-e.lastApplyTime,100)),m=1-Math.exp(-h/e.smoothMs);for(let g=0;g<a;g++)i[g]+=(s[g]-i[g])*m}else{let h=Math.max(0,Math.min(r-e.lastApplyTime,100));if(c!==e.lastBaseT&&!Number.isNaN(e.lastBaseT)){let g=e.snap,p=e.frameVel;for(let y=0;y<a;y++){let x=i[y]+p[y]*h-s[y];o[y]=g>0&&Math.abs(x)>g?0:x}}else if(h>0){let g=e.outPrev,p=e.frameVel;for(let y=0;y<a;y++)p[y]=(s[y]-g[y])/h}let m=Math.exp(-h/e.smoothMs);for(let g=0;g<a;g++)o[g]*=m,i[g]=s[g]+o[g]}let d=e.outPrev;for(let h=0;h<a;h++)d[h]=s[h];e.lastBaseT=c,e.lastApplyTime=r}return e.smoothed[t]}};l(Hr,"MAX_STEPS_PER_FRAME",5);Xs=Hr});var Ph={};Ml(Ph,{DEFAULT_GRACE_TICKS:()=>Kc,Predict:()=>Xs,PredictedEventChannel:()=>Br,PredictedSpawns:()=>Kn,Reconciler:()=>Yn,SimReconciler:()=>Xn,classifyDrift:()=>Dr});var Oh=Oe(()=>{"use strict";Qc();No();Oo();Bo();Yc();Do()});var Zr="genex-native";var hi="genex_native";var pi="genex_protocol",mi="genex_attempt",gi="genex_nonce",pa="genex_caps";var sr="genex_";var ma="genex_r";var ga="entryRef",ya="genex_hash",ba="genex_referrer",wa="genex_ref";var yi="__genexNative";var gp=/^[0-9a-f]{32}$/,yp=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function Jt(n){return typeof n=="string"&&gp.test(n)}function _a(n){return typeof n=="string"&&yp.test(n)}var ir="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bp=(()=>{let n=new Array(128).fill(-1);for(let e=0;e<ir.length;e++)n[ir.charCodeAt(e)]=e;return n})();function Dl(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);if(r>=55296&&r<=56319){let s=t+1<n.length?n.charCodeAt(t+1):0;s>=56320&&s<=57343?(r=65536+(r-55296<<10)+(s-56320),t++):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 wp(n){let e="";for(let t=0;t<n.length;){let r=n[t],s,i;if(r<128)s=r,i=1;else if((r&224)===192)s=r&31,i=2;else if((r&240)===224)s=r&15,i=3;else if((r&248)===240)s=r&7,i=4;else return null;if(t+i>n.length)return null;for(let o=1;o<i;o++){let a=n[t+o];if((a&192)!==128)return null;s=s<<6|a&63}if(i===2&&s<128||i===3&&(s<2048||s>=55296&&s<=57343)||i===4&&(s<65536||s>1114111))return null;if(s>65535){let o=s-65536;e+=String.fromCharCode(55296+(o>>10),56320+(o&1023))}else e+=String.fromCharCode(s);t+=i}return e}function Ea(n){return Dl(n).length}function Ra(n){let e=Dl(JSON.stringify(n)),t="";for(let r=0;r<e.length;r+=3){let s=e[r],i=e[r+1],o=e[r+2];if(t+=ir[s>>2],t+=ir[(s&3)<<4|(i??0)>>4],i===void 0||(t+=ir[(i&15)<<2|(o??0)>>6],o===void 0))break;t+=ir[o&63]}return t}function xa(n){if(n.length%4===1)return;let e=[],t=0,r=0;for(let i=0;i<n.length;i++){let o=n.charCodeAt(i),a=o<128?bp[o]:-1;if(a<0)return;t=t<<6|a,r+=6,r>=8&&(r-=8,e.push(t>>r&255))}if(r>0&&(t&(1<<r)-1)!==0)return;let s=wp(e);if(s!==null)try{return JSON.parse(s)}catch{return}}var Nl=2048,Bl=32;var Ep=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;function Rp(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function bi(n,e){if(Object.keys(n).length!==e.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(n,r))return!1;return!0}var wi=["channel","v","type","slug","attemptId","nonce"];function xp(n){return n.channel===Zr&&n.v===1&&_a(n.slug)&&Jt(n.attemptId)&&Jt(n.nonce)}function Sa(n){if(!(!Rp(n)||!xp(n)))switch(n.type){case"ticket":return!bi(n,[...wi,"ticket","expiresAt"])||typeof n.ticket!="string"||n.ticket.length===0||n.ticket.length>Nl||typeof n.expiresAt!="string"||n.expiresAt.length>Bl||!Ep.test(n.expiresAt)?void 0:n;case"guest":case"cancel":return bi(n,wi)?n:void 0;case"foreground":return!bi(n,[...wi,"active"])||typeof n.active!="boolean"?void 0:n;case"network":return!bi(n,[...wi,"online"])||typeof n.online!="boolean"?void 0:n;default:return}}function Tp(n,e){if(typeof n!="string"||n.length===0)return{ok:!1,reason:"undecodable"};if(Ea(n)>4096)return{ok:!1,reason:"too-large"};let t=xa(n);if(t===void 0)return{ok:!1,reason:"undecodable"};let r=e(t);return r===void 0?{ok:!1,reason:"invalid"}:{ok:!0,message:r}}function ka(n){return Tp(n,Sa)}function va(n){let e=Ra(n);if(!(e.length>4096))return e}function _i(n,e){let t=n.charAt(0)==="?"?n.slice(1):n;if(t.length===0)return null;for(let r of t.split("&")){let s=r.indexOf("=");if(s!==-1&&r.slice(0,s)===e)return r.slice(s+1)}return null}function Ei(n){return _i(n,hi)==="1"}function Ca(n){if(!Ei(n))return null;let e=_i(n,mi),t=_i(n,gi),r=Number(_i(n,pi));return!Jt(e)||!Jt(t)||r!==1?null:{attemptId:e,nonce:t,protocol:r}}function Vl(n){return n.indexOf("%")===-1?n:n.replace(/%([0-9A-Fa-f]{2})/g,(e,t)=>{let r=parseInt(t,16);return r<128?String.fromCharCode(r):e})}function jl(n){let e=n.indexOf("="),t=e===-1?n:n.slice(0,e);return Vl(t.indexOf("+")===-1?t:t.split("+").join(" "))}function Ri(n){return ql(n,[ma])}var vp=[hi,pi,mi,gi,pa];function Ia(n){return ql(n,vp)}function ql(n,e){let t=n.charAt(0)==="?"?n.slice(1):n;if(t.length===0)return"";let r=t.split("&"),s=r.filter(o=>!e.includes(jl(o)));if(s.length===r.length)return`?${t}`;let i=s.join("&");return i.length===0?"":`?${i}`}var Ap=/^[!$-&(-;=?-~]+$/;function xi(n,e){if(typeof n!="string")return"";let t=n.charAt(0)==="?"?n.slice(1):n,r=t.indexOf("#");if(r!==-1&&(t=t.slice(0,r)),t.length===0||!Ap.test(t))return"";let i=t.split("&").filter(o=>{if(o.length===0)return!1;let a=jl(o);return!a.startsWith(sr)&&!e.includes(a)}).join("&");return i.length>1024?"":i}var Cp=/^#[!#-;=?-_a-~]+$/;function Si(n){return typeof n!="string"||n.length<2||n.length>4096||!Cp.test(n)||Vl(n).includes(sr)?"":n}var Ip=/^[a-z0-9._-]+$/,Pp=/^\[[0-9a-f:.]+\]$/;function Op(n){return Ip.test(n)&&/[a-z0-9]/.test(n)||Pp.test(n)}function Aa(n){let e=n.slice(0,8).toLowerCase(),t=e==="https://"?"https":e.slice(0,7)==="http://"?"http":null;if(t===null)return null;let r=t.length+3,s=n.length;for(let u=r;u<n.length;u++){let d=n.charAt(u);if(d==="/"||d==="?"||d==="#"||d==="\\"){s=u;break}}if(s-r>255)return null;let i=n.slice(r,s).toLowerCase();if(i.length===0||i.indexOf("@")!==-1)return null;let o=i,a="",c=i.lastIndexOf(":");if(c!==-1&&i.charAt(i.length-1)!=="]"&&(o=i.slice(0,c),a=i.slice(c+1)),!Op(o))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===(t==="https"?443:80)?"":`:${u}`}return`${t}://${o}${a}`}function ar(n,e){if(typeof n!="string"||n.length===0)return null;let t=Aa(n);return t===null||t.length>255||typeof e=="string"&&Aa(e)===t?null:t}var Gl=["open","save","fullscreen"];var Hl=50*1024*1024,Mp=16;function zl(n){return typeof n=="string"&&Gl.includes(n)}function Pa(n){if(!Array.isArray(n))return[];let e=[],t=Math.min(n.length,Mp);for(let r=0;r<t;r++){let s=n[r];zl(s)&&!e.includes(s)&&e.push(s)}return e}var Hp=null;function Jl(n){Hp=n}var Wp=null;function Kl(n){Wp=n}var Jp=null;function Yl(n){Jp=n}var rs=1,Ba="genex:embed:retry",uu="genex:guest:popover-dismissed",du="genex:embed:local-auth",fu="genex:embed:entry-referrer",Kp="none",Xl="genex:player",Yp="0.33.0",ue=null,fe="pending",rt=null,hn=!1,dn=null,cr=!1,fn,lr,hu=0,ze,La,pn=null,pu=[],dr=!1,Dn=!1,ts=!1,nt=0,fr=1e4,Xp=2e3,Qp=10*6e4,Zp=6e4,Ql=500,em=3e4,tm=3e4,we,gt,ur,Zl=!1,eu,Ti=null,tu=new Set;var nu=!1,nm=new Map,mu=[],ss=[],ns=null,ki=null,Mn,Oa,Ma=!1,vi=new Map;function Se(){return globalThis.window}function Fa(){return globalThis.document}function is(n,e,t){let r;if(t!==void 0)try{let s=globalThis.AbortSignal;s&&typeof s.timeout=="function"&&(r=s.timeout(t))}catch{}return globalThis.fetch(n,r?{...e,signal:r}:e)}function rm(){try{return Se()?.sessionStorage?.getItem(Ba)==="1"}catch{return!1}}function sm(){try{Se()?.sessionStorage?.setItem(Ba,"1")}catch{}}function Ua(){try{Se()?.sessionStorage?.removeItem(Ba)}catch{}}function im(){try{return Se()?.sessionStorage?.getItem(du)==="1"}catch{return!1}}function om(){try{Se()?.sessionStorage?.setItem(du,"1")}catch{}}function am(){try{let n=Se()?.sessionStorage?.getItem(fu);return n==null?void 0:ar(n)}catch{return}}function cm(n){try{Se()?.sessionStorage?.setItem(fu,n??Kp)}catch{}}function lm(){try{return Se()?.sessionStorage?.getItem(uu)==="1"}catch{return!1}}function um(){try{Se()?.sessionStorage?.setItem(uu,"1")}catch{}}function dm(){try{let n=Se()?.localStorage;if(!n)return"no-storage";let e=n.getItem(Xl);return e||(e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,n.setItem(Xl,e)),e}catch{return"no-storage"}}function Ci(n){let e=Se();if(!e||dr)return;if(dr=!0,ur!==void 0&&(clearTimeout(ur),ur=void 0),ue={slug:n.slug,apiUrl:n.apiUrl.replace(/\/$/,""),dashboardOrigins:[...n.dashboardOrigins]},fe="pending",Eu(e),Kl({apiUrl:ue.apiUrl,dashboardOrigins:ue.dashboardOrigins,getToken:()=>ze,getParentOrigin:()=>pn,isEmbedded:We,isNative:ut,isLocalTest:()=>hn}),Yl({apiUrl:ue.apiUrl,dashboardOrigins:ue.dashboardOrigins,getToken:()=>ze,getParentOrigin:()=>pn,isEmbedded:We,isNative:ut,isLocalTest:()=>hn}),Ha(e)){Dm(e);return}Pi("connecting");let t=Ru(e);if(t){km(e,t);return}We()?Sm(e):Cm(e)}function We(){let n=Se();if(!n)return!1;try{return n.self!==n.top}catch{return!0}}function fm(){let n=Se();return n?We()?"page":ut()||Va(n)?"app":dr?hn?"local":"standalone":Ha(n,!1)?"local":"standalone":"standalone"}function gu(){return ze?{embedToken:ze}:void 0}function yu(){return La??[]}function $a(){return(fe==="authenticated"||fe==="guest")&&rt?Promise.resolve({user:rt,guest:fe==="guest"}):fe==="blocked"?Promise.reject(new Error("genex embed auth: blocked")):(hm("waitForPlayer"),new Promise((n,e)=>{ss.push({resolve:n,reject:e})}))}function hm(n){if(!dr){if(!Zl){Zl=!0;try{console.error(`[genex] ${n}() 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{}}ur===void 0&&(ur=setTimeout(()=>{ur=void 0,dr||Kt("no-identity")},fr))}}var pm=32*1024;async function bu(){if(!ue)throw new Error("genex embed: call initEmbed() first");if(fe==="pending"&&await $a(),fe==="blocked")throw new Error("genex embed auth: blocked")}function wu(n,e={}){let t={Authorization:`Bearer ${ze}`};return e.body!==void 0&&(t["Content-Type"]="application/json"),e.ifVersion!==void 0&&(t["If-Match"]=String(e.ifVersion)),is(`${ue.apiUrl}/api/projects/${encodeURIComponent(ue.slug)}${n}`,{method:e.method??"GET",headers:t,body:e.body,keepalive:e.body!==void 0&&e.body.length<=pm?!0:void 0})}async function mm(n){return n.status!==403?!1:(await n.json().catch(()=>null))?.error==="staging_no_save"}async function gm(n){return n.status===409?{saved:!1,conflict:!0,version:(await n.json().catch(()=>({}))).version}:n.ok?{saved:!0,version:(await n.json()).version}:await mm(n)?{saved:!1,staging:!0}:(st("error",{error:new Error(`genex state save failed (${n.status})`)}),{saved:!1})}async function ym(n,e){return await bu(),fe==="guest"?(Oa=n,Ma=!0,{saved:!1,guest:!0,queued:!0}):gm(await wu("/state/me",{method:"PUT",body:JSON.stringify(n),ifVersion:e?.ifVersion}))}async function bm(n,e){let t=e?.board??"main",r=e?.mode??"max";if(await bu(),fe==="guest"){let o=vi.get(t);return(!o||(r==="min"?n<o.score:n>o.score))&&vi.set(t,{score:n,mode:r}),{submitted:!1,guest:!0,queued:!0}}let s=await wu("/scores",{method:"POST",body:JSON.stringify({score:n,board:t,mode:r})});if(!s.ok)return st("error",{error:new Error(`genex score submit failed (${s.status})`)}),{submitted:!1};let i=await s.json();return{submitted:!0,best:i.best,improved:i.improved}}async function wm(){try{if(Ma){let e=Oa;Oa=void 0,Ma=!1,await ym(e)}let n=[...vi.entries()];vi.clear();for(let[e,{score:t,mode:r}]of n)await bm(t,{board:e,mode:r})}catch(n){st("error",{error:n})}}function st(n,e){let t=nm.get(n);if(t)for(let r of[...t])try{r(e)}catch{}}var _m=["embed"];function _u(n,e){let t={ticket:null,guest:!1,entryHash:"",entryReferrer:null};if(!n||n.length<2)return t;try{let r=new URLSearchParams(n.slice(1));return{ticket:r.get("genex_ticket"),guest:r.get("genex_guest")==="1",entryHash:Si(r.get(ya)),entryReferrer:ar(r.get(ba),e)}}catch{return t}}function Em(n,e){try{return new URLSearchParams(n).get(e)}catch{return null}}function Eu(n){if(Ti)return Ti;let e="",t="",r=null;try{e=n.location.search??"",t=Ai??n.location.hash??"",r=n.location.origin??null}catch{}let s=We(),i=_u(t,r),o=!s&&(!!i.ticket||i.guest),a=xi(e,_m);return Ti={search:a?`?${a}`:"",hash:o?i.entryHash:t.includes(sr)?"":t,referrer:Rm(e,s,o,i.entryReferrer,r)},Ti}function Rm(n,e,t,r,s){let i=am();if(i!==void 0)return i;let o;return e?o=ar(Em(n,wa),s):t?o=r:o=ar(Fa()?.referrer,s),cm(o),o}function xm(){if(!(nu||tu.size===0)){nu=!0;for(let n of[...tu])try{n()}catch{}}}function Sm(n){eu=e=>{Tm(e)},n.addEventListener("message",eu),n.parent.postMessage({type:"genex:embed:ready",v:rs},"*"),we=setTimeout(()=>{hr()},fr)}function ru(){return(fe==="pending"||fe==="guest")&&!Dn}async function Tm(n){if(!ue)return;let e=n.data;if(!e||e.v!==rs)return;let t=e.type==="genex:embed:ticket",r=e.type==="genex:embed:guest";if(!(!t&&!r)&&!(t&&(!ru()||typeof e.ticket!="string"||!e.ticket))&&!(r&&(fe!=="pending"||Dn||ts))){if(!ue.dashboardOrigins.includes(n.origin)){let s=await Da();if(t&&!ru()||r&&(fe!=="pending"||Dn||ts)||!s.includes(n.origin))return}if(we!==void 0&&clearTimeout(we),pn=n.origin,pu=Pa(e.caps),r){await hr();return}await Ga(e.ticket)}}function Va(n){let e=n.ReactNativeWebView;return!e||typeof e!="object"?null:typeof e.postMessage=="function"?e:null}function Ru(n){if(We())return null;let e;try{e=n.location.search??""}catch{return null}return!Ei(e)||!Va(n)?null:Ca(e)}function ut(){return dn!==null}function Nn(n){let e=Se();if(!e||!ue||!dn)return;let t=Va(e);if(!t)return;let r=va({channel:Zr,v:1,slug:ue.slug,attemptId:dn.attemptId,nonce:dn.nonce,...n});if(r)try{t.postMessage(r)}catch{}}function xu(n){ut()&&Nn({type:"error",code:n})}function km(n,e){dn=e,hu=Date.now(),n[yi]=r=>{vm(r)},Nn({type:"ready",sdkVersion:Yp,capabilities:["native-ticket","native-guest","heartbeat"]}),we=setTimeout(()=>{hr()},fr)}async function vm(n){if(!ue||!dn)return;let e=ka(n);if(!e.ok)return;let t=e.message;if(!(t.slug!==ue.slug||t.attemptId!==dn.attemptId||t.nonce!==dn.nonce))switch(t.type){case"ticket":we!==void 0&&clearTimeout(we),await Ga(t.ticket);return;case"guest":we!==void 0&&clearTimeout(we),await hr();return;case"cancel":Su(),xm();return;case"foreground":case"network":return}}function Su(){we!==void 0&&clearTimeout(we),we=void 0,gt!==void 0&&clearTimeout(gt),gt=void 0,fn!==void 0&&clearTimeout(fn),fn=void 0,lr!==void 0&&clearInterval(lr),lr=void 0}function Tu(){!ut()||lr!==void 0||(lr=setInterval(()=>{Nn({type:"heartbeat",uptimeMs:Math.max(0,Date.now()-hu)})},tm),lr.unref?.())}function Am(){!ut()||cr||(cr=!0,Nn({type:"reauth-required"}),fn=setTimeout(()=>{fn=void 0,cr&&(cr=!1,st("error",{error:new Error("embed session expired")}),Kt("session-expired"))},em))}function ja(){cr=!1,fn!==void 0&&clearTimeout(fn),fn=void 0}function qa(n,e){let t=Se();if(!(!t||!We()))try{t.parent.postMessage(n,e)}catch{}}async function Cm(n){let e=ku(n);if(e.ticket){su(),await Ga(e.ticket);return}if(e.guest){su(),await hr();return}Pi("redirecting"),await Ii(n,{guestOk:!0})}function su(){we!==void 0&&clearTimeout(we),we=setTimeout(()=>{we=void 0,fe==="pending"&&Kt("no-identity")},fr+Xp)}var Ai=null;function Im(n){return n.location.pathname+Ri(n.location.search)}function ku(n){let e=Ai??n.location.hash;Ai=null;let{ticket:t,guest:r,entryHash:s}=_u(e);if(t||r)try{n.history.replaceState(n.history.state??null,"",Im(n)+s)}catch{}return{ticket:t,guest:r}}async function Ii(n,e){if(!ue||hn||ut())return;let t=e?.guestOk?ue.dashboardOrigins[0]??(await Da())[0]:(await Da())[0]??ue.dashboardOrigins[0];if(!t){Kt();return}let r=n.location.origin+n.location.pathname,s=Ia(Ri(n.location.search));s.length-1<=1024&&r.length+s.length<=2048&&s.indexOf("#")===-1&&(r+=s);let i=e?.guestOk?"&guest=ok":"",o=`${t}/play/authorize?returnTo=${encodeURIComponent(r)}&slug=${encodeURIComponent(ue.slug)}${i}`,a=Eu(n).referrer;a&&(o+=`&${ga}=${encodeURIComponent(a)}`),o+=Si(n.location.hash),n.location.replace(o)}async function Da(){if(!ue)return[];try{let n=await is(`${ue.apiUrl}/api/embed/dashboard-origins`);if(!n.ok)return ue.dashboardOrigins;let e=await n.json();if(Array.isArray(e.origins)&&e.origins.every(t=>typeof t=="string"))return e.origins}catch{}return ue.dashboardOrigins}async function Ga(n){if(!ue||hn||Dn||fe!=="pending"&&fe!=="guest"&&!(cr&&fe==="authenticated"))return;let t=fe==="guest",r=++nt;Dn=!0;try{let s=await is(`${ue.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ticket:n})},fr);if(r!==nt)return;if(!s.ok){st("error",{error:new Error(`ticket redemption failed (${s.status})`)}),t||await iu();return}let i=await s.json();if(r!==nt)return;ze=i.embedToken,rt=i.user,La=i.colyseus?.urls,fe="authenticated",we!==void 0&&clearTimeout(we),we=void 0,Ua(),Oi(),Wa(),za(),We()&&pn&&qa({type:"genex:embed:authenticated",v:rs},pn),ut()&&(ja(),Nn({type:"authenticated",guest:!1}),Tu()),t&&await wm();let o={user:rt};for(let a of mu.splice(0))a.resolve(o);for(let a of ss.splice(0))a.resolve({user:rt,guest:!1});st("authenticated",o)}catch(s){if(r!==nt)return;st("error",{error:s}),t||await iu()}finally{Dn=!1}}async function hr(){if(!ue||hn||ts||Dn||fe!=="pending"&&fe!=="guest")return;let n=++nt;ts=!0;try{let e=await is(`${ue.apiUrl}/api/embed/guest-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:ue.slug,playerId:dm()})},fr);if(n!==nt)return;if(!e.ok){st("error",{error:new Error(`guest session failed (${e.status})`)}),xu("guest-failed"),Kt(e.status===404?"not-available":"no-identity");return}let t=await e.json();if(n!==nt)return;ze=t.embedToken,rt=t.user,La=t.colyseus?.urls,Pm()}catch(e){if(n!==nt)return;st("error",{error:e}),Kt()}finally{ts=!1}}function Pm(){let n=fe!=="guest";if(fe="guest",we!==void 0&&clearTimeout(we),Oi(),za(),We()?qa({type:"genex:embed:authenticated",v:rs,guest:!0},pn??"*"):ut()?(Nn({type:"authenticated",guest:!0}),Tu()):n&&!lm()&&$m(),rt){let e={user:rt};for(let t of ss.splice(0))t.resolve({user:rt,guest:!0});st("guest",e)}}function Om(n){try{let e=new URL(n.location.origin);return e.protocol==="http:"&&(e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]")}catch{return!1}}function Ha(n,e=!0){if(We()||Ru(n)||!Om(n))return!1;let t=null;try{t=new URLSearchParams(n.location.search)}catch{}return t?.get("genex_local_test")==="1"?!0:t?.get("genex_auth")==="1"?(e&&om(),!1):im()?!1:!Mm(n)}function Mm(n){let e=Ai??n.location.hash;return!!e&&e.includes("genex_")}function Dm(n){hn=!0,ku(n);let e={id:"local:test",name:"Local Tester"};rt=e,fe="guest",Oi();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 t of ss.splice(0))t.resolve({user:e,guest:!0});st("guest",{user:e})}async function iu(){let n=Se();if(we!==void 0&&clearTimeout(we),we=void 0,ut()){ja(),xu("ticket-rejected"),Kt();return}if(n&&!We()&&!rm()){sm(),Pi("redirecting"),await Ii(n,{guestOk:!0});return}Kt()}function za(){gt!==void 0&&clearTimeout(gt),gt=setTimeout(()=>{vu()},Qp)}async function vu(){if(!ue||fe!=="authenticated"&&fe!=="guest"||!ze)return;let n=nt,e=ze,t;try{let r=await is(`${ue.apiUrl}/api/embed/session/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`},keepalive:!0});if(t=r.status,n!==nt||ze!==e)return;if(r.ok){let s=await r.json();if(n!==nt||ze!==e)return;ze=s.embedToken,za();return}}catch{t=void 0}if(!(n!==nt||ze!==e)){if(t===401){if(fe==="guest"){hr();return}if(ut()){Am();return}st("error",{error:new Error("embed session expired")}),Kt("session-expired");return}gt!==void 0&&clearTimeout(gt),gt=setTimeout(()=>{vu()},Zp)}}function Kt(n="no-identity"){if(fe==="blocked")return;nt++,fe="blocked",rt=null,ze=void 0,we!==void 0&&clearTimeout(we),gt!==void 0&&clearTimeout(gt),Wa(),ut()?(Su(),ja(),Oi(),Nn({type:"blocked",reason:n})):Pi(We()?"blocked-embedded":"blocked-standalone"),We()&&qa({type:"genex:embed:blocked",v:rs},pn??"*");let e=new Error("genex embed auth: blocked");for(let t of mu.splice(0))t.reject(e);for(let t of ss.splice(0))t.reject(e);st("blocked")}var Nm={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}},Bm="https://cdn.genex.technology/fonts/GeistMono-variable.woff2",Au="'Geist Mono',ui-monospace,SFMono-Regular,Menlo,monospace",ou=!1,au="!<>-_/[]{}=+*^?#$%&@",Cu=50,cu=10,lu=[{name:"churn",ticks:5},{name:"settle",ticks:10},{name:"hold",ticks:12},{name:"dissolve",ticks:8}];function Na(n){let e="";for(let t=0;t<n;t++)e+=au[Math.floor(Math.random()*au.length)];return e}function Iu(){try{let n=Se();return!n||typeof n.matchMedia!="function"?!0:n.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!0}}function Lm(n,e){if(Iu())return n.textContent=e,()=>{};let t=0;n.textContent=Na(e.length);let r=setInterval(()=>{if(t++,t>=cu){n.textContent=e,clearInterval(r);return}let s=Math.floor(t/cu*e.length);n.textContent=e.slice(0,s)+Na(e.length-s)},Cu);return()=>clearInterval(r)}function Fm(n,e){if(Iu())return n.textContent=e,()=>{};let t=0,r=0,s=()=>{let o=lu[t],a;o.name==="churn"?a=0:o.name==="settle"?a=Math.floor(r/o.ticks*e.length):o.name==="hold"?a=e.length:a=e.length-Math.floor(r/o.ticks*e.length),n.textContent=e.slice(0,a)+Na(e.length-a),r++,r>=o.ticks&&(r=0,t=(t+1)%lu.length)};s();let i=setInterval(s,Cu);return()=>clearInterval(i)}function Pu(n){if(!ou){ou=!0;try{let e=Se()?.FontFace,t=n.fonts;if(!e||!t?.add)return;new e("Geist Mono",`url(${Bm}) format('woff2')`,{weight:"100 900",display:"swap"}).load().then(s=>t.add(s)).catch(()=>{})}catch{}}}function Pi(n){let e=Fa();if(e?.createElement)try{ns||(ns=Um(e)),ns.setContent(n)}catch{}}function Oi(n=!1){try{let e=ns;if(ns=null,!e)return;e.stopText();let t=e.root;if(n||!t.style){t.remove?.();return}t.style.pointerEvents="none",t.style.transition="opacity 180ms ease",t.style.opacity="0",setTimeout(()=>{try{t.remove?.()}catch{}},220)}catch{}}function Um(n){Pu(n);let e=n.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:${Au};text-align:center;pointer-events:auto;user-select:none`;let t=n.createElement("div");t.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(t);let r=n.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=Se();c&&(r.disabled=!0,Ua(),Ii(c))}),e.appendChild(r);let s=()=>{n.body&&!e.isConnected&&n.body.appendChild(e)};n.body?s():n.addEventListener?.("DOMContentLoaded",s);let i,o,a=()=>{i!==void 0&&(clearTimeout(i),i=void 0),o&&(o(),o=void 0)};return{root:e,stopText:a,setContent(c){let u=Nm[c];a(),t.textContent=u.title,t.style.letterSpacing=u.wordmark?"0.22em":"",t.style.marginRight=u.wordmark?"-0.22em":"";let d=()=>{t.style.opacity="1",o=u.wordmark?Fm(t,u.title):Lm(t,u.title)};u.instant||Ql<=0?d():(t.style.opacity="0",i=setTimeout(()=>{i=void 0,d()},Ql)),r.style.display=u.button?"inline-block":"none",u.button&&(r.textContent=u.button),s()}}}function $m(){let n=Fa();if(!(!n?.createElement||ki))try{ki=Vm(n)}catch{}}function Wa(){Mn!==void 0&&(clearTimeout(Mn),Mn=void 0);try{ki?.root?.remove?.()}catch{}ki=null}function Vm(n){Pu(n);let e=!1;try{let c=Se(),u=c?.navigator;if(c&&u){let d=c.matchMedia?.("(pointer: coarse)").matches??!1,h=(u.maxTouchPoints??0)>1,m=u.userAgentData?u.userAgentData.mobile:/Mobi|Android/i.test(u.userAgent??"");e=h&&d||m}}catch{}let t=n.createElement("div");t.setAttribute("data-genex-guest-popover",""),t.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=n.createElement("div");r.style.cssText=`display:flex;align-items:center;border-radius:12px;background:rgba(0,0,0,0.85);color:#fff;font-family:${Au};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"),t.appendChild(r);let s=n.createElement("span");s.textContent=!e&&rt?.name?`Playing as ${rt.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 i=n.createElement("button");i.textContent="Sign in",i.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"),i.addEventListener("mouseenter",()=>{i.style.background="#3f51a8"}),i.addEventListener("mouseleave",()=>{i.style.background="#4b60bf"}),i.addEventListener("click",()=>{let c=Se();c&&(i.disabled=!0,Ua(),Ii(c))}),r.appendChild(i);let o=n.createElement("button");if(o.textContent="\xD7",o.setAttribute("aria-label","Dismiss"),o.style.cssText="font-size:16px;line-height:1;padding:6px 8px;border:none;cursor:pointer;background:transparent;color:rgba(255,255,255,0.6)",o.addEventListener("click",()=>{um(),Wa()}),r.appendChild(o),e){let c=n.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>',t.appendChild(c);let u=d=>{r.style.display=d?"none":"flex",c.style.display=d?"flex":"none"};Mn=setTimeout(()=>u(!0),5e3),r.addEventListener("pointerdown",()=>{Mn!==void 0&&clearTimeout(Mn),Mn=void 0}),c.addEventListener("click",()=>u(!1))}let a=()=>{n.body&&!t.isConnected&&n.body.appendChild(t)};return n.body?a():n.addEventListener?.("DOMContentLoaded",a),{root:t}}Jl({getShell:fm,isLocalTest:()=>{let n=Se();return!n||We()?!1:dr?hn:Ha(n,!1)},getConfig:()=>ue,getParentOrigin:()=>pn,getShellCaps:()=>pu});var ul={};Ml(ul,{chatSend:()=>pb,claim:()=>mb,claimAsHost:()=>gb,connect:()=>rb,destroy:()=>bb,dispose:()=>sb,drainEventsJson:()=>Ab,leave:()=>Qh,listen:()=>db,objectsJson:()=>kb,open:()=>nb,playersJson:()=>Tb,release:()=>yb,reportEliminated:()=>wb,reportFinish:()=>Eb,reportScore:()=>_b,send:()=>ub,sendInput:()=>fb,serverNow:()=>Rb,sessionJson:()=>Sb,setIdentity:()=>X0,setMe:()=>ib,setObject:()=>cb,setRoomOpen:()=>hb,setShared:()=>ab,sharedJson:()=>vb,snapMe:()=>ob,snapObject:()=>lb,timeUntil:()=>xb,version:()=>Y0});ArrayBuffer.isView||(ArrayBuffer.isView=n=>n!==null&&typeof n=="object"&&n.buffer instanceof ArrayBuffer);typeof globalThis>"u"&&typeof window<"u"&&(window.globalThis=window);typeof FormData>"u"&&(globalThis.FormData=class{});Yt();var It=class extends Error{constructor(t,r,s){super(r);l(this,"code");l(this,"headers");l(this,"status");l(this,"response");l(this,"data");this.name="ServerError",this.code=t,s&&(this.headers=s.headers,this.status=s.status,this.response=s.response,this.data=s.data)}};var os=class n extends Error{constructor(t,r){super(t);l(this,"code");this.code=r,this.name="MatchMakeError",Object.setPrototypeOf(this,n.prototype)}};Yt();He();He();He();He();He();He();He();He();var sf=256,wc=5,Gn=class Gn{constructor(e,t={}){l(this,"instance");l(this,"mode");l(this,"historySize");l(this,"_desc");l(this,"_numFields");l(this,"_slots");l(this,"_slotLens");l(this,"_slotHead",0);l(this,"_slotCount",0);l(this,"_outBuffer");l(this,"_seq",0);l(this,"_encoder");this.instance=e,this.mode=t.mode??"reliable",this.historySize=this.mode==="unreliable"?Math.max(1,t.historySize??3):1,this._desc=dc(e);let r=this._desc.metadata?.[Fe];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(sf);this._outBuffer=new Uint8Array((sf+wc)*this.historySize)}this._encoder=new ms(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[_],t=this.instance[Ue];for(let r=0;r<=this._numFields;r++)t[r]===void 0||t[r]===null||e.markDirty(r)}copyInto(e){let t=this.instance[Ue],r=e[Ue];for(let s=0;s<=this._numFields;s++)r[s]=t[s]}_produceDelta(){let e=this._encoder.encode();return this._encoder.discardChanges(),e}_pushAndEmitRing(e){this._seq++;let t=this._slots[this._slotHead];return e.length>t.byteLength&&(t=this._slots[this._slotHead]=Gn._grow(t,e.length,"unreliable ring slot")),t.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,t=wc;for(let o=0;o<this._slotCount;o++)t+=this._slotLens[o]+wc;let r=this._outBuffer;t>r.byteLength&&(r=this._outBuffer=Gn._grow(r,t,"unreliable output packet"));let s={offset:0};Q.number(r,e,s);let i=(this._slotHead-this._slotCount+this.historySize)%this.historySize;for(let o=0;o<this._slotCount;o++){let a=(i+o)%this.historySize,c=this._slotLens[a];Q.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,t,r){let s=Math.max(t,e.byteLength*2);return Gn._warned||(Gn._warned=!0,console.warn(`@colyseus/schema/input: InputEncoder buffer overflow in ${r}. Growing to ${s} bytes.`)),new Uint8Array(s)}};l(Gn,"_warned",!1);var oo=Gn;Yt();Ec();fo();var Hn,kt,xr,ks,vs,As,Cs,Is,Ps,Sr,Os,ho,lf,Tr=class{constructor(e){he(this,ho);he(this,Hn);he(this,kt);he(this,xr);he(this,ks);he(this,vs,!1);he(this,As);he(this,Cs,!1);he(this,Is,!1);he(this,Ps);he(this,Sr);he(this,Os);pe(this,Hn,e)}get patchRate(){return H(this,Sr)}applyReflection(e,t,r){let s=Tt.decode(e.subarray(0,r),t);Tt.makeEncodable(s.state.constructor),pe(this,As,s.state.constructor),H(this,Hn).clock===Rr&&(H(this,Hn).clock=new uo)}applyOptions(e,t){let r=e[t.offset++];pe(this,Cs,(r&Bn.RENDER_TIME)!==0),pe(this,Is,(r&Bn.RECKON_TIME)!==0),r&Bn.FIXED_TIMESTEP&&pe(this,Ps,te.number(e,t)),r&Bn.PATCH_RATE&&pe(this,Sr,te.number(e,t)),r&Bn.SUB_STEPS&&pe(this,Os,te.number(e,t))}ackInput(e){return H(this,kt)?H(this,kt).ackInput(e):-1}reset(){H(this,kt)?.reset()}handle(e){if(H(this,kt))return e!==void 0&&On(this,ho,lf).call(this,e),H(this,kt);let t=e?.type??H(this,As);if(!t)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 t,s=new oo(r,e);return pe(this,kt,new Er(H(this,Hn),r,s,{stampRender:H(this,Cs),stampReckon:H(this,Is),renderDelay:e?.renderDelay,allowRewind:e?.allowRewind,tickRate:H(this,Ps),patchRate:H(this,Sr),subSteps:H(this,Os)})),pe(this,xr,e),pe(this,ks,s),H(this,kt)}};Hn=new WeakMap,kt=new WeakMap,xr=new WeakMap,ks=new WeakMap,vs=new WeakMap,As=new WeakMap,Cs=new WeakMap,Is=new WeakMap,Ps=new WeakMap,Sr=new WeakMap,Os=new WeakMap,ho=new WeakSet,lf=function(e){if(H(this,vs))return;let t=H(this,kt),r=[];e.type!==void 0&&e.type!==t.data?.constructor&&r.push("type"),e.mode!==void 0&&e.mode!==t.mode&&r.push("mode"),e.historySize!==void 0&&t.mode==="unreliable"&&e.historySize!==H(this,ks).historySize&&r.push("historySize"),e.renderDelay!==void 0&&e.renderDelay!==H(this,xr)?.renderDelay&&r.push("renderDelay"),e.allowRewind!==void 0!=(H(this,xr)?.allowRewind!==void 0)&&r.push("allowRewind"),r.length!==0&&(pe(this,vs,!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 xc;try{xc=new TextDecoder}catch{}var F,ft,w=0;var _f=[],Sc=_f,Tc=0,de={},se,Rn,dt=0,Ft=0,Le,rn,Xe=[],re,uf={useRecords:!1,mapsAsObjects:!0},Ms=class{},vc=new Ms;vc.name="MessagePack 0xC1";var xn=!1,df=2;var Sn=class n{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,t){if(F)return Tf(()=>(mo(),this?this.unpack(e,t):n.prototype.unpack.call(uf,e,t)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof t=="object"?(ft=t.end||e.length,w=t.start||0):(w=0,ft=t>-1?t:e.length),Tc=0,Ft=0,Rn=null,Sc=_f,Le=null,F=e;try{re=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(r){throw F=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 n){if(de=this,this.structures)return se=this.structures,po(t);(!se||se.length>0)&&(se=[])}else de=uf,(!se||se.length>0)&&(se=[]);return po(t)}unpackMultiple(e,t){let r,s=0;try{xn=!0;let i=e.length,o=this?this.unpack(e,i):yo.unpack(e,i);if(t){if(t(o,s,w)===!1)return;for(;w<i;)if(s=w,t(po(),s,w)===!1)return}else{for(r=[o];w<i;)s=w,r.push(po());return r}}catch(i){throw i.lastPosition=s,i.values=r,i}finally{xn=!1,mo()}}_mergeStructures(e,t){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 i=e[r];i&&(i.isShared=!0,r>=32&&(i.highByte=r-32>>5))}e.sharedLength=e.length;for(let r in t||[])if(r>=0){let s=e[r],i=t[r];i&&(s&&((e.restoreStructures||(e.restoreStructures=[]))[r]=s),e[r]=i)}return this.structures=e}decode(e,t){return this.unpack(e,t)}};function po(n){try{if(!de.trusted&&!xn){let t=se.sharedLength||0;t<se.length&&(se.length=t)}let e;if(de._readStruct&&F[w]<64&&F[w]>=32?(e=de._readStruct(F,w,ft),F=null,!(n&&n.lazy)&&e&&(e=e.toJSON()),w=ft):e=ke(),Le&&(w=Le.postBundlePosition,Le=null),xn&&(se.restoreStructures=null),w==ft)se&&se.restoreStructures&&ff(),se=null,F=null,rn&&(rn=null);else{if(w>ft)throw new Error("Unexpected end of MessagePack data");if(!xn){let t;try{t=JSON.stringify(e,(r,s)=>typeof s=="bigint"?`${s}n`:s).slice(0,100)}catch(r){t="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+t)}}return e}catch(e){throw se&&se.restoreStructures&&ff(),mo(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||w>ft)&&(e.incomplete=!0),e}}function ff(){for(let n in se.restoreStructures)se[n]=se.restoreStructures[n];se.restoreStructures=null}function ke(){let n=F[w++];if(n<160)if(n<128){if(n<64)return n;{let e=se[n&63]||de.getStructures&&Ef()[n&63];return e?(e.read||(e.read=Ac(e,n&63)),e.read()):n}}else if(n<144)if(n-=128,de.mapsAsObjects){let e={};for(let t=0;t<n;t++){let r=xf();r==="__proto__"&&(r="__proto_"),e[r]=ke()}return e}else{let e=new Map;for(let t=0;t<n;t++)e.set(ke(),ke());return e}else{n-=144;let e=new Array(n);for(let t=0;t<n;t++)e[t]=ke();return de.freezeData?Object.freeze(e):e}else if(n<192){let e=n-160;if(Ft>=w)return Rn.slice(w-dt,(w+=e)-dt);if(Ft==0&&ft<140){let t=e<16?Cc(e):Rf(e);if(t!=null)return t}return kc(e)}else{let e;switch(n){case 192:return null;case 193:return Le?(e=ke(),e>0?Le[1].slice(Le.position1,Le.position1+=e):Le[0].slice(Le.position0,Le.position0-=e)):vc;case 194:return!1;case 195:return!0;case 196:if(e=F[w++],e===void 0)throw new Error("Unexpected end of buffer");return Rc(e);case 197:return e=re.getUint16(w),w+=2,Rc(e);case 198:return e=re.getUint32(w),w+=4,Rc(e);case 199:return zn(F[w++]);case 200:return e=re.getUint16(w),w+=2,zn(e);case 201:return e=re.getUint32(w),w+=4,zn(e);case 202:if(e=re.getFloat32(w),de.useFloat32>2){let t=go[(F[w]&127)<<1|F[w+1]>>7];return w+=4,(t*e+(e>0?.5:-.5)>>0)/t}return w+=4,e;case 203:return e=re.getFloat64(w),w+=8,e;case 204:return F[w++];case 205:return e=re.getUint16(w),w+=2,e;case 206:return e=re.getUint32(w),w+=4,e;case 207:return de.int64AsType==="number"?(e=re.getUint32(w)*4294967296,e+=re.getUint32(w+4)):de.int64AsType==="string"?e=re.getBigUint64(w).toString():de.int64AsType==="auto"?(e=re.getBigUint64(w),e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=re.getBigUint64(w),w+=8,e;case 208:return re.getInt8(w++);case 209:return e=re.getInt16(w),w+=2,e;case 210:return e=re.getInt32(w),w+=4,e;case 211:return de.int64AsType==="number"?(e=re.getInt32(w)*4294967296,e+=re.getUint32(w+4)):de.int64AsType==="string"?e=re.getBigInt64(w).toString():de.int64AsType==="auto"?(e=re.getBigInt64(w),e>=BigInt(-2)<<BigInt(52)&&e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=re.getBigInt64(w),w+=8,e;case 212:if(e=F[w++],e==114)return bf(F[w++]&63);{let t=Xe[e];if(t)return t.read?(w++,t.read(ke())):t.noBuffer?(w++,t()):t(F.subarray(w,++w));throw new Error("Unknown extension "+e)}case 213:return e=F[w],e==114?(w++,bf(F[w++]&63,F[w++])):zn(2);case 214:return zn(4);case 215:return zn(8);case 216:return zn(16);case 217:return e=F[w++],Ft>=w?Rn.slice(w-dt,(w+=e)-dt):Py(e);case 218:return e=re.getUint16(w),w+=2,Ft>=w?Rn.slice(w-dt,(w+=e)-dt):Oy(e);case 219:return e=re.getUint32(w),w+=4,Ft>=w?Rn.slice(w-dt,(w+=e)-dt):My(e);case 220:return e=re.getUint16(w),w+=2,pf(e);case 221:return e=re.getUint32(w),w+=4,pf(e);case 222:return e=re.getUint16(w),w+=2,mf(e);case 223:return e=re.getUint32(w),w+=4,mf(e);default:if(n>=224)return n-256;if(n===void 0){let t=new Error("Unexpected end of MessagePack data");throw t.incomplete=!0,t}throw new Error("Unknown MessagePack token "+n)}}}var Iy=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Ac(n,e){function t(){if(t.count++>df){let s;try{s=n.read=new Function("r","return function(){return "+(de.freezeData?"Object.freeze":"")+"({"+n.map(i=>i==="__proto__"?"__proto_:r()":Iy.test(i)?i+":r()":"["+JSON.stringify(i)+"]:r()").join(",")+"})}")(ke)}catch{return df=1/0,t()}return n.read0=s,n.highByte===0&&(n.read=hf(e,n.read)),s()}let r={};for(let s=0,i=n.length;s<i;s++){let o=n[s];o==="__proto__"&&(o="__proto_"),r[o]=ke()}return de.freezeData?Object.freeze(r):r}return t.count=0,n.read0=t,n.highByte===0?hf(e,t):t}var hf=(n,e)=>function(){let t=F[w++];if(t===0)return e();let r=n<32?-(n+(t<<5)):n+(t<<5),s=se[r]||Ef()[r];if(!s)throw new Error("Record id is not defined for "+r);return s.read||(s.read=Ac(s,n)),s.read()};function Ef(){let n=Tf(()=>(F=null,de.getStructures()));return se=de._mergeStructures(n,se)}var kc=Ds,Py=Ds,Oy=Ds,My=Ds;function Ds(n){let e;if(n<16&&(e=Cc(n)))return e;if(n>64&&xc)return xc.decode(F.subarray(w,w+=n));let t=w+n,r=[];for(e="";w<t;){let s=F[w++];if((s&128)===0)r.push(s);else if((s&224)===192){let i=F[w++]&63,o=(s&31)<<6|i;o<128?r.push(65533):r.push(o)}else if((s&240)===224){let i=F[w++]&63,o=F[w++]&63,a=(s&31)<<12|i<<6|o;a<2048||a>=55296&&a<=57343?r.push(65533):r.push(a)}else if((s&248)===240){let i=F[w++]&63,o=F[w++]&63,a=F[w++]&63,c=(s&7)<<18|i<<12|o<<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+=Be.apply(String,r),r.length=0)}return r.length>0&&(e+=Be.apply(String,r)),e}function pf(n){let e=new Array(n);for(let t=0;t<n;t++)e[t]=ke();return de.freezeData?Object.freeze(e):e}function mf(n){if(de.mapsAsObjects){let e={};for(let t=0;t<n;t++){let r=xf();r==="__proto__"&&(r="__proto_"),e[r]=ke()}return e}else{let e=new Map;for(let t=0;t<n;t++)e.set(ke(),ke());return e}}var Be=String.fromCharCode;function Rf(n){let e=w,t=new Array(n);for(let r=0;r<n;r++){let s=F[w++];if((s&128)>0){w=e;return}t[r]=s}return Be.apply(String,t)}function Cc(n){if(n<4)if(n<2){if(n===0)return"";{let e=F[w++];if((e&128)>1){w-=1;return}return Be(e)}}else{let e=F[w++],t=F[w++];if((e&128)>0||(t&128)>0){w-=2;return}if(n<3)return Be(e,t);let r=F[w++];if((r&128)>0){w-=3;return}return Be(e,t,r)}else{let e=F[w++],t=F[w++],r=F[w++],s=F[w++];if((e&128)>0||(t&128)>0||(r&128)>0||(s&128)>0){w-=4;return}if(n<6){if(n===4)return Be(e,t,r,s);{let i=F[w++];if((i&128)>0){w-=5;return}return Be(e,t,r,s,i)}}else if(n<8){let i=F[w++],o=F[w++];if((i&128)>0||(o&128)>0){w-=6;return}if(n<7)return Be(e,t,r,s,i,o);let a=F[w++];if((a&128)>0){w-=7;return}return Be(e,t,r,s,i,o,a)}else{let i=F[w++],o=F[w++],a=F[w++],c=F[w++];if((i&128)>0||(o&128)>0||(a&128)>0||(c&128)>0){w-=8;return}if(n<10){if(n===8)return Be(e,t,r,s,i,o,a,c);{let u=F[w++];if((u&128)>0){w-=9;return}return Be(e,t,r,s,i,o,a,c,u)}}else if(n<12){let u=F[w++],d=F[w++];if((u&128)>0||(d&128)>0){w-=10;return}if(n<11)return Be(e,t,r,s,i,o,a,c,u,d);let h=F[w++];if((h&128)>0){w-=11;return}return Be(e,t,r,s,i,o,a,c,u,d,h)}else{let u=F[w++],d=F[w++],h=F[w++],m=F[w++];if((u&128)>0||(d&128)>0||(h&128)>0||(m&128)>0){w-=12;return}if(n<14){if(n===12)return Be(e,t,r,s,i,o,a,c,u,d,h,m);{let g=F[w++];if((g&128)>0){w-=13;return}return Be(e,t,r,s,i,o,a,c,u,d,h,m,g)}}else{let g=F[w++],p=F[w++];if((g&128)>0||(p&128)>0){w-=14;return}if(n<15)return Be(e,t,r,s,i,o,a,c,u,d,h,m,g,p);let y=F[w++];if((y&128)>0){w-=15;return}return Be(e,t,r,s,i,o,a,c,u,d,h,m,g,p,y)}}}}}function gf(){let n=F[w++],e;if(n<192)e=n-160;else switch(n){case 217:e=F[w++];break;case 218:e=re.getUint16(w),w+=2;break;case 219:e=re.getUint32(w),w+=4;break;default:throw new Error("Expected string")}return Ds(e)}function Rc(n){return de.copyBuffers?Uint8Array.prototype.slice.call(F,w,w+=n):F.subarray(w,w+=n)}function zn(n){let e=F[w++];if(Xe[e]){let t;return Xe[e](F.subarray(w,t=w+=n),r=>{w=r;try{return ke()}finally{w=t}})}else throw new Error("Unknown extension type "+e)}var yf=new Array(4096);function xf(){let n=F[w++];if(n>=160&&n<192){if(n=n-160,Ft>=w)return Rn.slice(w-dt,(w+=n)-dt);if(!(Ft==0&&ft<180))return kc(n)}else return w--,Sf(ke());let e=(n<<5^(n>1?re.getUint16(w):n>0?F[w]:0))&4095,t=yf[e],r=w,s=w+n-3,i,o=0;if(t&&t.bytes==n){for(;r<s;){if(i=re.getUint32(r),i!=t[o++]){r=1879048192;break}r+=4}for(s+=3;r<s;)if(i=F[r++],i!=t[o++]){r=1879048192;break}if(r===s)return w=r,t.string;s-=3,r=w}for(t=[],yf[e]=t,t.bytes=n;r<s;)i=re.getUint32(r),t.push(i),r+=4;for(s+=3;r<s;)i=F[r++],t.push(i);let a=n<16?Cc(n):Rf(n);return a!=null?t.string=a:t.string=kc(n)}function Sf(n){if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean"||typeof n=="bigint")return n.toString();if(n==null)return n+"";if(de.allowArraysInMapKeys&&Array.isArray(n)&&n.flat().every(e=>["string","number","boolean","bigint"].includes(typeof e)))return n.flat().toString();throw new Error(`Invalid property type for record: ${typeof n}`)}var bf=(n,e)=>{let t=ke().map(Sf),r=n;e!==void 0&&(n=n<32?-((e<<5)+n):(e<<5)+n,t.highByte=e);let s=se[n];return s&&(s.isShared||xn)&&((se.restoreStructures||(se.restoreStructures=[]))[n]=s),se[n]=t,t.read=Ac(t,r),(t.read0||t.read)()};Xe[0]=()=>{};Xe[0].noBuffer=!0;Xe[66]=n=>{let e=n.byteLength%8||8,t=BigInt(n[0]&128?n[0]-256:n[0]);for(let r=1;r<e;r++)t<<=BigInt(8),t+=BigInt(n[r]);if(n.byteLength!==e){let r=new DataView(n.buffer,n.byteOffset,n.byteLength),s=(i,o)=>{let a=o-i;if(a<=40){let h=r.getBigUint64(i);for(let m=i+8;m<o;m+=8)h<<=BigInt(64),h|=r.getBigUint64(m);return h}let c=i+(a>>4<<3),u=s(i,c),d=s(c,o);return u<<BigInt((o-c)*8)|d};t=t<<BigInt((r.byteLength-e)*8)|s(e,r.byteLength)}return t};var wf={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError=="function"?AggregateError:null};Xe[101]=()=>{let n=ke();if(!wf[n[0]]){let e=Error(n[1],{cause:n[2]});return e.name=n[0],e}return wf[n[0]](n[1],{cause:n[2]})};Xe[105]=n=>{if(de.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=re.getUint32(w-4);rn||(rn=new Map);let t=F[w],r;t>=144&&t<160||t==220||t==221?r=[]:t>=128&&t<144||t==222||t==223?r=new Map:(t>=199&&t<=201||t>=212&&t<=216)&&F[w+1]===115?r=new Set:r={};let s={target:r};rn.set(e,s);let i=ke();if(s.used)Object.assign(r,i);else return s.target=i;if(r instanceof Map)for(let[o,a]of i.entries())r.set(o,a);if(r instanceof Set)for(let o of Array.from(i))r.add(o);return r};Xe[112]=n=>{if(de.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=re.getUint32(w-4),t=rn.get(e);return t.used=!0,t.target};Xe[115]=()=>new Set(ke());var Ic=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(n=>n+"Array"),Dy=typeof globalThis=="object"?globalThis:window;Xe[116]=n=>{let e=n[0],t=Uint8Array.prototype.slice.call(n,1).buffer,r=Ic[e];if(!r){if(e===16)return t;if(e===17)return new DataView(t);throw new Error("Could not find typed array for code "+e)}return new Dy[r](t)};Xe[120]=()=>{let n=ke();return new RegExp(n[0],n[1])};var Ny=[];Xe[98]=n=>{let e=(n[0]<<24)+(n[1]<<16)+(n[2]<<8)+n[3],t=w;return w+=e-n.length,Le=Ny,Le=[gf(),gf()],Le.position0=0,Le.position1=0,Le.postBundlePosition=w,w=t,ke()};Xe[255]=n=>n.length==4?new Date((n[0]*16777216+(n[1]<<16)+(n[2]<<8)+n[3])*1e3):n.length==8?new Date(((n[0]<<22)+(n[1]<<14)+(n[2]<<6)+(n[3]>>2))/1e6+((n[3]&3)*4294967296+n[4]*16777216+(n[5]<<16)+(n[6]<<8)+n[7])*1e3):n.length==12?new Date(((n[0]<<24)+(n[1]<<16)+(n[2]<<8)+n[3])/1e6+((n[4]&128?-281474976710656:0)+n[6]*1099511627776+n[7]*4294967296+n[8]*16777216+(n[9]<<16)+(n[10]<<8)+n[11])*1e3):new Date("invalid");function Tf(n){de&&de._onSaveState&&de._onSaveState();let e=ft,t=w,r=Tc,s=dt,i=Ft,o=Rn,a=Sc,c=rn,u=Le,d=new Uint8Array(F.slice(0,ft)),h=se,m=se.slice(0,se.length),g=de,p=xn,y=n();return ft=e,w=t,Tc=r,dt=s,Ft=i,Rn=o,Sc=a,rn=c,Le=u,F=d,xn=p,se=h,se.splice(0,se.length,...m),de=g,re=new DataView(F.buffer,F.byteOffset,F.byteLength),y}function mo(){F=null,rn=null,se=null}var go=new Array(147);for(let n=0;n<256;n++)go[n]=+("1e"+Math.floor(45.15-n*.30103));var yo=new Sn({useRecords:!1}),bo=yo.unpack,By=yo.unpackMultiple,Ly=yo.unpack,wo={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},Fy=new Float32Array(1),_E=new Uint8Array(Fy.buffer,0,4);Sn.SUPPORTS_STRUCT_HOOKS=!0;var Eo;try{Eo=new TextEncoder}catch{}var Mc,Dc,vr=typeof Buffer<"u",_o=vr?function(n){return Buffer.allocUnsafeSlow(n)}:Uint8Array,Cf=vr?Buffer:Uint8Array,kf=vr?4294967296:2144337920,T,Ns,me,E=0,Ve,xe=null,Uy=21760,$y=/[\u0080-\uFFFF]/,kr=Symbol("record-id"),Tn=class extends Sn{constructor(e){super(e),this.offset=0;let t,r,s,i,o,a=Cf.prototype.utf8Write?function(S,L){return T.utf8Write(S,L,T.byteLength-L)}:Eo&&Eo.encodeInto?function(S,L){return Eo.encodeInto(S,T.subarray(L)).written}:!1,c=this;e||(e={});let u=e&&e.sequential,d=e.structures||e.saveStructures,h=e.maxSharedStructures;if(h==null&&(h=d?32:0),h>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let m=e.maxOwnStructures;m==null&&(m=d?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let g=h>32||m+h>64,p=h+64,y=h+m+64;if(y>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let x=[],k=0,P=0;this.pack=this.encode=function(S,L){if(T||(T=new _o(8192),me=T.dataView||(T.dataView=new DataView(T.buffer,0,8192)),E=0),Ve=T.length-10,Ve-E<2048?(T=new _o(T.length),me=T.dataView||(T.dataView=new DataView(T.buffer,0,T.length)),Ve=T.length-10,E=0):E=E+7&2147483640,r=E,L&Ar&&(E+=L&255),o=c.structuredClone?new Map:null,c.bundleStrings&&typeof S!="string"?(xe=[],xe.size=1/0):xe=null,i=c.structures,i){i.uninitialized&&(i=c._mergeStructures(c.getStructures()));let D=i.sharedLength||0;if(D>h)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+i.sharedLength);if(!i.transitions){i.transitions=Object.create(null);for(let M=0;M<D;M++){let z=i[M];if(!z)continue;let W,q=i.transitions;for(let ae=0,Y=z.length;ae<Y;ae++){let Ze=z[ae];W=q[Ze],W||(W=q[Ze]=Object.create(null)),q=W}q[kr]=M+64}this.lastNamedStructuresLength=D}u||(i.nextId=D+64)}s&&(s=!1);let B;try{c._writeStruct&&S&&typeof S=="object"?S.constructor===Object?Z(S):S.constructor!==Map&&!Array.isArray(S)&&!Dc.some(M=>S instanceof M)?Z(S.toJSON?S.toJSON():S):C(S):C(S);let D=xe;if(xe&&Af(r,C,0),o&&o.idsToInsert){let M=o.idsToInsert.sort((ae,Y)=>ae.offset>Y.offset?1:-1),z=M.length,W=-1;for(;D&&z>0;){let ae=M[--z].offset+r;ae<D.stringsPosition+r&&W===-1&&(W=0),ae>D.position+r?W>=0&&(W+=6):(W>=0&&(me.setUint32(D.position+r,me.getUint32(D.position+r)+W),W=-1),D=D.previous,z++)}W>=0&&D&&me.setUint32(D.position+r,me.getUint32(D.position+r)+W),E+=M.length*6,E>Ve&&ee(E),c.offset=E;let q=Vy(T.subarray(r,E),M);return o=null,q}return c.offset=E,L&Pf?(T.start=r,T.end=E,T):T.subarray(r,E)}catch(D){throw B=D,D}finally{if(i&&(U(),s&&c.saveStructures)){let D=i.sharedLength||0,M=T.subarray(r,E),z=(c._prepareStructures||jy)(i,c);if(!B)return c.saveStructures(z,z.isCompatible)===!1?(i.uninitialized=!0,c.pack(S,L)):(c.lastNamedStructuresLength=D,T.length>1073741824&&(T=null),M)}T.length>1073741824&&(T=null),L&Of&&(E=r)}};let U=()=>{P<10&&P++;let S=i.sharedLength||0;if(i.length>S&&!u&&(i.length=S),k>1e4)i.transitions=null,P=0,k=0,x.length>0&&(x=[]);else if(x.length>0&&!u){for(let L=0,B=x.length;L<B;L++)x[L][kr]=0;x=[]}},N=S=>{var L=S.length;L<16?T[E++]=144|L:L<65536?(T[E++]=220,T[E++]=L>>8,T[E++]=L&255):(T[E++]=221,me.setUint32(E,L),E+=4);for(let B=0;B<L;B++)C(S[B])},C=S=>{E>Ve&&(T=ee(E));var L=typeof S,B;if(L==="string"){let D=S.length;if(xe&&D>=4&&D<4096){if((xe.size+=D)>Uy){let q,ae=(xe[0]?xe[0].length*3+xe[1].length:0)+10;E+ae>Ve&&(T=ee(E+ae));let Y;xe.position?(Y=xe,T[E]=200,E+=3,T[E++]=98,q=E-r,E+=4,Af(r,C,0),me.setUint16(q+r-3,E-r-q)):(T[E++]=214,T[E++]=98,q=E-r,E+=4),xe=["",""],xe.previous=Y,xe.size=0,xe.position=q}let W=$y.test(S);xe[W?0:1]+=S,T[E++]=193,C(W?-D:D);return}let M;D<32?M=1:D<256?M=2:D<65536?M=3:M=5;let z=D*3;if(E+z>Ve&&(T=ee(E+z)),D<64||!a){let W,q,ae,Y=E+M;for(W=0;W<D;W++)q=S.charCodeAt(W),q<128?T[Y++]=q:q<2048?(T[Y++]=q>>6|192,T[Y++]=q&63|128):(q&64512)===55296&&((ae=S.charCodeAt(W+1))&64512)===56320?(q=65536+((q&1023)<<10)+(ae&1023),W++,T[Y++]=q>>18|240,T[Y++]=q>>12&63|128,T[Y++]=q>>6&63|128,T[Y++]=q&63|128):(T[Y++]=q>>12|224,T[Y++]=q>>6&63|128,T[Y++]=q&63|128);B=Y-E-M}else B=a(S,E+M);B<32?T[E++]=160|B:B<256?(M<2&&T.copyWithin(E+2,E+1,E+1+B),T[E++]=217,T[E++]=B):B<65536?(M<3&&T.copyWithin(E+3,E+2,E+2+B),T[E++]=218,T[E++]=B>>8,T[E++]=B&255):(M<5&&T.copyWithin(E+5,E+3,E+3+B),T[E++]=219,me.setUint32(E,B),E+=4),E+=B}else if(L==="number")if(S>>>0===S)S<32||S<128&&this.useRecords===!1||S<64&&!this._writeStruct?T[E++]=S:S<256?(T[E++]=204,T[E++]=S):S<65536?(T[E++]=205,T[E++]=S>>8,T[E++]=S&255):(T[E++]=206,me.setUint32(E,S),E+=4);else if(S>>0===S)S>=-32?T[E++]=256+S:S>=-128?(T[E++]=208,T[E++]=S+256):S>=-32768?(T[E++]=209,me.setInt16(E,S),E+=2):(T[E++]=210,me.setInt32(E,S),E+=4);else{let D;if((D=this.useFloat32)>0&&S<4294967296&&S>=-2147483648){T[E++]=202,me.setFloat32(E,S);let M;if(D<4||(M=S*go[(T[E]&127)<<1|T[E+1]>>7])>>0===M){E+=4;return}else E--}T[E++]=203,me.setFloat64(E,S),E+=8}else if(L==="object"||L==="function")if(!S)T[E++]=192;else{if(o){let M=o.get(S);if(M){if(!M.id){let z=o.idsToInsert||(o.idsToInsert=[]);M.id=z.push(M)}T[E++]=214,T[E++]=112,me.setUint32(E,M.id),E+=4;return}else o.set(S,{offset:E-r})}let D=S.constructor;if(D===Object)V(S);else if(D===Array)N(S);else if(D===Map)if(this.mapAsEmptyObject)T[E++]=128;else{B=S.size,B<16?T[E++]=128|B:B<65536?(T[E++]=222,T[E++]=B>>8,T[E++]=B&255):(T[E++]=223,me.setUint32(E,B),E+=4);for(let[M,z]of S)C(M),C(z)}else{for(let M=0,z=Mc.length;M<z;M++){let W=Dc[M];if(S instanceof W){let q=Mc[M];if(q.write){q.type&&(T[E++]=212,T[E++]=q.type,T[E++]=0);let ln=q.write.call(this,S);ln===S?Array.isArray(S)?N(S):V(S):C(ln);return}let ae=T,Y=me,Ze=E;T=null;let pt;try{pt=q.pack.call(this,S,ln=>(T=ae,ae=null,E+=ln,E>Ve&&ee(E),{target:T,targetView:me,position:E-ln}),C)}finally{ae&&(T=ae,me=Y,E=Ze,Ve=T.length-10)}pt&&(pt.length+E>Ve&&ee(pt.length+E),E=vf(pt,T,E,q.type));return}}if(Array.isArray(S))N(S);else{if(S.toJSON){let M=S.toJSON();if(M!==S)return C(M)}if(L==="function")return C(this.writeFunction&&this.writeFunction(S));V(S)}}}else if(L==="boolean")T[E++]=S?195:194;else if(L==="bigint"){if(S<9223372036854776e3&&S>=-9223372036854776e3)T[E++]=211,me.setBigInt64(E,S);else if(S<18446744073709552e3&&S>0)T[E++]=207,me.setBigUint64(E,S);else if(this.largeBigIntToFloat)T[E++]=203,me.setFloat64(E,Number(S));else{if(this.largeBigIntToString)return C(S.toString());if(this.useBigIntExtension||this.moreTypes){let D=S<0?BigInt(-1):BigInt(0),M;if(S>>BigInt(65536)===D){let z=BigInt(18446744073709552e3)-BigInt(1),W=[];for(;W.push(S&z),S>>BigInt(63)!==D;)S>>=BigInt(64);M=new Uint8Array(new BigUint64Array(W).buffer),M.reverse()}else{let z=S<0,W=(z?~S:S).toString(16);if(W.length%2?W="0"+W:parseInt(W.charAt(0),16)>=8&&(W="00"+W),vr)M=Buffer.from(W,"hex");else{M=new Uint8Array(W.length/2);for(let q=0;q<M.length;q++)M[q]=parseInt(W.slice(q*2,q*2+2),16)}if(z)for(let q=0;q<M.length;q++)M[q]=~M[q]}M.length+E>Ve&&ee(M.length+E),E=vf(M,T,E,66);return}else throw new RangeError(S+" 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")}E+=8}else if(L==="undefined")this.encodeUndefinedAsNil?T[E++]=192:(T[E++]=212,T[E++]=0,T[E++]=0);else throw new Error("Unknown type: "+L)},O=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?S=>{let L;if(this.skipValues){L=[];for(let M in S)(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(M))&&!this.skipValues.includes(S[M])&&L.push(M)}else L=Object.keys(S);let B=L.length;B<16?T[E++]=128|B:B<65536?(T[E++]=222,T[E++]=B>>8,T[E++]=B&255):(T[E++]=223,me.setUint32(E,B),E+=4);let D;if(this.coercibleKeyAsNumber)for(let M=0;M<B;M++){D=L[M];let z=Number(D);C(isNaN(z)?D:z),C(S[D])}else for(let M=0;M<B;M++)C(D=L[M]),C(S[D])}:S=>{T[E++]=222;let L=E-r;E+=2;let B=0;for(let D in S)(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(D))&&(C(D),C(S[D]),B++);if(B>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');T[L+++r]=B>>8,T[L+r]=B&255},A=this.useRecords===!1?O:e.progressiveRecords&&!g?S=>{let L,B=i.transitions||(i.transitions=Object.create(null)),D=E++-r,M;for(let z in S)if(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(z)){if(L=B[z],L)B=L;else{let W=Object.keys(S),q=B;B=i.transitions;let ae=0;for(let Y=0,Ze=W.length;Y<Ze;Y++){let pt=W[Y];L=B[pt],L||(L=B[pt]=Object.create(null),ae++),B=L}D+r+1==E?(E--,ve(B,W,ae)):Pe(B,W,D,ae),M=!0,B=q[z]}C(S[z])}if(!M){let z=B[kr];z?T[D+r]=z:Pe(B,Object.keys(S),D,0)}}:S=>{let L,B=i.transitions||(i.transitions=Object.create(null)),D=0;for(let z in S)(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(z))&&(L=B[z],L||(L=B[z]=Object.create(null),D++),B=L);let M=B[kr];M?M>=96&&g?(T[E++]=((M-=96)&31)+96,T[E++]=M>>5):T[E++]=M:ve(B,B.__keys__||Object.keys(S),D);for(let z in S)(typeof S.hasOwnProperty!="function"||S.hasOwnProperty(z))&&C(S[z])},I=typeof this.useRecords=="function"&&this.useRecords,V=I?S=>{I(S)?A(S):O(S)}:A,Z=S=>{let L=c._writeStruct(S,T,r,E,i,ee,(B,D,M)=>{if(M)return s=!0;E=D;let z=T;return C(B),U(),z!==T?{position:E,targetView:me,target:T}:E});if(L===0)return V(S);E=L},ee=S=>{let L;if(S>16777216){if(S-r>kf)throw new Error("Packed buffer would be larger than maximum buffer size");L=Math.min(kf,Math.round(Math.max((S-r)*(S>67108864?1.25:2),4194304)/4096)*4096)}else L=(Math.max(S-r<<2,T.length-1)>>12)+1<<12;let B=new _o(L);return me=B.dataView||(B.dataView=new DataView(B.buffer,0,L)),S=Math.min(S,T.length),T.copy?T.copy(B,0,r,S):B.set(T.slice(r,S)),E-=r,r=0,Ve=B.length-10,T=B},ve=(S,L,B)=>{let D=i.nextId;D||(D=64),D<p&&this.shouldShareStructure&&!this.shouldShareStructure(L)?(D=i.nextOwnId,D<y||(D=p),i.nextOwnId=D+1):(D>=y&&(D=p),i.nextId=D+1);let M=L.highByte=D>=96&&g?D-96>>5:-1;S[kr]=D,S.__keys__=L,i[D-64]=L,D<p?(L.isShared=!0,i.sharedLength=D-63,s=!0,M>=0?(T[E++]=(D&31)+96,T[E++]=M):T[E++]=D):(M>=0?(T[E++]=213,T[E++]=114,T[E++]=(D&31)+96,T[E++]=M):(T[E++]=212,T[E++]=114,T[E++]=D),B&&(k+=P*B),x.length>=m&&(x.shift()[kr]=0),x.push(S),C(L))},Pe=(S,L,B,D)=>{let M=T,z=E,W=Ve,q=r;T=Ns,E=0,r=0,T||(Ns=T=new _o(8192)),Ve=T.length-10,ve(S,L,D),Ns=T;let ae=E;if(T=M,E=z,Ve=W,r=q,ae>1){let Y=E+ae-1;Y>Ve&&ee(Y);let Ze=B+r;T.copyWithin(Ze+ae,Ze+1,E),T.set(Ns.slice(0,ae),Ze),E=Y}else T[B+r]=Ns[0]}}useBuffer(e){T=e,T.dataView||(T.dataView=new DataView(T.buffer,T.byteOffset,T.byteLength)),me=T.dataView,E=0}set position(e){E=e}get position(){return E}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}};Dc=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Ms];Mc=[{pack(n,e,t){let r=n.getTime()/1e3;if((this.useTimestamp32||n.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:s,targetView:i,position:o}=e(6);s[o++]=214,s[o++]=255,i.setUint32(o,r)}else if(r>0&&r<4294967296){let{target:s,targetView:i,position:o}=e(10);s[o++]=215,s[o++]=255,i.setUint32(o,n.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),i.setUint32(o+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return e(0),t(this.onInvalidDate());let{target:s,targetView:i,position:o}=e(3);s[o++]=212,s[o++]=255,s[o++]=255}else{let{target:s,targetView:i,position:o}=e(15);s[o++]=199,s[o++]=12,s[o++]=255,i.setUint32(o,n.getMilliseconds()*1e6),i.setBigInt64(o+4,BigInt(Math.floor(r)))}}},{pack(n,e,t){if(this.setAsEmptyObject)return e(0),t({});let r=Array.from(n),{target:s,position:i}=e(this.moreTypes?3:0);this.moreTypes&&(s[i++]=212,s[i++]=115,s[i++]=0),t(r)}},{pack(n,e,t){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=101,r[s++]=0),t([n.name,n.message,n.cause])}},{pack(n,e,t){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=120,r[s++]=0),t([n.source,n.flags])}},{pack(n,e){this.moreTypes?Pc(n,16,e):Oc(vr?Buffer.from(n):new Uint8Array(n),e)}},{pack(n,e){let t=n.constructor;t!==Cf&&this.moreTypes?Pc(n,Ic.indexOf(t.name),e):Oc(n,e)}},{pack(n,e){this.moreTypes?Pc(n,17,e):Oc(vr?Buffer.from(n):new Uint8Array(n),e)}},{pack(n,e){let{target:t,position:r}=e(1);t[r]=193}}];function Pc(n,e,t,r){let s=n.byteLength;if(s+1<256){var{target:i,position:o}=t(4+s);i[o++]=199,i[o++]=s+1}else if(s+1<65536){var{target:i,position:o}=t(5+s);i[o++]=200,i[o++]=s+1>>8,i[o++]=s+1&255}else{var{target:i,position:o,targetView:a}=t(7+s);i[o++]=201,a.setUint32(o,s+1),o+=4}i[o++]=116,i[o++]=e,n.buffer||(n=new Uint8Array(n)),i.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength),o)}function Oc(n,e){let t=n.byteLength;var r,s;if(t<256){var{target:r,position:s}=e(t+2);r[s++]=196,r[s++]=t}else if(t<65536){var{target:r,position:s}=e(t+3);r[s++]=197,r[s++]=t>>8,r[s++]=t&255}else{var{target:r,position:s,targetView:i}=e(t+5);r[s++]=198,i.setUint32(s,t),s+=4}r.set(n,s)}function vf(n,e,t,r){let s=n.length;switch(s){case 1:e[t++]=212;break;case 2:e[t++]=213;break;case 4:e[t++]=214;break;case 8:e[t++]=215;break;case 16:e[t++]=216;break;default:s<256?(e[t++]=199,e[t++]=s):s<65536?(e[t++]=200,e[t++]=s>>8,e[t++]=s&255):(e[t++]=201,e[t++]=s>>24,e[t++]=s>>16&255,e[t++]=s>>8&255,e[t++]=s&255)}return e[t++]=r,e.set(n,t),t+=s,t}function Vy(n,e){let t,r=e.length*6,s=n.length-r;for(;t=e.pop();){let i=t.offset,o=t.id;n.copyWithin(i+r,i,s),r-=6;let a=i+r;n[a++]=214,n[a++]=105,n[a++]=o>>24,n[a++]=o>>16&255,n[a++]=o>>8&255,n[a++]=o&255,s=i}return n}function Af(n,e,t){if(xe.length>0){me.setUint32(xe.position+n,E+t-xe.position-n),xe.stringsPosition=E-n;let r=xe;xe=null,e(r[0]),e(r[1])}}function jy(n,e){return n.isCompatible=t=>{let r=!t||(e.lastNamedStructuresLength||0)===t.length;return r||e._mergeStructures(t),r},n}Tn.SUPPORTS_STRUCT_HOOKS=!0;var If=new Tn({useRecords:!1}),qy=If.pack,Gy=If.pack;var{NEVER:Hy,ALWAYS:zy,DECIMAL_ROUND:Wy,DECIMAL_FIT:Jy}=wo,Pf=512,Of=1024,Ar=2048;He();Yt();var Ky=9,Ro=class{constructor(){l(this,"pending",new Uint8Array(0))}push(e){if(!e||e.byteLength===0)return[];let t=this.pending.byteLength===0?e:Yy(this.pending,e),r=[],s=0;for(;s<t.byteLength;){let i={offset:s},o;try{o=te.number(t,i)}catch(c){if(t.byteLength-s<=Ky)break;throw c}let a=i.offset+o;if(a>t.byteLength)break;r.push(t.subarray(i.offset,a)),s=a}return this.pending=s<t.byteLength?t.slice(s):new Uint8Array(0),r}};function Yy(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}var Bs=class{constructor(e){l(this,"wt");l(this,"url");l(this,"isOpen",!1);l(this,"events");l(this,"reader");l(this,"writer");l(this,"unreliableReader");l(this,"unreliableWriter");l(this,"lengthPrefixBuffer",new Uint8Array(9));l(this,"reliableReassembler",new Ro);l(this,"unreliableReassembler",new Ro);this.events=e}connect(e,t={}){this.url=e;let r=t.fingerprint&&{serverCertificateHashes:[{algorithm:"sha-256",value:new Uint8Array(t.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 i=this.wt.datagrams;this.unreliableWriter=(i.createWritable?i.createWritable():i.writable).getWriter(),this.wt.incomingBidirectionalStreams.getReader().read().then(a=>{this.reader=a.value.readable.getReader(),this.writer=a.value.writable.getWriter(),this.sendSeatReservation(t.roomId,t.sessionId,t.reconnectionToken,t.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 t=e instanceof Uint8Array?e:new Uint8Array(e),r=Q.number(this.lengthPrefixBuffer,t.length,{offset:0}),s=new Uint8Array(r+t.length);return s.set(this.lengthPrefixBuffer.subarray(0,r),0),s.set(t,r),s}close(e,t){this.isOpen=!1;try{let r=this.wt?.close({closeCode:e,reason:t});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,t,r){for(;this.isOpen;){let s;try{s=await e.read()}catch(i){await this.onChannelFailure(r,i);return}if(s.done||!s.value)return;for(let i of t.push(s.value))this.events.onmessage({data:i})}}async onChannelFailure(e,t){await new Promise(r=>setTimeout(r,0)),this.isOpen&&(console.error(`H3Transport: stopped reading the ${e} channel while the session was open`,t),this.close(Ne.ABNORMAL_CLOSURE,`h3 ${e} channel failed`))}sendSeatReservation(e,t,r,s){let i={offset:0},o=[];Q.string(o,e,i),Q.string(o,t,i),r&&Q.string(o,r,i),s&&Q.boolean(o,1,i),this.writer.write(new Uint8Array(o).buffer)}_close(){this.isOpen=!1}};var Bf=mp(Df(),1);Yt();var Nc=globalThis.WebSocket||Bf.default,Nf=!1,xo=class{constructor(e){l(this,"ws");l(this,"protocols");l(this,"events");this.events=e}send(e){this.ws.send(e)}sendUnreliable(e){Nf||(Nf=!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,t){try{this.ws=new Nc(e,{headers:t,protocols:this.protocols})}catch{this.ws=new Nc(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,t){e===Ne.MAY_TRY_RECONNECT&&this.events.onclose&&(this.ws.onclose=null,this.events.onclose({code:e,reason:t})),this.ws.close(e,t)}get isOpen(){return this.ws.readyState===Nc.OPEN}};Yt();var Ls=[],Bc=typeof addEventListener=="function"&&typeof removeEventListener=="function";Bc&&addEventListener("offline",()=>{console.warn(`@colyseus/sdk: \u{1F6D1} Network offline. Closing ${Ls.length} connection(s)`),Ls.forEach(n=>n())},!1);var Fs,Cr=class{constructor(e){l(this,"transport");l(this,"events",{});l(this,"url");l(this,"options");he(this,Fs,Bc?()=>this.close(Ne.MAY_TRY_RECONNECT):null);e==="h3"?this.transport=new Bs(this.events):this.transport=new xo(this.events)}connect(e,t){if(Bc){let r=this.events.onopen;this.events.onopen=i=>{Ls.push(H(this,Fs)),r?.(i)};let s=this.events.onclose;this.events.onclose=i=>{Ls.splice(Ls.indexOf(H(this,Fs)),1),s?.(i)}}this.url=e,this.options=t,this.transport.connect(e,t)}send(e){this.transport.send(e)}sendUnreliable(e){this.transport.sendUnreliable(e)}reconnect(e){if(this.transport instanceof Bs){this.transport.connect(this.url,{...this.options,...e});return}let t=new URL(this.url);for(let r in e)t.searchParams.set(r,e[r]);this.transport.connect(t.toString(),this.options)}close(e,t){this.transport.close(e,t)}get isOpen(){return this.transport.isOpen}};Fs=new WeakMap;var Lf={};function Lc(n,e){Lf[n]=e}function Fc(n){let e=Lf[n];if(!e)throw new Error("missing serializer: "+n);return e}var So=()=>({emit(n,...e){let t=this.events[n]||[];for(let r=0,s=t.length;r<s;r++)t[r](...e)},events:{},on(n,e){return this.events[n]?.push(e)||(this.events[n]=[e]),()=>{this.events[n]=this.events[n]?.filter(t=>e!==t)}}});var Ff=new WeakMap,Uc=class{constructor(){l(this,"handlers",[])}register(e,t=!1){return this.handlers.push(e),this}invoke(...e){let t=this.handlers;for(let r=0,s=t.length;r<s;r++)t[r].apply(this,e)}invokeAsync(...e){return Promise.all(this.handlers.map(t=>t.apply(this,e)))}remove(e){let t=this.handlers.indexOf(e);t===-1&&(t=this.handlers.findIndex(r=>Ff.get(r)===e)),t!==-1&&(this.handlers=this.handlers.filter((r,s)=>s!==t))}clear(){this.handlers=[]}};function Wn(){let n=new Uc;function e(t){return n.register(t,this===null)}return e.once=t=>{let r=function(...s){n.remove(r),t.apply(this,s)};Ff.set(r,t),n.register(r)},e.remove=t=>n.remove(t),e.invoke=(...t)=>n.invoke(...t),e.invokeAsync=(...t)=>n.invokeAsync(...t),e.clear=()=>n.clear(),e}He();function $c(n){try{return Ki(n.serializer.decoder)}catch{return}}var Ir=class{constructor(){l(this,"state");l(this,"decoder")}setState(e,t){this.decoder.root.refs.size>1&&typeof this.decoder.decodeResync=="function"?this.decoder.decodeResync(e,t):this.decoder.decode(e,t)}getState(){return this.state}patch(e,t){return this.decoder.decode(e,t)}teardown(){this.decoder.root.clearRefs()}handshake(e,t){this.state?(Tt.decode(e,t),this.decoder=new St(this.state)):(this.decoder=Tt.decode(e,t),this.state=this.decoder.state)}};fo();function Uf(){return{enabled:!0,retryCount:0,maxRetries:15,delay:100,minDelay:100,maxDelay:5e3,minUptime:5e3,backoff:Xy,maxEnqueuedMessages:10,enqueuedMessages:[],isReconnecting:!1}}var Xy=(n,e)=>Math.floor(Math.pow(2,n)*e);function To(n,e){n.reconnection.enqueuedMessages.push({data:e}),n.reconnection.enqueuedMessages.length>n.reconnection.maxEnqueuedMessages&&n.reconnection.enqueuedMessages.shift()}function $f(n,e){if(!e){let r=new Error("request rejected");return r.name="rejected",r.reason=n,r}let t=new Error(n?.message??"request failed");return n?.name&&(t.name=n.name),n?.code!==void 0&&(t.code=n.code),t}Es();var $s,Pr,Or,Ut,$t,Mr,Vt,Vf,jf,qf,Gf,ko=class ko{constructor(e,t){he(this,Vt);l(this,"roomId");l(this,"sessionId");l(this,"reconnectionToken");l(this,"name");l(this,"connection");l(this,"onStateChange",Wn());l(this,"onError",Wn());l(this,"onLeave",Wn());l(this,"onReconnect",Wn());l(this,"onDrop",Wn());l(this,"onJoin",Wn());l(this,"serializerId");l(this,"serializer");l(this,"reconnection",Uf());l(this,"joinedAtTime",0);l(this,"clock",Rr);l(this,"onMessageHandlers",So());l(this,"packr");l(this,"sharedBuffer");he(this,$s,0);he(this,Pr);he(this,Or,0);he(this,Ut,new Map);he(this,$t);he(this,Mr,0);if(this.name=e,this.packr=new Tn,this.sharedBuffer=new Uint8Array(8192),t){let r=new(Fc("schema"));this.serializer=r;let s=new t;r.state=s,r.decoder=new St(s)}this.onLeave(()=>{this.removeAllListeners(),this.destroy()})}connect(e,t,r){this.connection=new Cr(t.protocol),this.connection.events.onmessage=this.onMessageCallback.bind(this),this.connection.events.onclose=i=>{if(On(this,Vt,qf).call(this,"connection closed before a response was received."),this.joinedAtTime===0){console.warn?.(`Room connection was closed unexpectedly (${i.code}): ${i.reason}`),this.onError.invoke(i.code,i.reason);return}i.code===Ne.NO_STATUS_RECEIVED||i.code===Ne.ABNORMAL_CLOSURE||i.code===Ne.GOING_AWAY||i.code===Ne.MAY_TRY_RECONNECT?(this.onDrop.invoke(i.code,i.reason),this.handleReconnection(i.code,i.reason)):this.onLeave.invoke(i.code,i.reason)},this.connection.events.onerror=i=>{this.onError.invoke(i.code,i.reason)};let s=this.serializer?.getState()!==void 0;if(t.protocol==="h3"){let i=new URL(e);this.connection.connect(i.origin,{...t,skipHandshake:s})}else this.connection.connect(`${e}${s?"&skipHandshake=1":""}`,r)}leave(e=!0){return new Promise(t=>{this.onLeave(r=>t(r)),this.connection?e?(this.sharedBuffer[0]=_e.LEAVE_ROOM,this.connection.send(this.sharedBuffer.subarray(0,1))):this.connection.close():this.onLeave.invoke(Ne.CONSENTED)})}onMessage(e,t){return this.onMessageHandlers.on(this.getMessageHandlerKey(e),t)}ping(e){this.connection?.isOpen&&(pe(this,$s,$e()),pe(this,Pr,e),this.sharedBuffer[0]=_e.PING,this.connection.send(this.sharedBuffer.subarray(0,1)))}send(e,t,r){if(r!==void 0){this.request(e,t).then(a=>r(a,void 0),a=>r(void 0,a));return}let s={offset:1};this.sharedBuffer[0]=_e.ROOM_DATA,typeof e=="string"?Q.string(this.sharedBuffer,e,s):Q.number(this.sharedBuffer,e,s);let i=s.offset,o;t!==void 0?(o=this.packr.pack(t,Ar|i),o.set(this.sharedBuffer.subarray(0,i),0)):o=this.sharedBuffer.subarray(0,i),this.connection.isOpen?this.connection.send(o):To(this,new Uint8Array(o))}request(e,t,r){if(!this.connection.isOpen)return Promise.reject(new Error(`cannot send request "${e}": connection is not open.`));let s=r?.timeout??ko.defaultRequestTimeout;return new Promise((i,o)=>{let a,c=this.sendRequest(e,t,{mode:r?.mode},(u,d,h)=>{clearTimeout(a),u?i(d):o($f(d,h))},u=>{clearTimeout(a),o(new Error(u))});a=setTimeout(()=>{this.cancelRequest(c),o(new Error(`request "${e}" timed out after ${s}ms.`))},s)})}sendRequest(e,t,r,s,i){let o=On(this,Vt,Vf).call(this),a=On(this,Vt,jf).call(this,o,e,t);if(r.mode==="unreliable"){if(!this.connection.isOpen)return-1;this.connection.sendUnreliable(a)}else this.connection.isOpen?this.connection.send(a):To(this,new Uint8Array(a));return H(this,Ut).set(o,{onReply:s,onClose:i}),o}cancelRequest(e){H(this,Ut).delete(e)}sendUnreliable(e,t){if(!this.connection.isOpen)return;let r={offset:1};this.sharedBuffer[0]=_e.ROOM_DATA,typeof e=="string"?Q.string(this.sharedBuffer,e,r):Q.number(this.sharedBuffer,e,r);let s=r.offset,i;t!==void 0?(i=this.packr.pack(t,Ar|s),i.set(this.sharedBuffer.subarray(0,s),0)):i=this.sharedBuffer.subarray(0,s),this.connection.sendUnreliable(i)}sendBytes(e,t){let r={offset:1};this.sharedBuffer[0]=_e.ROOM_DATA_BYTES,typeof e=="string"?Q.string(this.sharedBuffer,e,r):Q.number(this.sharedBuffer,e,r);let s=r.offset;if(s+t.byteLength>this.sharedBuffer.byteLength){let i=new Uint8Array(s+t.byteLength);i.set(this.sharedBuffer.subarray(0,s)),this.sharedBuffer=i}this.sharedBuffer.set(t,s),this.connection.isOpen?this.connection.send(this.sharedBuffer.subarray(0,s+t.byteLength)):To(this,this.sharedBuffer.subarray(0,s+t.byteLength))}input(e){return(H(this,$t)??pe(this,$t,new Tr(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 Ir&&(this.serializer.decoder.root.callbacks={})}onMessageCallback(e){On(this,Vt,Gf).call(this,new Uint8Array(e.data))}dispatchMessage(e,t){let r=this.getMessageHandlerKey(e);this.onMessageHandlers.events[r]?this.onMessageHandlers.emit(r,t):this.onMessageHandlers.events["*"]?this.onMessageHandlers.emit("*",e,t):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,t){if(!this.reconnection.enabled){this.onLeave.invoke(e,t);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(Ne.ABNORMAL_CLOSURE,"Room uptime too short for reconnection.");return}this.reconnection.isReconnecting||(this.reconnection.retryCount=0,this.reconnection.isReconnecting=!0,H(this,$t)?.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(Ne.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)}};$s=new WeakMap,Pr=new WeakMap,Or=new WeakMap,Ut=new WeakMap,$t=new WeakMap,Mr=new WeakMap,Vt=new WeakSet,Vf=function(){let e=H(this,Or);return pe(this,Or,H(this,Or)+1>>>0),e},jf=function(e,t,r){let s={offset:1};this.sharedBuffer[0]=_e.ROOM_REQUEST,Q.number(this.sharedBuffer,e,s),typeof t=="string"?Q.string(this.sharedBuffer,t,s):Q.number(this.sharedBuffer,t,s);let i=s.offset;if(r!==void 0){let o=this.packr.pack(r,Ar|i);return o.set(this.sharedBuffer.subarray(0,i),0),o}return this.sharedBuffer.subarray(0,i)},qf=function(e){if(H(this,Ut).size!==0){for(let t of H(this,Ut).values())t.onClose?.(e);H(this,Ut).clear()}},Gf=function(e){var i;let t={offset:1},r=e[0],s=r&Ja;if(r&pr.TIMED){let o=te.uint32(e,t),a=te.uint32(e,t),c=H(this,$t)?H(this,$t).ackInput(a):-1;this.clock.sample(o,c)}if(s===_e.JOIN_ROOM){let o=te.utf8Read(e,t,e[t.offset++]);if(this.serializerId=te.utf8Read(e,t,e[t.offset++]),!this.serializer){let u=Fc(this.serializerId);this.serializer=new u}let a=te.number(e,t);if(a>0&&this.serializer.handshake){let u=t.offset+a;this.serializer.handshake(e.subarray(0,u),t),t.offset=u}for(;t.offset<e.byteLength;){let u=e[t.offset++],d=te.number(e,t),h=t.offset+d;u===Di.INPUT_REFLECTION?(H(this,$t)??pe(this,$t,new Tr(this))).applyReflection(e,t,h):u===Di.INPUT_OPTIONS&&(H(this,$t)??pe(this,$t,new Tr(this))).applyOptions(e,t),t.offset=h}let c=H(this,$t)?.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}:${o}`,this.sharedBuffer[0]=_e.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===_e.ERROR){let o=te.number(e,t),a=te.string(e,t);this.onError.invoke(o,a)}else if(s===_e.LEAVE_ROOM)this.leave();else if(s===_e.ROOM_STATE)pe(this,Mr,0),this.serializer.setState(e,t),this.onStateChange.invoke(this.serializer.getState());else if(s===_e.ROOM_STATE_PATCH){if(r&pr.UNRELIABLE){let o=te.uint16(e,t);if(o-H(this,Mr)<<16>>16<=0)return;pe(this,Mr,o)}this.serializer.patch(e,t),this.onStateChange.invoke(this.serializer.getState())}else if(s===_e.ROOM_DATA){let o=te.stringCheck(e,t)?te.string(e,t):te.number(e,t),a=e.byteLength>t.offset?bo(e,{start:t.offset}):void 0;this.dispatchMessage(o,a)}else if(s===_e.ROOM_DATA_BYTES){let o=te.stringCheck(e,t)?te.string(e,t):te.number(e,t);this.dispatchMessage(o,e.subarray(t.offset))}else if(s===_e.ROOM_RESPONSE){let o=te.number(e,t),a=e[t.offset++],c=e.byteLength>t.offset?bo(e,{start:t.offset}):void 0,u=H(this,Ut).get(o);u!==void 0&&(H(this,Ut).delete(o),u.onReply(a===Mi.OK,c,a===Mi.ERROR))}else s===_e.PING&&((i=H(this,Pr))==null||i.call(this,Math.round($e()-H(this,$s))),pe(this,Pr,void 0))},l(ko,"defaultRequestTimeout",1e4);var Us=ko;function Hf(n,e){return new Promise((t,r)=>{let s=new XMLHttpRequest,i=e?.method||"GET";s.open(i,n.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 o=new Headers,a=s.getAllResponseHeaders().trim();if(a)for(let u of a.split(/[\r\n]+/)){let d=u.indexOf(": ");d>0&&o.append(u.substring(0,d),u.substring(d+2))}let c=s.response??s.responseText;t(new Vc(c,{status:s.status,statusText:s.statusText,headers:o}))},s.onerror=()=>r(new TypeError("Network request failed")),s.ontimeout=()=>r(new TypeError("Network request timed out")),s.send(e?.body??null)})}var Vc=class{constructor(e,t){l(this,"status");l(this,"statusText");l(this,"headers");l(this,"ok");l(this,"body");this.body=e,this.status=t.status,this.statusText=t.statusText,this.headers=t.headers,this.ok=t.status>=200&&t.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 Qy(n){if(n===void 0)return!1;let e=typeof n;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(n)?!0:n.buffer?!1:n.constructor&&n.constructor.name==="Object"||typeof n.toJSON=="function"}function Zy(n,e){let{params:t,query:r}=e||{},[s,i]=n.split("?"),o=s;if(t)if(Array.isArray(t)){let u=o.split("/").filter(d=>d.startsWith(":"));for(let[d,h]of u.entries()){let m=t[d];o=o.replace(h,m)}}else for(let[u,d]of Object.entries(t))o=o.replace(`:${u}`,String(d));let a=new URLSearchParams(i);if(r)for(let[u,d]of Object.entries(r))d!=null&&a.set(u,String(d));let c=a.toString();return c=c.length>0?`?${c}`.replace(/\+/g,"%20"):"",`${o}${c}`}var vo=class{constructor(e,t,r){l(this,"authToken");l(this,"options");l(this,"sdk");l(this,"_fetchFn");l(this,"del",this.delete);this.sdk=e,this.options=t,this._fetchFn=r}get fetchFn(){return this._fetchFn||(this._fetchFn=typeof globalThis.fetch<"u"?globalThis.fetch.bind(globalThis):Hf),this._fetchFn}async request(e,t,r){return this.executeRequest(e,t,r)}get(e,t){return this.request("GET",e,t)}post(e,t){return this.request("POST",e,t)}delete(e,t){return this.request("DELETE",e,t)}patch(e,t){return this.request("PATCH",e,t)}put(e,t){return this.request("PUT",e,t)}async executeRequest(e,t,r){let s=this.options.body?{...this.options.body,...r?.body||{}}:r?.body,i=this.options.query?{...this.options.query,...r?.query||{}}:r?.query,o=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}`),Qy(s)&&typeof s=="object"&&s!==null){a.has("content-type")||a.set("content-type","application/json");for(let[g,p]of Object.entries(s))p instanceof Date&&(s[g]=p.toISOString());s=JSON.stringify(s)}let c={credentials:r?.credentials||"include",...this.options,...r,query:i,params:o,headers:a,body:s,method:e},u=Zy(this.sdk.getHttpEndpoint(t.toString()),c),d;try{d=await this.fetchFn(u,c)}catch(g){if(g.name==="AbortError")throw g;let p=new It(g.cause?.code||g.code,g.message);throw p.response=d,p.cause=g.cause,p}let h=d.headers.get("content-type"),m;if(h?.includes("json")?m=await d.json():h?.includes("text")?m=await d.text():m=await d.blob(),!d.ok)throw new It(d.status,m.message??m.error??d.statusText,{headers:d.headers,status:d.status,response:d,data:m});return{raw:d,data:m,headers:d.headers,status:d.status,statusText:d.statusText}}};var Jn;function qc(){if(!Jn)try{Jn=typeof cc<"u"&&cc.sys&&cc.sys.localStorage?cc.sys.localStorage:window.localStorage}catch{}return!Jn&&typeof globalThis.indexedDB<"u"&&(Jn=new jc),Jn||(Jn={cache:{},setItem:function(n,e){this.cache[n]=e},getItem:function(n){return this.cache[n]},removeItem:function(n){delete this.cache[n]}}),Jn}function zf(n,e){qc().setItem(n,e)}function Wf(n){qc().removeItem(n)}function Jf(n,e){let t=qc().getItem(n);typeof Promise>"u"||!(t instanceof Promise)?e(t):t.then(r=>e(r))}var jc=class{constructor(){l(this,"dbPromise",new Promise(e=>{let t=indexedDB.open("_colyseus_storage",1);t.onupgradeneeded=()=>t.result.createObjectStore("store"),t.onsuccess=()=>e(t.result)}))}async tx(e,t){let s=(await this.dbPromise).transaction("store",e).objectStore("store");return t(s)}setItem(e,t){return this.tx("readwrite",r=>r.put(t,e)).then()}async getItem(e){let t=await this.tx("readonly",r=>r.get(e));return new Promise(r=>{t.onsuccess=()=>r(t.result)})}removeItem(e){return this.tx("readwrite",t=>t.delete(e)).then()}};var js,sn,qs,Vs=class{constructor(e){l(this,"settings",{path:"/auth",key:"colyseus-auth-token"});he(this,js,!1);he(this,sn,null);he(this,qs,So());l(this,"http");this.http=e,Jf(this.settings.key,t=>this.token=t)}set token(e){this.http.authToken=e}get token(){return this.http.authToken}onChange(e){let t=H(this,qs).on("change",e);return H(this,js)||this.getUserData().then(r=>{this.emitChange({...r,token:this.token})}).catch(r=>{this.emitChange({user:null,token:void 0})}),pe(this,js,!0),t}async getUserData(){if(this.token)return(await this.http.get(`${this.settings.path}/userdata`)).data;throw new Error("missing auth.token")}async registerWithEmailAndPassword(e,t,r){let s=(await this.http.post(`${this.settings.path}/register`,{body:{email:e,password:t,options:r}})).data;return this.emitChange(s),s}async signInWithEmailAndPassword(e,t){let r=(await this.http.post(`${this.settings.path}/login`,{body:{email:e,password:t}})).data;return this.emitChange(r),r}async signInAnonymously(e){let t=(await this.http.post(`${this.settings.path}/anonymous`,{body:{options:e}})).data;return this.emitChange(t),t}async sendPasswordResetEmail(e){return(await this.http.post(`${this.settings.path}/forgot-password`,{body:{email:e}})).data}async signInWithProvider(e,t={}){return new Promise((r,s)=>{let i=t.width||480,o=t.height||768,a=this.token?`?token=${this.token}`:"",c=`Login with ${e[0].toUpperCase()+e.substring(1)}`,u=this.http.sdk.getHttpEndpoint(`${t.prefix||`${this.settings.path}/provider`}/${e}${a}`),d=screen.width/2-i/2,h=screen.height/2-o/2;pe(this,sn,window.open(u,c,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+i+", height="+o+", top="+h+", left="+d));let m=p=>{if(!(p.data.user===void 0&&p.data.token===void 0))if(clearInterval(g),H(this,sn)?.close(),pe(this,sn,null),window.removeEventListener("message",m),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)},g=setInterval(()=>{(!H(this,sn)||H(this,sn).closed)&&(pe(this,sn,null),s("cancelled"),window.removeEventListener("message",m))},200);window.addEventListener("message",m)})}async signOut(){this.emitChange({user:null,token:null})}emitChange(e){e.token!==void 0&&(this.token=e.token,e.token===null?Wf(this.settings.key):zf(this.settings.key,e.token)),H(this,qs).emit("change",e)}};js=new WeakMap,sn=new WeakMap,qs=new WeakMap;function Kf(n){let e=window?.location?.hostname||"localhost",t=n.hostname.split("."),r=!n.hostname.includes("trycloudflare.com")&&!n.hostname.includes("discordsays.com")&&t.length>2?`/${t[0]}`:"";return n.pathname.startsWith("/.proxy")?`${n.protocol}//${e}${r}${n.pathname}${n.search}`:`${n.protocol}//${e}/.proxy/colyseus${r}${n.pathname}${n.search}`}Rs();var Yf=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",Co=class Co{constructor(e=Yf,t){l(this,"http");l(this,"auth");l(this,"settings");l(this,"urlBuilder");if(typeof e=="string"){let r=e.startsWith("/")?new URL(e,Yf):new URL(e),s=r.protocol==="https:"||r.protocol==="wss:",i=Number(r.port||(s?443:80));this.settings={hostname:r.hostname,pathname:r.pathname,port:i,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)),t?.protocol&&(this.settings.protocol=t.protocol),this.http=new vo(this,{headers:t?.headers||{}},t?.fetchFn),this.auth=new Vs(this.http),this.urlBuilder=t?.urlBuilder,!this.urlBuilder&&typeof window<"u"&&window?.location?.hostname?.includes("discordsays.com")&&(this.urlBuilder=Kf,console.log("Colyseus SDK: Discord Embedded SDK detected. Using custom URL builder."))}static async selectByLatency(e,t,r={}){let s=e.map(o=>new Co(o,t)),i=(await Promise.allSettled(s.map((o,a)=>o.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(o=>o.status==="fulfilled").map(o=>o.value);if(i.length===0)throw new Error("All endpoints failed to respond");return s[i.sort((o,a)=>o[1]-a[1])[0][0]]}async joinOrCreate(e,t={},r){return await this.createMatchMakeRequest("joinOrCreate",e,t,r)}async create(e,t={},r){return await this.createMatchMakeRequest("create",e,t,r)}async join(e,t={},r){return await this.createMatchMakeRequest("join",e,t,r)}async joinById(e,t={},r){return await this.createMatchMakeRequest("joinById",e,t,r)}async reconnect(e,t){if(typeof e=="string"&&typeof t=="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},t)}async consumeSeatReservation(e,t){let r=this.createRoom(e.name,t);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((i,o)=>{let a=(c,u)=>o(new It(c,u));r.onError.once(a),r.onJoin.once(()=>{r.onError.remove(a),ao("room",r),i(r)})})}getLatency(e={}){let t=e.protocol??"ws",r=e.pingCount??1,s=e.timeout??1500;return new Promise((i,o)=>{let a=new Cr(t),c=[],u=0,d=!1,h,m=p=>{if(!d){d=!0,clearTimeout(h);try{a.close()}catch{}p()}},g=p=>m(()=>o(new It(Ne.ABNORMAL_CLOSURE,`Failed to get latency: ${p}`)));h=setTimeout(()=>g(`timed out after ${s}ms`),s),a.events.onopen=()=>{u=Date.now(),a.send(new Uint8Array([_e.PING]))},a.events.onmessage=p=>{if(c.push(Date.now()-u),c.length<r)u=Date.now(),a.send(new Uint8Array([_e.PING]));else{let y=c.reduce((x,k)=>x+k,0)/c.length;m(()=>i(y))}},a.events.onclose=p=>g(`connection closed${p?.code?` (${p.code})`:""}${p?.reason?`: ${p.reason}`:""}`),a.events.onerror=p=>g(p.message);try{a.connect(this.getHttpEndpoint())}catch(p){g(p?.message??"failed to connect")}})}async createMatchMakeRequest(e,t,r={},s){try{if(!t)throw new Error("Must provide a room name");let o=(await this.http.post(`/matchmake/${e}/${t}`,{headers:{Accept:"application/json","Content-Type":"application/json"},body:r})).data;return e==="reconnect"&&(o.reconnectionToken=r.reconnectionToken),await this.consumeSeatReservation(o,s)}catch(i){throw i instanceof It?new os(i.message,i.code):i}}createRoom(e,t){return new Us(e,t)}buildEndpoint(e,t={}){let r=this.settings.protocol||"ws",s=this.settings.searchParams||"";this.http.authToken&&(t._authToken=this.http.authToken);for(let a in t)t.hasOwnProperty(a)&&(s+=(s?"&":"")+`${a}=${t[a]}`);r==="h3"&&(r="http");let i=this.settings.secure?`${r}s://`:`${r}://`;e.publicAddress?i+=`${e.publicAddress}`:i+=`${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}`;let o=`${i}/${e.processId}/${e.roomId}?${s}`;return this.urlBuilder?this.urlBuilder(new URL(o)):o}getHttpEndpoint(e=""){let t=e.startsWith("/")?e:`/${e}`,r=`${this.settings.secure?"https":"http"}://${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}${t}`;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}`:""}};l(Co,"VERSION","0.18");var Ao=Co,Gs=Ao;Yt();var Io=class{setState(e){}getState(){return null}patch(e){}teardown(){}handshake(e){}};He();Qc();No();Bo();Do();Lc("schema",Ir);Lc("none",Io);var jo={PLAY:"play",QUEUE:"queue",MATCH:"match"};var dh={BAD_OPTION:400,AUTH_REQUIRED:401,FORBIDDEN:403,PROTOCOL_UNSUPPORTED:426};var J={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"},ne={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"},c0=["__","match:","server:","rate:"],l0=["state","shared","claim","release","destroy","obj","queue","seat"];function Qs(n){return l0.includes(n)||c0.some(e=>n.startsWith(e))}var qo="__",qt="__t";var Xx={[J.STATE]:"state",[J.STATE_SNAP]:"state",[J.SHARED]:"bulk",[J.CLAIM]:"control",[J.RELEASE]:"control",[J.DESTROY]:"control",[J.OBJECT]:"bulk",[J.OBJECT_SNAP]:"bulk",[J.INPUT]:"input",[J.ROOM_OPEN]:"control",[J.CHAT]:"chat",[J.CHAT_HISTORY_REQUEST]:"control",[J.VOICE_ICE_REQUEST]:"voice",[J.VOICE_JOIN]:"voice",[J.VOICE_LEAVE]:"voice",[J.VOICE_SIGNAL]:"voice",[J.MATCH_ELIMINATED]:"bulk",[J.MATCH_SCORE]:"bulk",[J.MATCH_FINISH]:"bulk",[J.POSE]:"pose",[J.POSE_SNAP]:"pose"},Zc={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},vn={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},Qx={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},Gt={enabled:!0,minUptime:0,delay:125,minDelay:100,maxDelay:4e3,maxRetries:9,maxEnqueuedMessages:0,firstStateTimeoutMs:2e3},fh=["x","y","z","yaw","vx","vy","vz","anim"],ye={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},an={HEARTBEAT_HZ:10,MIN_HEARTBEAT_HZ:5,MAX_HEARTBEAT_HZ:20,HEARTBEAT_DITHER:.15,RELAY_BUFFER:4,WARMUP_ACKS:30};function hh(n,e){let t=null,r=null;return{request(){return t||(t=new Promise(s=>{let i,o=a=>{r&&(r=null,t=null,i&&clearTimeout(i),s(a))};r=o,i=setTimeout(()=>o(null),e),n()}),t)},deliver(s){r?.(s)},get pending(){return t!==null}}}var ph=["x","y","z","yaw","vx","vy","vz"],mh=[["x","vx"],["y","vy"],["z","vz"]],el=Math.PI*2,u0=n=>fh.includes(n);function tl(n){if(!Number.isFinite(n))return 0;let e=n%el;return e<=-Math.PI?e+=el:e>Math.PI&&(e-=el),e}var gh=n=>typeof n=="number"&&Number.isFinite(n)&&Math.abs(n)<=vn.MAX_POSE_ABS;function yh(n){let e={},t={},r=[];for(let s of Object.keys(n)){let i=n[s];if(!u0(s)){t[s]=i;continue}i!==void 0&&(s==="anim"?typeof i=="string"&&i.length<=vn.MAX_ANIM_CHARS?e.anim=i:r.push(s):gh(i)?e[s]=i:r.push(s))}return{pose:e,data:t,invalid:r}}function bh(n){for(let e in n)if(n[e]!==void 0)return!0;return!1}function wh(n,e,t){let r={...n},s={t:e},i=t?e-t.t:0,o=t!==void 0&&i>ye.MIN_GAP_MS&&i<ye.MAX_GAP_MS;for(let[a,c]of mh){let u=n[a];if(u===void 0||(s[a]=u,n[c]!==void 0))continue;let d=t?.[a],h=o&&d!==void 0?(u-d)/i*1e3:0;r[c]=gh(h)?h:0}return{pose:r,memory:s}}function zo(n){let e=t=>typeof t=="number"&&Number.isFinite(t)?t:0;return{x:e(n.x),y:e(n.y),z:e(n.z),yaw:e(n.yaw),vx:e(n.vx),vy:e(n.vy),vz:e(n.vz),anim:typeof n.anim=="string"?n.anim:""}}var zr=(n,e)=>{let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0};function _h(n,e){let t=n.length;if(t===0)return;let r=0;for(;r<t&&n[r].t<=e;)r++;if(r===0)return n[0].state;if(r>=t){let u=n[t-1],d={...u.state},h=Math.min(Math.max(0,e-u.t),ye.MAX_EXTRAP_MS)/1e3;for(let[m,g]of mh)d[m]=zr(u.state,m)+zr(u.state,g)*h;if(t>=2){let m=n[t-2],g=u.t-m.t;if(g>0){let p=Math.min(Math.max(0,e-u.t),ye.ROT_EXTRAP_MS)/g,y=zr(u.state,"yaw");d.yaw=y+tl(y-zr(m.state,"yaw"))*p}}return d}let s=n[r-1],i=n[r],o=i.t-s.t,a=o>0?(e-s.t)/o:1,c={...s.state};for(let u of ph){let d=zr(s.state,u),h=zr(i.state,u);c[u]=u==="yaw"?d+tl(h-d)*a:d+(h-d)*a}return c}function Eh(n,e,t,r){let s={...e};for(let i of ph){let o=n[i],a=e[i];typeof o!="number"||typeof a!="number"||!Number.isFinite(o)||!Number.isFinite(a)||(s[i]=i==="yaw"?o+tl(a-o)*r:o+(a-o)*t)}return s}var Ho=class Ho{constructor(){l(this,"pending",[]);l(this,"current")}push(e,t){for(this.pending.push({t:e,state:t});this.pending.length>Ho.MAX_PENDING;)this.current=this.pending.shift()?.state}at(e){for(;this.pending.length>0;){let t=this.pending[0];if(this.current!==void 0&&e!==void 0&&t.t!==void 0&&t.t>e)break;this.current=t.state,this.pending.shift()}return this.current}flush(){this.at(void 0)}};l(Ho,"MAX_PENDING",64);var Go=Ho;function Rh(n){try{let e=n.input();return e&&typeof e.send=="function"?e:null}catch{return null}}function xh(n,e,t=an.HEARTBEAT_HZ,r=Math.random){let i=1e3/Math.min(an.MAX_HEARTBEAT_HZ,Math.max(an.MIN_HEARTBEAT_HZ,t)),o=1e3/an.MAX_HEARTBEAT_HZ,a=1e3/an.MIN_HEARTBEAT_HZ,c=!1,u=!1,d,h=()=>{if(u)return;if(e()){try{n.send()}catch{}!c&&n.lastProcessed>=an.WARMUP_ACKS&&(c=!0)}let m=i*(1+(r()*2-1)*an.HEARTBEAT_DITHER);d=setTimeout(h,Math.min(a,Math.max(o,m)))};return h(),{get synced(){return!c&&n.lastProcessed>=an.WARMUP_ACKS&&(c=!0),c},stop(){u=!0,d&&clearTimeout(d)}}}function Sh(n,e){return e.synced&&e.clockOrigin>0&&e.serverNow!==void 0&&Number.isFinite(e.serverNow)?n-e.clockOrigin-e.serverNow:n-e.wallNow}function Zs(n){let e=n.reconnection;return e.enabled=Gt.enabled,e.minUptime=Gt.minUptime,e.delay=Gt.delay,e.minDelay=Gt.minDelay,e.maxDelay=Gt.maxDelay,e.maxRetries=Gt.maxRetries,e.maxEnqueuedMessages=Gt.maxEnqueuedMessages,e.enqueuedMessages.length=0,n}function Th(n){return n.reconnection.enabled=!1,n}function kh(n,e){return new Promise(t=>{let r=()=>{clearTimeout(s),t(!0)},s=setTimeout(()=>{n.onStateChange.remove(r),t(!1)},e);n.onStateChange.once(r)})}function vh(n,e,t){return n!==e&&t!=null}var d0="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.",nl=class extends Error{constructor(e){super(d0,{cause:e}),this.name="VoiceNotDelegatedError"}},Ah=[{urls:"stun:stun.l.google.com:19302"}],f0=120,Ch=.02,h0=.6,Wo=class{constructor(e){l(this,"transport");l(this,"peers",new Map);l(this,"listeners",new Set);l(this,"roster",[]);l(this,"local",null);l(this,"audio",null);l(this,"localAnalyser",null);l(this,"levelTimer",null);l(this,"iceServers",Ah);l(this,"spatial",!1);l(this,"threshold",Ch);l(this,"micOn",!0);l(this,"selfSpeaking",!1);l(this,"running",!1);l(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={},t=!1){if(!this.running){this.peeringHeld=t,this.iceServers=e.iceServers?.length?e.iceServers:Ah,this.spatial=e.spatial===!0,this.threshold=e.speakingThreshold??Ch,this.micOn=e.startMuted!==!0;try{this.local=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1})}catch(r){throw m0(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(),f0)}}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 t of this.peers.values())try{t.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 t=this.transport.selfId(),r=new Set(e.filter(s=>s!==t));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 t of this.local?.getAudioTracks()??[])t.enabled=e;!e&&this.selfSpeaking&&(this.selfSpeaking=!1,this.emit())}mute(e){this.setMuted(e,!0)}unmute(e){this.setMuted(e,!1)}setVolume(e,t){let r=this.peers.get(e);r&&(r.volume=Math.max(0,Math.min(1,t)),r.el&&(r.el.volume=r.volume),this.emit())}async handleSignal(e,t){if(!this.running)return;let r=t;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 i=await s.pc.createAnswer();await s.pc.setLocalDescription(i),this.transport.sendSignal(e,{t:"answer",sdp:i})}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(i){console.warn(`[multiplayer] voice signaling failed with ${e}`,i)}}setMuted(e,t){let r=this.peers.get(e);!r||r.muted===t||(r.muted=t,r.el&&(r.el.muted=t||this.spatial),t&&r.speaking&&(r.speaking=!1),this.emit())}createPeer(e){let t=new RTCPeerConnection({iceServers:this.iceServers}),r={id:e,pc:t,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&&t.addTrack(s,this.local);return t.onicecandidate=s=>{s.candidate&&this.transport.sendSignal(e,{t:"ice",c:s.candidate.toJSON()})},t.ontrack=s=>{let i=s.streams[0]??new MediaStream([s.track]);r.stream=i,r.el=this.attachSink(i,r),r.analyser=this.makeAnalyser(i),this.emit()},t.onconnectionstatechange=()=>{let s=t.connectionState,i=s==="connected"?"connected":s==="failed"||s==="closed"?"failed":"connecting";if(i!==r.connection){if(r.connection=i,i==="failed"){let o=this.iceServers.some(a=>g0(a));console.warn(`[multiplayer] voice connection to ${e} failed`+(o?"":" \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 t=await e.pc.createOffer();await e.pc.setLocalDescription(t),this.transport.sendSignal(e.id,{t:"offer",sdp:t})}catch(t){console.warn(`[multiplayer] voice offer to ${e.id} failed`,t)}}async flushIce(e){let t=e.pendingIce.splice(0);for(let r of t)try{await e.pc.addIceCandidate(r)}catch{}}destroyPeer(e){let t=this.peers.get(e);if(t){this.peers.delete(e),t.pc.onicecandidate=null,t.pc.ontrack=null,t.pc.onconnectionstatechange=null;try{t.pc.close()}catch{}t.el&&(t.el.srcObject=null,t.el.remove())}}attachSink(e,t){let r=document.createElement("audio");return r.autoplay=!0,r.srcObject=e,r.muted=this.spatial||t.muted,r.volume=t.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 t=this.audio.createMediaStreamSource(e),r=this.audio.createAnalyser();return r.fftSize=512,t.connect(r),r}catch{return null}}pollLevels(){let e=!1,t=this.micOn?Ih(this.localAnalyser):0,r=this.crossed(t,this.selfSpeaking);r!==this.selfSpeaking&&(this.selfSpeaking=r,e=!0);for(let s of this.peers.values()){let i=s.muted?!1:this.crossed(Ih(s.analyser),s.speaking);i!==s.speaking&&(s.speaking=i,e=!0)}e&&this.emit()}crossed(e,t){return e>=(t?this.threshold*h0:this.threshold)}emit(){for(let e of[...this.listeners])try{e()}catch(t){console.error("[multiplayer] a voice listener threw",t)}}};function p0(){try{return window.self!==window.top}catch{return!0}}function m0(n){if(n?.name!=="NotAllowedError")return n;try{if(!p0()||document.featurePolicy?.allowsFeature?.("microphone")!==!1)return n}catch{return n}return new nl(n)}function g0(n){return(Array.isArray(n.urls)?n.urls:[n.urls]).some(t=>typeof t=="string"&&t.startsWith("turn"))}function Ih(n){if(!n)return 0;let e=new Uint8Array(n.fftSize);n.getByteTimeDomainData(e);let t=0;for(let r=0;r<e.length;r++){let s=((e[r]??128)-128)/128;t+=s*s}return Math.sqrt(t/e.length)}var rl=Symbol("genex.roomRef"),cn=n=>n[rl]();var y0=ye.RATIO,b0=ye.MIN_MS,w0=ye.MAX_MS,Jo=ye.DEFAULT_MS,_0=ye.JITTER_SAFETY,E0=ye.POISON_GUARD_MS,R0=ye.EASE,x0=ye.MAX_EXTRAP_MS,S0=ye.ROT_EXTRAP_MS,Mh=ye.CLOCK_WINDOW,T0=ye.CLOCK_WINDOW_MS,k0=ye.CLOCK_WINDOW_MAX,v0=ye.INTERVAL_WINDOW,A0=ye.MIN_GAP_MS,C0=ye.MAX_GAP_MS,I0=ye.HISTORY_MS,P0=ye.SMOOTH_TAU_POS_MS,O0=ye.SMOOTH_TAU_ROT_MS,Dh=ye.MAX_HOST_TICK_DT_MS,M0=ye.REBASE_AFTER_GAP_MS,Ht="obj:",D0=3e3,N0=5e3,B0=6e4,L0=2e3;async function Xo(n){if(n.url)return new Gs(n.url);if(n.urls.length>1)return Gs.selectByLatency(n.urls);let e=n.urls[0];if(!e)throw new Error("genex multiplayer: `urls` must contain at least one relay URL");return new Gs(e)}var F0=n=>typeof n=="function"?n():n;function Lh(n){if(n==="predict")return{mode:"lerp"};if(n&&typeof n=="object"&&n.engine==="predict")return{mode:n.mode==="damped"?"damped":"lerp",delay:n.delay,smoothMs:n.smoothMs}}var Qo=async n=>Lh(n)?Promise.resolve().then(()=>(Oh(),Ph)):void 0;function Nh(n){if(!n)return{state:{}};try{let e=JSON.parse(n);if(!e||typeof e!="object")return{state:{}};let t=e,r=t[qt];if(typeof r=="number"&&Number.isFinite(r)){let s={...t};return delete s[qt],{state:s,sendTime:r}}return{state:t}}catch{return{state:{}}}}function Ko(n){if(n!=null)try{return JSON.parse(n)}catch{return}}var U0=(n,e)=>typeof e=="number"?Number.isFinite(e)?e:0:typeof e=="bigint"?Number(e):e;function Wr(n){return JSON.parse(JSON.stringify(n,U0))}var er=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function Fh(n,e,t){let[r,s,i,o]=e,[a,c,u,d]=n,h=a*r+c*s+u*i+d*o;if(h<0&&(r=-r,s=-s,i=-i,o=-o,h=-h),h>.9995){let x=a+(r-a)*t,k=c+(s-c)*t,P=u+(i-u)*t,U=d+(o-d)*t,N=Math.hypot(x,k,P,U)||1;return[x/N,k/N,P/N,U/N]}let m=Math.acos(h),g=Math.sin(m),p=Math.sin(m-m*t)/g,y=Math.sin(m*t)/g;return[a*p+r*y,c*p+s*y,u*p+i*y,d*p+o*y]}function Yo(n){return Array.isArray(n)&&n.length===4&&n.every(e=>typeof e=="number"&&Number.isFinite(e))}function Bh(n,e,t,r){let s={},i=t<1;for(let o in e){let a=n[o],c=e[o];typeof a=="number"&&typeof c=="number"&&Number.isFinite(a)&&Number.isFinite(c)?s[o]=a+(c-a)*t:Yo(a)&&Yo(c)?s[o]=Fh(a,c,r):s[o]=i&&o in n?a:c}return s}function $0(n,e,t,r){let s={};for(let i in e){let o=e[i],a=n[i];typeof a=="number"&&typeof o=="number"&&Number.isFinite(a)&&Number.isFinite(o)?s[i]=a+(o-a)*t:Yo(a)&&Yo(o)?s[i]=Fh(a,o,r):s[i]=o}return s}function V0(n,e){let t=n.length;if(t===0)return;if(t===1)return n[0].state;let r=0;for(;r<t&&n[r].t<=e;)r++;if(r===0)return n[0].state;if(r>=t){let c=n[t-2],u=n[t-1],d=u.t-c.t;if(d<=0)return u.state;let h=(Math.min(e,u.t+x0)-c.t)/d,m=(Math.min(e,u.t+S0)-c.t)/d;return Bh(c.state,u.state,h,m)}let s=n[r-1],i=n[r],o=i.t-s.t,a=o>0?(e-s.t)/o:1;return Bh(s.state,i.state,a,a)}function j0(n){if(n.length===0)return 66;let e=[...n].sort((t,r)=>t-r);return e[e.length>>1]}function q0(n,e){if(n.length===0)return 0;let t=[...n].sort((s,i)=>s-i),r=Math.min(t.length-1,Math.max(0,Math.round(e*(t.length-1))));return t[r]}async function Uh(n){let e=await Xo(n),t=await Qo(n.smoothing),r=Zs(await e.joinOrCreate(jo.PLAY,{...$h(n.room,n.name,n.auth),...n.options,protocol:3}).catch(G0));return il(r,{pose:n.pose,smoothing:n.smoothing,predict:t})}function $h(n,e,t){return{gameId:n,name:e,embedToken:F0(t)?.embedToken,protocol:3}}var Vh=n=>!!n&&typeof n=="object"&&n.code===dh.PROTOCOL_UNSUPPORTED,jh=()=>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.`),G0=n=>{throw Vh(n)&&jh(),n},H0=n=>typeof n=="string"&&n.length>0&&n.length<=vn.MAX_EVENT_TYPE_CHARS&&!Qs(n),z0=new Set(["join","leave","change","shared","object","host","reconnecting","reconnected","disconnect","room:open","voice","voice:rejected"]),W0=new Set([ne.OBJECT_RESULT,ne.INPUT,ne.ROOM_OPEN,ne.CHAT,ne.CHAT_HISTORY,ne.VOICE_ICE,ne.VOICE_SIGNAL,ne.VOICE_REJECTED,ne.RATE_DROP,...Object.values(J)]),J0=[500,1e3,2e3,4e3,8e3];function il(n,e={}){let t=new Map,r=new Map,s=new Map,i=new Map,o=new Map,a=new Map,c=new Set,u=new Map,d=new Map,h=new Map,m=new Map,g,p=new Map,y=new Map,x=new Map,k=new Map,P=new Map,U=new Map,N=new Map,C=new Map,O=new Set,A=new Map,I,V=0,Z=new Map,ee=f=>{for(let b of Z.values())if(b.id===f)return!0;return!1},ve=typeof globalThis<"u"&&globalThis.__GENEX_MP_TEST_SKEW__||0,Pe=ve?()=>er()+ve:er,S=(f,b)=>{if(p.get(b)===n.sessionId)return!1;let v=`${f}:${b}`;return O.has(v)||(O.add(v),console.warn(`[multiplayer] objects.${f}('${b}') ignored because this session does not own the object \u2014 await objects.claimConfirmed('${b}') and check accepted before publishing`)),!0},L=(f,b,v,j)=>{let ie=Pe(),K=v,oe=ie-v,G=i.get(j);G||i.set(j,G={samples:[],mins:[],n:0});let ge=++G.n;for(G.samples.push({at:ie,n:ge});G.mins.length>0&&G.mins[G.mins.length-1].v>=oe;)G.mins.pop();for(G.mins.push({v:oe,n:ge});G.samples.length>k0||G.samples.length>Mh&&G.samples[0].at<ie-T0;)G.samples.shift();let Re=G.samples[0].n;for(;G.mins[0].n<Re;)G.mins.shift();s.set(j,G.mins[0].v);let et=o.get(f);et||o.set(f,et=[]),et.push(oe),et.length>Mh&&et.shift(),a.set(f,j);let mt=r.get(f);if(r.set(f,K),mt!=null){let tt=K-mt;if(tt>A0&&tt<C0){let rr=h.get(f);rr||h.set(f,rr=[]),rr.push(tt),rr.length>v0&&rr.shift();let ip=et.length>=8?Math.max(0,q0(et,.9)-G.mins[0].v):0,op=Math.min(w0,Math.max(b0,y0*j0(rr),_0*ip)),Pl=m.get(f)??Jo;m.set(f,Pl+(op-Pl)*R0)}}let Ae=t.get(f);Ae||t.set(f,Ae=[]);let di=A.get(f);if(di&&Ae.length===0){let tt=m.get(f)??Jo;Ae.push({t:K-Math.max(1,tt),state:di})}A.delete(f),Ae.push({t:K,state:b});let Pn=K-I0;for(;Ae.length>2&&Ae[0].t<Pn;)Ae.shift();for(;Ae.length>1&&Ae[0].t>Ae[Ae.length-1].t+E0;)Ae.shift()},B=(f,b)=>{let v=a.get(f),j=v===void 0?void 0:s.get(v);if(j!==void 0)return b-j-(m.get(f)??Jo)},D=(f,b)=>{let v=t.get(f),j=B(f,b)??b-Jo,ie=c.has(f),K=v&&(ie?_h(v,j):V0(v,j));if(!K)return u.get(f);let oe=u.get(f),G;if(oe){let ge=Math.min(Dh,Math.max(0,b-(d.get(f)??b))),Re=1-Math.exp(-ge/P0),et=1-Math.exp(-ge/O0);G=ie?Eh(oe,K,Re,et):$0(oe,K,Re,et)}else G=K;return u.set(f,G),d.set(f,b),G},M=f=>{t.delete(f),r.delete(f),a.delete(f),u.delete(f),d.delete(f),h.delete(f),m.delete(f),o.delete(f),A.delete(f)},z=f=>{t.delete(f),r.delete(f),a.delete(f),h.delete(f),m.delete(f),o.delete(f)},W=f=>{s.delete(f),i.delete(f)},q=new Map,ae=new Set,Y=(f,...b)=>q.get(f)?.forEach(v=>{try{v(...b)}catch(j){console.error(`[multiplayer] a '${f}' listener threw:`,j)}}),Ze=new Map,pt=(f,b)=>{Ze.get(b)!==f&&(Ze.set(b,f),Y("shared",b,Ko(f)))},ln=f=>{let b=f||void 0;b!==I&&(I=b,Y("host",I))},dl="",ia=()=>{let f=n.state?.voice?[...n.state.voice.keys()].sort():[],b=f.join(`
|
|
14
|
+
`);b!==dl&&(dl=b,be.setRoster(f),Y("voice",be.participants))},fl=(f,b)=>{let v=Ht+f,j=n.sessionId,ie=k.has(f),K=b.owner||void 0,oe=Number.isFinite(b.seq)?b.seq:0,G=Number.isFinite(b.epoch)?b.epoch:0,ge=Number.isFinite(b.t)?b.t:0,Re=typeof b.d=="string"?b.d:"",mt=K!==y.get(f)||ie&&oe!==k.get(f),Ae=x.has(f)&&G!==x.get(f),di=ge!==P.get(f);if(k.set(f,oe),x.set(f,G),P.set(f,ge),Re!==U.get(f)){U.set(f,Re);let tt=Re?Ko(Re):void 0;tt&&typeof tt=="object"&&!Array.isArray(tt)&&N.set(f,tt)}K?y.set(f,K):y.delete(f),(mt||p.get(f)!==K&&!ee(f))&&(K?p.set(f,K):p.delete(f)),Ae&&M(v),mt&&K!==j&&(C.delete(f),Ae||z(v));let Pn=N.get(f);if(Pn&&K!==j){let tt=ge!==0&&di&&K!==void 0;Ae?(u.set(v,Pn),d.set(v,Pe()),tt&&L(v,Pn,ge,K)):(mt&&A.set(v,u.get(v)??Pn),tt&&L(v,Pn,ge,K))}(!ie||mt)&&Y("object",f)},hl=f=>{let b=k.has(f)||p.has(f)||N.has(f)||C.has(f);M(Ht+f),N.delete(f),p.delete(f),y.delete(f),x.delete(f),k.delete(f),P.delete(f),U.delete(f),C.delete(f),b&&Y("object",f)},oa=new Map,Kr=new Map,aa=new Map,Zh=(f,b)=>{if(!b)return{};let v=oa.get(f);if(v&&v.raw===b)return v.state;let{state:j}=Nh(b);return oa.set(f,{raw:b,state:j}),j},ti=new Map,ca=new Map,tr=e.predict?Lh(e.smoothing):void 0,At,un=new Map,ep=(f,b)=>{if(!tr||!e.predict)return;At??(At=e.predict.Predict.get(n));let v={mode:tr.mode,delay:tr.delay,smoothMs:tr.smoothMs};At.attach(b,{x:v,y:v,z:v,vx:v,vy:v,vz:v}),At.attach(b,{yaw:{...v,angle:!0}}),un.set(f,b)},pl=f=>{let b=un.get(f);b&&At&&At.detach(b),un.delete(f)},tp=f=>{let b=At;return{x:b.value(f,"x"),y:b.value(f,"y"),z:b.value(f,"z"),yaw:b.value(f,"yaw"),vx:b.value(f,"vx"),vy:b.value(f,"vy"),vz:b.value(f,"vz"),anim:f.anim??""}},Ct=!1,Wt=!1,Cn=!0,ni=!1,ml=0,ri=0,la=0,ua=new Set,si=()=>ua.forEach(f=>f()),Yr=(f,b)=>{if(Z.delete(f.requestId),f.timeout&&clearTimeout(f.timeout),f.abort?.(),f.operation==="claim"&&f.optimistic&&!b.accepted){let v=b.owner??y.get(f.id);v?p.set(f.id,v):p.delete(f.id),v!==n.sessionId&&C.delete(f.id)}f.operation==="claim"&&b.accepted&&(p.set(f.id,n.sessionId),z(Ht+f.id)),f.operation==="release"&&b.accepted&&(C.delete(f.id),p.get(f.id)===n.sessionId&&p.delete(f.id),z(Ht+f.id)),f.operation==="remove"&&b.accepted&&(C.delete(f.id),N.delete(f.id),p.delete(f.id),M(Ht+f.id)),f.resolve(b)},Xr=(f,b)=>{let v=n.state?.objects?.get(f.id);return{requestId:f.requestId,operation:f.operation,id:f.id,accepted:!1,owner:v?.owner||void 0,sequence:v&&Number.isFinite(v.seq)?v.seq:0,reason:b}},gl=f=>{for(let b of[...Z.values()])Yr(b,Xr(b,f))},yl=(f,b=!1)=>{if(!b&&!Cn)return;let v=f.operation==="claim"?J.CLAIM:f.operation==="release"?J.RELEASE:J.DESTROY;De(v,f.payload)},nr=(f,b,v={})=>{let j=String(b),ie=`${n.sessionId.slice(0,12)}:${Date.now().toString(36)}:${(++V).toString(36)}`,K=Math.max(250,Math.min(v.timeoutMs??N0,B0));return new Promise(oe=>{let G={operation:f,id:j,requestId:ie,payload:{id:j,requestId:ie,...v.authority==="host"?{authority:"host"}:{}},optimistic:f==="claim"&&v.optimistic===!0,resolve:oe,timeout:null,abort:void 0};if(Ct||Wt){oe(Xr(G,Ct?"aborted":"disconnected"));return}if(G.optimistic&&p.set(j,n.sessionId),G.timeout=setTimeout(()=>Yr(G,Xr(G,"timeout")),K),v.signal){let ge=()=>Yr(G,Xr(G,"aborted"));v.signal.addEventListener("abort",ge,{once:!0}),G.abort=()=>v.signal?.removeEventListener("abort",ge)}if(Z.set(ie,G),v.signal?.aborted){Yr(G,Xr(G,"aborted"));return}yl(G)})},ii=0,De=(f,b,v=!1)=>{if(n.connection?.isOpen)try{return n.send(f,b),!0}catch{}return v&&ii++,!1},oi,bl=0,wl,_l=new Set,El=(f,b)=>{let{pose:v,data:j,invalid:ie}=yh(f);for(let Re of ie)_l.has(Re)||(_l.add(Re),console.warn(`[multiplayer] me.set: '${Re}' is a typed pose key (pose: true) and its value is not a `+(Re==="anim"?`string of \u2264${vn.MAX_ANIM_CHARS} chars`:"finite number")+" \u2014 it is not sent."));if(!bh(v))return!1;let K=Pe(),oe=wh(v,K,b?void 0:wl);wl=oe.memory;let G=JSON.stringify(j),ge=b||G!==oi||K-bl>=L0;return ge&&De(J.STATE,JSON.stringify({...j,[qt]:K}))?(oi=G,bl=K):ge&&(oi=void 0),De(b?J.POSE_SNAP:J.POSE,{...oe.pose,t:K})||(oi=void 0),!0},be=new Wo({selfId:()=>n.sessionId,nameOf:f=>n.state?.players?.get(f)?.name??"",sendSignal:(f,b)=>De(J.VOICE_SIGNAL,{to:f,data:b},!0)});be.onChange(()=>Y("voice",be.participants));let ai=null,da=hh(()=>De(J.VOICE_ICE_REQUEST,{},!0),D0),ci=()=>{ai&&clearTimeout(ai),ai=null},Rl=f=>{ci(),!(typeof f!="number"||!Number.isFinite(f)||f<=0)&&(ai=setTimeout(()=>{be.active&&da.request().then(b=>{!be.active||!b?.iceServers?.length||(be.setIceServers(b.iceServers),Rl(b.ttl))})},Math.max(6e4,Math.floor(f*800))))},In=[],xl=new Set,fa=new Set,li=new Set,np=f=>!!f&&typeof f=="object"&&typeof f.id=="number"&&typeof f.from=="string"&&typeof f.name=="string"&&typeof f.text=="string",Sl=f=>{if(!np(f)||xl.has(f.id)||li.has(f.from))return;xl.add(f.id);let b=In[In.length-1];if(!b||f.id>b.id)In.push(f);else{let v=In.length;for(;v>0&&(In[v-1]?.id??0)>f.id;)v--;In.splice(v,0,f)}for(let v of[...fa])try{v(f)}catch(j){console.error("[multiplayer] a chat listener threw",j)}},lt=$c(n);if(!lt)throw new Error("genex multiplayer: the relay room has no schema state");let Tl=(f,b,v)=>{let j=f===n.sessionId,{state:ie,sendTime:K}=Nh(b.data),oe=Number.isFinite(b.epoch)?b.epoch:0,G=Kr.has(f)&&oe!==Kr.get(f);Kr.set(f,oe);let ge=v||b.data!==aa.get(f);aa.set(f,b.data);let Re=Number.isFinite(b.poseT)?b.poseT:0,et=Re!==(ca.get(f)??0);ca.set(f,Re);let mt=b.posed===!0;if(!j&&mt&&!c.has(f)&&(M(f),c.add(f),ti.set(f,new Go)),!j&&G&&(M(f),un.has(f)&&pl(f)),Y(v?"join":"change",f,mt?{...ie,...zo(b)}:ie),!j){if(mt){let Ae=ti.get(f);(ge||G)&&(Ae.push(K,ie),(G||tr)&&Ae.flush()),tr?un.has(f)||ep(f,b):Re!==0&&(et||G)&&L(f,zo(b),Re,f);return}(ge||G)&&vh(f,n.sessionId,K)&&L(f,ie,K,f)}};lt(n.state).players.onAdd((f,b)=>{Tl(b,f,!0),lt(f).onChange(()=>Tl(b,f,!1))});let kl=f=>{Y("leave",f),M(f),W(f),pl(f),oa.delete(f),Kr.delete(f),aa.delete(f),ca.delete(f),c.delete(f),ti.delete(f)};lt(n.state).players.onRemove((f,b)=>kl(b)),lt(n.state).shared.onAdd(pt),lt(n.state).shared.onChange(pt),lt(n.state).objects.onAdd((f,b)=>{fl(b,f),lt(f).onChange(()=>fl(b,f))}),lt(n.state).objects.onRemove((f,b)=>hl(b)),lt(n.state).listen("host",f=>ln(f)),lt(n.state).voice.onAdd(ia),lt(n.state).voice.onRemove(ia);let rp=()=>{let f=n.state;if(f){for(let b of new Set([...p.keys(),...N.keys(),...k.keys()]))f.objects?.has(b)||hl(b);for(let b of[...Kr.keys()])f.players?.has(b)||kl(b);ln(f.host),ia()}};n.onMessage(ne.VOICE_SIGNAL,f=>{f&&typeof f.from=="string"&&be.handleSignal(f.from,f.data)}),n.onMessage(ne.VOICE_REJECTED,f=>{ci(),be.stop(),Y("voice:rejected",f??{reason:"full"})}),n.onMessage(ne.VOICE_ICE,f=>{da.deliver(f??null)}),n.onMessage(ne.CHAT,f=>Sl(f)),n.onMessage(ne.CHAT_HISTORY,f=>{if(Array.isArray(f?.messages))for(let b of f.messages)Sl(b)}),n.onMessage(ne.OBJECT_RESULT,f=>{if(!f||typeof f.requestId!="string")return;let b=Z.get(f.requestId);!b||f.operation!==b.operation||f.id!==b.id||Yr(b,f)}),n.onMessage(ne.INPUT,f=>{f&&typeof f.from=="string"&&Y(ne.INPUT,f.from,f.d)}),n.onMessage(ne.ROOM_OPEN,f=>{typeof f?.open=="boolean"&&Y("room:open",{open:f.open})}),n.onMessage(ne.RATE_DROP,f=>{console.warn(`[multiplayer] the relay dropped ${f?.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).`)}),n.onMessage(ne.SERVER_RESTART,()=>{}),De(J.CHAT_HISTORY_REQUEST,{});let vl=Rh(n),Qr=vl?xh(vl,()=>!Wt&&!Ct):void 0,Al=()=>Qr?n.clock.serverNow():void 0,sp=f=>Sh(f,{synced:Qr?.synced===!0,clockOrigin:Number.isFinite(n.state?.clockOrigin)?n.state?.clockOrigin:0,serverNow:Al(),wallNow:Date.now()}),Cl=()=>{Qr?.stop(),At?.dispose(),At=void 0,un.clear()};n.onDrop(f=>{if(Ct||Wt)return;la++,ni||(ni=!0,ml=0,ri=er()),Cn=!1,si();let{isReconnecting:b,retryCount:v,maxRetries:j}=n.reconnection;b&&v>=j||Y("reconnecting",{attempt:++ml,code:f})}),n.onReconnect(()=>{if(Wt)return;if(Ct){n.leave().catch(()=>{});return}let f=la;if((ri?er()-ri:0)>M0){for(let v of[...t.keys()])M(v);for(let v of[...i.keys()])W(v)}(async()=>{if(await kh(n,Gt.firstStateTimeoutMs),!(f!==la||Wt||Ct)){rp();for(let v of[...Z.values()])yl(v,!0);De(J.CHAT_HISTORY_REQUEST,{}),ni=!1,ri=0,Cn=!0,si(),Y("reconnected"),ii>0&&(console.warn(`[multiplayer] ${ii} fire-and-forget event(s)/input(s) were dropped while reconnecting \u2014 they are not buffered; player/object state re-synced automatically.`),ii=0)}})()}),n.onLeave(f=>{Wt||(Wt=!0,Cn=!1,ni=!1,Cl(),si(),!Ct&&(gl("disconnected"),Y("disconnect",f??1006)))}),n.onError(()=>{});let Il=((f,b)=>{let v=q.get(f);return v||q.set(f,v=new Set),v.add(b),!z0.has(f)&&!W0.has(f)&&!ae.has(f)&&(ae.add(f),n.onMessage(f,j=>Y(f,j))),()=>{v?.delete(b)}}),ui={id:n.sessionId,get players(){let f=new Map,b=Pe();return At&&un.size>0&&At.tick(er()),n.state?.players?.forEach((v,j)=>{let ie=Zh(j,v.data),K=ie,oe=ie,G=ti.get(j);if(j!==n.sessionId&&G){let ge=zo(v);if(oe={...ie,...ge},un.has(j))K={...G.at(void 0)??ie,...tp(v)};else{let Re=D(j,b)??ge;K={...G.at(B(j,b))??ie,...Re}}}else j===n.sessionId?g&&(K=g,oe=g):K=D(j,b)??ie;f.set(j,{id:j,name:v.name??"",avatarUrl:v.avatarUrl??"",connected:v.connected!==!1,uid:v.uid??"",team:Number.isFinite(v.team)?v.team:-1,state:K,stateRaw:oe})}),f},get activePlayers(){return new Map([...ui.players].filter(([,f])=>f.connected))},me:{set(f){qt in f&&console.warn(`[multiplayer] '${qt}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let b=Wr(f);g=b,!(e.pose&&El(b,!1))&&De(J.STATE,JSON.stringify({...b,[qt]:Pe()}))},snap(f){qt in f&&console.warn(`[multiplayer] '${qt}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let b=Wr(f);g=b,!(e.pose&&El(b,!0))&&De(J.STATE_SNAP,JSON.stringify({...b,[qt]:Pe()}))}},shared:{get(f){return Ko(n.state?.shared?.get(f))},set(f,b){f.startsWith(qo)||De(J.SHARED,{key:f,value:JSON.stringify(Wr(b))})},keys(){return n.state?.shared?Array.from(n.state.shared.keys()):[]}},objects:{claim(f){nr("claim",f,{optimistic:!0})},claimConfirmed(f,b){return nr("claim",f,b)},release(f){let b=String(f);C.delete(b),p.get(b)===n.sessionId&&p.delete(b),z(Ht+b),nr("release",b)},releaseConfirmed(f,b){return nr("release",f,b)},remove(f){let b=String(f);p.get(b)===n.sessionId&&(C.delete(b),N.delete(b),p.delete(b),M(Ht+b)),nr("remove",b)},removeConfirmed(f,b){return nr("remove",f,b)},set(f,b){let v=String(f);if(S("set",v))return;let j=Wr(b);p.get(v)===n.sessionId&&C.set(v,j),De(J.OBJECT,{id:v,d:j,t:Pe()})},snap(f,b){let v=String(f);if(S("snap",v))return;let j=Wr(b);p.get(v)===n.sessionId&&C.set(v,j),De(J.OBJECT_SNAP,{id:v,d:j,t:Pe()})},get(f){let b=String(f),v=p.get(b),j=C.get(b);if(v===void 0&&!N.has(b)&&!j)return;let ie=v!==void 0&&v===n.sessionId,K,oe;return ie&&j?(K=j,oe=j,u.set(Ht+b,j),d.set(Ht+b,Pe())):(oe=N.get(b)??{},K=D(Ht+b,Pe())??oe),{id:b,epoch:x.get(b)??0,owner:v,isMine:ie,state:K,stateRaw:oe}},ids(){return[...new Set([...p.keys(),...N.keys(),...C.keys()])]}},get isHost(){return Cn&&!Ct&&!Wt&&I!==void 0&&I===n.sessionId},get host(){return I},inputs:{send(f){De(J.INPUT,Wr(f),!0)},on(f){let b=q.get(ne.INPUT);b||q.set(ne.INPUT,b=new Set);let v=(j,ie)=>f(j,ie);return b.add(v),()=>{b?.delete(v)}}},onHostTick(f,b){let v=null,j=0,ie=Number.isFinite(f)&&f>0?Math.min(f,100):20,K=Math.max(10,Math.round(1e3/ie)),oe=()=>{let ge=Cn&&!Ct&&!Wt&&I!==void 0&&I===n.sessionId;ge&&!v?(j=er(),v=setInterval(()=>{let Re=er();b(Math.min(Re-j,Dh)),j=Re},K)):!ge&&v&&(clearInterval(v),v=null)},G=Il("host",oe);return ua.add(oe),oe(),()=>{G(),ua.delete(oe),v&&clearInterval(v),v=null}},on:Il,send(f,b){if(!H0(f)){console.warn(`[multiplayer] send('${f}') collides with a relay-internal channel \u2014 use a different event name`);return}De(f,b,!0)},chat:{send(f){typeof f=="string"&&f.trim()&&De(J.CHAT,{text:f},!0)},on(f){return fa.add(f),()=>fa.delete(f)},get history(){return[...In]},mute(f){typeof f=="string"&&f&&li.add(f)},unmute(f){li.delete(f)},get muted(){return[...li]}},voice:{async join(f){if(await be.start(f,!0),!f?.iceServers?.length){let b=await da.request();be.active&&b?.iceServers?.length&&(be.setIceServers(b.iceServers),Rl(b.ttl))}be.active&&(De(J.VOICE_JOIN,{},!0),be.releasePeering())},leave(){ci(),De(J.VOICE_LEAVE,{},!0),be.stop()},get active(){return be.active},get participants(){return be.participants},setMicEnabled(f){be.setMicEnabled(f===!0)},get micEnabled(){return be.micEnabled},get speaking(){return be.speaking},mute(f){be.mute(f)},unmute(f){be.unmute(f)},setVolume(f,b){be.setVolume(f,b)},get muted(){return be.participants.filter(f=>f.muted).map(f=>f.id)}},setRoomOpen(f){De(J.ROOM_OPEN,{open:f===!0})},leave(){Ct=!0,Cl(),be.stop(),ci(),Cn=!1,si(),gl("aborted"),n.reconnection.enabled=!1,n.leave().catch(()=>{})},serverNow:Al,get rtt(){if(!Qr)return;let f=n.clock.smoothedRtt();return f>0?f:void 0},get clockSynced(){return Qr?.synced===!0},timeUntil:sp};return Object.defineProperty(ui,rl,{value:()=>n,enumerable:!1}),Object.defineProperty(ui,Symbol.for("genex.multiplayer.internals"),{enumerable:!1,value:{senderOf:f=>a.get(f),offsetOf:f=>{let b=a.get(f);return b===void 0?void 0:s.get(b)},offsetSamples:f=>i.get(f)?.samples.length??0,bufferLength:f=>t.get(f)?.length??0}}),ui}var K0=[1e3,2e3,4e3],ol=n=>$h(n.room,n.name,n.auth);function qh(n,e,t=r=>r-Date.now()){let r=n?.state?.match,s=r?Ko(r):null,i=s&&typeof s=="object"?s:null;if(!i)return{status:n?"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:n?"Waiting for players\u2026":"Finding a match\u2026",startsAt:null,endsBy:null,startsInMs:null,endsInMs:null};let o=n?.sessionId,a=i.championId??null,c=i.challengerId??null,u=i.teams??{},d=Array.isArray(i.players)?i.players:[],h=i.connectedPlayers??d,m=o!=null&&d.includes(o),g=m?i.phase:"spectating",p=d.filter(O=>O!==o),y=o?Object.keys(u).find(O=>u[O]?.includes(o))??null:null,{winCondition:x,...k}=i.cfg??{},P=O=>typeof O=="number"&&Number.isFinite(O)&&O>0?O:null,U=P(i.startsAt),N=P(i.endsBy),C=O=>O===null?null:Math.max(0,t(O));return{status:g,role:m?"player":"spectator",queue:{position:0,size:0},players:d,connectedPlayers:h,opponents:p,teams:u,myTeam:y,scores:i.scores??{},config:k,winCondition:x?.type??"lastStanding",championId:a,challengerId:c,roundId:i.roundId??0,winnerId:i.winnerId??null,message:i.message??"",startsAt:U,endsBy:N,startsInMs:C(U),endsInMs:C(N)}}function Jr(n,e,t){if(n?.connection?.isOpen)try{n.send(e,t)}catch{}}async function Gh(n){let e=await Xo(n),t=await Qo(n.smoothing),r=new Map,s=(O,...A)=>r.get(O)?.forEach(I=>I(...A)),i=((O,A)=>{let I=r.get(O);return I||r.set(O,I=new Set),I.add(A),()=>{I?.delete(A)}}),o=null,a=null,c=null,u={position:0,size:0},d=!1,h=!1,m=0,g=!1,p=!1,y=async()=>{if(d||h)return;h=!0;let O=++m;try{o=null,a=null;for(let A=0;;A++){c&&(c.leave(),c=null),u={position:0,size:0};let I;try{I=Th(await e.joinOrCreate(jo.QUEUE,ol(n)))}catch(V){if(d)return;let Z=Vh(V);Z&&jh();let ee=Z?void 0:K0[A];if(ee==null){if(A===0&&await new Promise(ve=>setTimeout(ve,0)),d)return;s("error",V);return}if(await new Promise(ve=>setTimeout(ve,ee)),d)return;continue}if(d||O!==m){I.leave();return}c=I,I.onMessage(ne.QUEUE,V=>{u={position:V.position,size:V.size},s("queue",V)}),I.onMessage(ne.SEAT,V=>{d||O!==m||c!==I||g||(g=!0,c=null,I.leave(),x(V.reservation,V.role,O))}),I.onLeave(()=>{d||c!==I||(c=null,(async()=>{for(let V of J0)if(await new Promise(Z=>setTimeout(Z,V)),d||c||o||(await y(),c||o))return})())}),s("searching");return}}finally{h=!1}},x=async(O,A,I)=>{try{let V=Zs(await e.consumeSeatReservation(O));if(d||I!==m){V.leave();return}a=V;let Z=il(V,{pose:n.pose,smoothing:n.smoothing,predict:t});o=Z,Z.on(ne.MATCH_START,ee=>s("matchStart",ee)),Z.on(ne.MATCH_ENDED,ee=>s("matchEnded",ee)),Z.on(ne.MATCH_REQUEUE,()=>{o===Z&&k()}),Z.on("disconnect",ee=>{if(!(d||o!==Z)){if(ee===Zc.SUPERSEDED||ee===Zc.REVOKED){m++,g=!1,a=null,o=null,s("disconnect",ee);return}k()}}),c&&(c.leave(),c=null),s("matched"),A==="spectator"&&s("spectate")}catch{!d&&I===m&&(g=!1,y())}finally{I===m&&(g=!1)}},k=async()=>{if(!(d||p)){p=!0;try{m++,g=!1,o?.leave(),a=null,o=null,await y()}finally{p=!1}}};y();let P=()=>o?cn(o):null,U=null,N=null,C=()=>{o!==U&&(U=o,N=null);let O=P(),A=!!O?.state?.match;if(!A&&o&&N)return N;let I=qh(O,u,o?o.timeUntil:void 0);return A&&(N=I),I};return{get session(){return o},get matchmaking(){return C()},on:i,eliminated(){Jr(P(),J.MATCH_ELIMINATED,{})},score(O=1){Jr(P(),J.MATCH_SCORE,{delta:O})},finish(){Jr(P(),J.MATCH_FINISH,{})},retry(){d||h||c||a||y()},cancel(){d=!0,m++,g=!1,o?.leave(),!o&&a&&a.leave(),c&&c.leave(),a=null,c=null,o=null}}}function Hh(n,e){let t=new Map,r=(c,...u)=>t.get(c)?.forEach(d=>d(...u)),s=((c,u)=>{let d=t.get(c);return d||t.set(c,d=new Set),d.add(u),()=>{d?.delete(u)}}),i=!0,o=il(n,e);o.on(ne.MATCH_START,c=>r("matchStart",c)),o.on(ne.MATCH_ENDED,c=>r("matchEnded",c)),o.on(ne.MATCH_REQUEUE,()=>{i=!1}),o.on("disconnect",()=>{i=!1});let a=()=>i?cn(o):null;return{get session(){return i?o:null},get matchmaking(){return qh(a(),{position:0,size:0},o.timeUntil)},on:s,eliminated(){Jr(a(),J.MATCH_ELIMINATED,{})},score(c=1){Jr(a(),J.MATCH_SCORE,{delta:c})},finish(){Jr(a(),J.MATCH_FINISH,{})},retry(){},cancel(){o.leave(),i=!1}}}async function zh(n){let e=await Xo(n),t=await Qo(n.smoothing),r=Zs(await e.create(jo.MATCH,ol(n))),s=Hh(r,{pose:n.pose,smoothing:n.smoothing,predict:t});return Object.defineProperty(s,"code",{value:r.roomId,enumerable:!0}),s}async function Wh(n,e){let t=await Xo(e),r=await Qo(e.smoothing),s=Zs(await t.joinById(n,ol(e)));return Hh(s,{pose:e.pose,smoothing:e.smoothing,predict:r})}var Y0=1,Kh={ready(n){let e=globalThis.__GENEX__;return n&&e&&typeof e.apiUrl=="string"&&Array.isArray(e.dashboardOrigins)&&Ci({slug:n,apiUrl:e.apiUrl,dashboardOrigins:e.dashboardOrigins.filter(t=>typeof t=="string")}),$a()},auth:()=>gu(),urls:()=>yu()},Zo=Kh;function X0(n){Zo=n??Kh}var zt=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function Q0(n){let e=JSON.parse(n);if(!zt(e))throw new TypeError("genex bridge: options must be a JSON object");let t=typeof e.gameId=="string"?e.gameId:"";if(!t)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(zt(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 i=typeof e.controlTimeoutMs=="number"&&Number.isFinite(e.controlTimeoutMs)?e.controlTimeoutMs:void 0,o=e.smoothing==="genex"||e.smoothing==="predict"||zt(e.smoothing)?e.smoothing:void 0;return{gameId:t,name:typeof e.name=="string"&&e.name?e.name:void 0,urls:r,room:s,pose:e.pose===!0,smoothing:o,controlTimeoutMs:i,options:zt(e.options)?e.options:void 0}}var Z0=4096,al=new Map,eb=1;function le(n,e){n.q.length>=Z0&&(n.overflowed?n.q.splice(1,1):(n.overflowed=!0,n.q.splice(0,2,{type:"warning",message:"genex bridge: event queue full; drain it every frame (oldest events dropped)"}))),n.q.push(e)}var cl=n=>n.closed?null:n.mm?n.mm.session:n.session,ll=n=>{let e=zt(n)||n instanceof Error?n.code:void 0;return typeof e=="number"&&Number.isFinite(e)?e:0},ta=n=>n instanceof Error?n.message:typeof n=="string"?n:"join failed";function ei(n){n.closed=!0,n.connected=!1;for(let e of n.unwire.splice(0))e();n.wired=null,n.session=null,n.mm=null}function Yh(n,e){if(n.wired===e)return;for(let o of n.unwire.splice(0))o();n.wired=e,n.connected=!0,n.lastConnected.clear(),n.lastMatch="";let t=cn(e);n.sessionId=e.id,n.roomId=t.roomId;let r=n.unwire,s=o=>t.state?.players?.get(o)?.connected!==!1,i=o=>{let a=s(o),c=n.lastConnected.get(o);n.lastConnected.set(o,a),c!==void 0&&c!==a&&le(n,{type:"playerConnection",id:o,connected:a})};le(n,{type:"joined",sessionId:e.id}),t.state?.players?.forEach((o,a)=>{n.lastConnected.set(a,s(a)),le(n,{type:"playerJoined",id:a})});for(let o of e.objects.ids())le(n,{type:"objectChanged",id:o,owner:e.objects.get(o)?.owner??null});e.host!==void 0&&le(n,{type:"hostChanged",host:e.host}),r.push(e.on("join",o=>{n.lastConnected.set(o,s(o)),le(n,{type:"playerJoined",id:o})}),e.on("change",o=>{i(o),n.changed.has(o)||(n.changed.add(o),le(n,{type:"playerChanged",id:o}))}),e.on("leave",o=>{n.lastConnected.delete(o),le(n,{type:"playerLeft",id:o})}),e.on("host",o=>le(n,{type:"hostChanged",host:o??null})),e.on("shared",(o,a)=>le(n,{type:"sharedChanged",key:o,value:a??null})),e.on("object",o=>{let a=e.objects.get(o);le(n,a?{type:"objectChanged",id:o,owner:a.owner??null}:{type:"objectRemoved",id:o})}),e.on("room:open",({open:o})=>le(n,{type:"roomOpen",open:o})),e.on("reconnecting",({attempt:o,code:a})=>{n.connected=!1,le(n,{type:"reconnecting",code:a,attempt:o})}),e.on("reconnected",()=>{n.connected=!0,le(n,{type:"reconnected"})}),e.on("disconnect",o=>{n.connected=!1,n.opts.room!=="queue"&&(ei(n),le(n,{type:"disconnected",code:o,reason:""}))}),e.on(ne.SERVER_RESTART,()=>le(n,{type:"serverRestart"})),e.on(ne.MATCH_START,o=>le(n,{type:"matchStart",roundId:zt(o)&&typeof o.roundId=="number"?o.roundId:0})),e.on(ne.MATCH_ENDED,o=>le(n,{type:"matchEnded",data:o??null})),e.on(ne.MATCH_REQUEUE,o=>le(n,{type:"matchRequeue",reason:zt(o)&&typeof o.reason=="string"?o.reason:null})),e.inputs.on((o,a)=>le(n,{type:"input",from:o,data:a??null})),e.chat.on(o=>le(n,{type:"chat",id:o.id,from:o.from,name:o.name,text:o.text,at:o.at})),t.onMessage(ne.RATE_DROP,o=>le(n,{type:"rateDrop",dropped:zt(o)&&typeof o.dropped=="number"?o.dropped:0})),t.onMessage("*",(o,a)=>{typeof o=="string"&&!Qs(o)&&le(n,{type:"message",kind:o,data:a??null})}))}function ea(n){let e=cl(n);e&&e!==n.wired&&Yh(n,e)}async function tb(n){let e=n.opts;if(await Zo.ready(e.gameId),n.closed)return;let t=e.urls.length?e.urls:Zo.urls();if(!t.length)throw Object.assign(new Error("genex bridge: no relay URL (pass urls, or run on a Genex page)"),{code:0});let r=()=>Zo.auth(),s={urls:t,room:e.gameId,name:e.name,auth:r,pose:e.pose,smoothing:e.smoothing};if(e.room==="play"){let a=await Uh({...s,options:e.options});if(n.closed)return void a.leave();n.session=a,Yh(n,a);return}let i=s,o=e.room==="queue"?await Gh(i):e.room==="private"?await zh(i):await Wh(e.room.joinById,i);if(n.closed)return void o.cancel();n.mm=o,o.on("queue",a=>{zt(a)&&le(n,{type:"queue",position:Number(a.position)||0,size:Number(a.size)||0})}),o.on("matched",()=>{le(n,{type:"seated"}),ea(n)}),o.on("searching",()=>{if(n.wired){for(let a of n.unwire.splice(0))a();n.wired=null,n.connected=!1}}),o.on("error",a=>{let c=n.mm;ei(n),c?.cancel(),le(n,{type:"joinFailed",code:ll(a),message:ta(a)})}),o.on("disconnect",a=>{ei(n),le(n,{type:"disconnected",code:typeof a=="number"?a:0,reason:""})}),ea(n)}function Xh(n){let e=Q0(n),t=eb++,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};al.set(t,r);let s=tb(r).catch(i=>{throw ei(r),le(r,{type:"joinFailed",code:ll(i),message:ta(i)}),i});return{handle:t,done:s}}function nb(n){let{handle:e,done:t}=Xh(n);return t.catch(()=>{}),e}async function rb(n){let{handle:e,done:t}=Xh(n);try{await t}catch(r){let s=new Error(ta(r));throw s.code=ll(r),s}return e}var An=n=>al.get(n),qe=n=>{let e=An(n);return e?(ea(e),cl(e)):null};function na(n,e){if(typeof n!="string")throw new TypeError(`genex bridge: ${e} must be a JSON string`);return JSON.parse(n)}function ra(n,e){let t=na(n,e);if(!zt(t))throw new TypeError(`genex bridge: ${e} must be a JSON object`);return t}function Qh(n){let e=An(n);if(!e||e.closed)return;let{mm:t,session:r}=e;ei(e),t?t.cancel():r?.leave(),le(e,{type:"disconnected",code:4e3,reason:"left"})}function sb(n){Qh(n),typeof n=="number"&&al.delete(n)}function ib(n,e){let t=ra(e,"state"),r=qe(n);return r?(r.me.set(t),!0):!1}function ob(n,e){let t=ra(e,"state"),r=qe(n);return r?(r.me.snap(t),!0):!1}function ab(n,e,t){let r=na(t,"value");if(typeof e!="string"||!e||e.startsWith(qo))return!1;let s=qe(n);return s?(s.shared.set(e,r),!0):!1}function cb(n,e,t){let r=ra(t,"object state"),s=qe(n);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.set(e,r),!0)}function lb(n,e,t){let r=ra(t,"object state"),s=qe(n);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.snap(e,r),!0)}function ub(n,e,t){let r=na(t,"event data");if(typeof e!="string"||!e||e.length>vn.MAX_EVENT_TYPE_CHARS||Qs(e))return!1;let s=qe(n);return s?(s.send(e,r),!0):!1}function db(n,e){}function fb(n,e){let t=na(e,"input"),r=qe(n);return r?(r.inputs.send(t),!0):!1}function hb(n,e){let t=qe(n);return t?(t.setRoomOpen(e===!0),!0):!1}function pb(n,e){let t=qe(n);return!t||typeof e!="string"?!1:(t.chat.send(e),!0)}function sa(n,e,t,r,s=!1){if(typeof t!="string"||!t)throw new TypeError("genex bridge: object id must be a non-empty string");let i=An(n),o=qe(n),a=d=>{if(!i)return;let h={type:"controlResult",requestId:String(r),operation:e,id:t,accepted:d.accepted,owner:d.owner??null,sequence:d.sequence,reason:d.reason};typeof d.retryAfterMs=="number"&&(h.retryAfterMs=d.retryAfterMs),le(i,h)};if(!o){a({accepted:!1,sequence:0,reason:"disconnected"});return}let c={timeoutMs:i?.opts.controlTimeoutMs,...s?{authority:"host"}:{}};(e==="claim"?o.objects.claimConfirmed(t,c):e==="release"?o.objects.releaseConfirmed(t,c):o.objects.removeConfirmed(t,c)).then(a,()=>a({accepted:!1,sequence:0,reason:"disconnected"}))}function mb(n,e,t){sa(n,"claim",e,t)}function gb(n,e,t){sa(n,"claim",e,t,!0)}function yb(n,e,t){sa(n,"release",e,t)}function bb(n,e,t){sa(n,"remove",e,t)}function wb(n){let e=An(n);return!e?.mm||e.closed?!1:(e.mm.eliminated(),!0)}function _b(n,e=1){let t=An(n);return!t?.mm||t.closed||typeof e!="number"||!Number.isFinite(e)?!1:(t.mm.score(e),!0)}function Eb(n){let e=An(n);return!e?.mm||e.closed?!1:(e.mm.finish(),!0)}function Rb(n){return qe(n)?.serverNow()??null}function xb(n,e){let t=qe(n);return t?t.timeUntil(e):e-Date.now()}var Jh=n=>typeof n=="number"&&Number.isFinite(n)?n:null;function Sb(n){let e=An(n),t=qe(n),r=t?cn(t):null,s=r?.state?.match,i=null;if(s)try{i=JSON.parse(s)}catch{i=null}return JSON.stringify({sessionId:t?.id??e?.sessionId??"",roomId:r?.roomId??e?.roomId??"",hostId:t?.host??null,isHost:t?.isHost??!1,connected:!!t&&!!e?.connected,closed:!e||e.closed,serverNow:Jh(t?.serverNow()),rtt:Jh(t?.rtt),clockSynced:t?.clockSynced??!1,clockOrigin:r?.state?.clockOrigin??0,matchState:i})}function Tb(n){let e=qe(n);if(!e)return"[]";let t=cn(e).state?.players,r=[];for(let[s,i]of e.players){let o=t?.get(s);r.push({id:s,name:i.name,uid:i.uid,team:i.team,connected:i.connected,avatarUrl:i.avatarUrl,state:i.state??{},stateRaw:i.stateRaw??{},epoch:o?.epoch??0,isMe:s===e.id,posed:o?.posed===!0})}return JSON.stringify(r)}function kb(n){let e=qe(n);if(!e)return"[]";let t=cn(e).state?.objects,r=[];for(let s of e.objects.ids()){let i=e.objects.get(s);i&&r.push({id:s,owner:i.owner??null,isMine:i.isMine,seq:t?.get(s)?.seq??0,epoch:i.epoch,state:i.state??null,stateRaw:i.stateRaw??null})}return JSON.stringify(r)}function vb(n){let e=qe(n),t={};if(e)for(let r of e.shared.keys())t[r]=e.shared.get(r)??null;return JSON.stringify(t)}function Ab(n){let e=An(n);if(!e)return"[]";try{ea(e);let t=cl(e);if(t){let r=cn(t).state?.match??"";if(r!==e.lastMatch){e.lastMatch=r;let s=null;try{s=r?JSON.parse(r):null}catch{s=null}le(e,{type:"matchState",state:s})}}return e.changed.clear(),e.overflowed=!1,JSON.stringify(e.q.splice(0))}catch(t){return JSON.stringify([{type:"warning",message:`genex bridge: ${ta(t)}`}])}}var Cb=Object.freeze({...ul,initEmbed:Ci});globalThis.GenexMultiplayerBridge=Cb;})();
|