@idosgames/core 0.19.0 → 0.19.1

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.
@@ -1 +1 @@
1
- 'use strict';function m(n,e){return {ok:false,reason:n,error:e}}var f=16384;function g(n){let e=new Uint8Array(n.byteLength+1);return e[0]=0,e.set(n,1),e}function v(n,e){if(n.byteLength+1<=16384)return [g(n)];if(n.byteLength>67108864)throw new RangeError(`Message of ${n.byteLength} bytes exceeds 67108864.`);let s=Math.ceil(n.byteLength/16375),t=[];for(let i=0;i<s;i++){let r=n.subarray(i*16375,Math.min(n.byteLength,(i+1)*16375)),o=new Uint8Array(9+r.byteLength),a=new DataView(o.buffer);o[0]=1,a.setUint32(1,e>>>0),a.setUint16(5,i),a.setUint16(7,s),o.set(r,9),t.push(o);}return t}var p=class{id=-1;count=0;parts=[];bytes=0;push(e){if(e.byteLength<9)return null;let s=new DataView(e.buffer,e.byteOffset,e.byteLength),t=s.getUint32(1),i=s.getUint16(5),r=s.getUint16(7);if(i===0&&(this.id=t,this.count=r,this.parts=[],this.bytes=0),t!==this.id||i!==this.parts.length||r!==this.count)return this.reset(),null;let o=e.subarray(9);if(this.bytes+=o.byteLength,this.bytes>67108864)return this.reset(),null;if(this.parts.push(o),this.parts.length<this.count)return null;let a=new Uint8Array(this.bytes),l=0;for(let h of this.parts)a.set(h,l),l+=h.byteLength;return this.reset(),a}reset(){this.id=-1,this.count=0,this.parts=[],this.bytes=0;}};function c(n){let e=new Map;for(let s of n??[]){let t=s.Urls?.trim();if(!t)continue;let i=s.Username??void 0,r=s.Credential??void 0,o=`${i??""}\0${r??""}`,a=e.get(o);if(a){let h=Array.isArray(a.urls)?a.urls:[a.urls];h.includes(t)||h.push(t),a.urls=h;continue}let l={urls:[t]};i&&(l.username=i),r&&(l.credential=r),e.set(o,l);}return [...e.values()]}var C=4*1024*1024,A=5e3,d=class{constructor(e){this.o=e;this.peerId=e.peerId,this.offerer=e.offerer,this.lid=e.lid,this.pc=e.createPeerConnection({iceServers:e.iceServers}),this.pc.onicecandidate=s=>{if(!s.candidate){this.sendDescriptionIfReady();return}this.descriptionSent&&this.lateIce.push(s.candidate.toJSON()),this.flushLateIce();},this.pc.onconnectionstatechange=()=>{let s=this.pc.connectionState;(s==="failed"||s==="closed")&&this.close(`connection ${s}`);},this.pc.ondatachannel=s=>this.adopt(s.channel),this.openTimer=setTimeout(()=>{this.state==="connecting"&&this.close("connect timeout");},Math.max(15e3,e.peerTimeoutMs*3)),this.offerer&&(this.adopt(this.pc.createDataChannel("rel",{ordered:true})),this.adopt(this.pc.createDataChannel("fast",{ordered:false,maxRetransmits:0})),this.makeOffer());}o;peerId;offerer;lid;state="connecting";pc;rel=null;fast=null;reassembler=new p;pendingRemoteIce=[];descriptionSent=false;lateIce=[];lastRecv=Date.now();lastSend=0;msgSeq=1;keepaliveTimer=null;gatherTimer=null;openTimer=null;bytesIn=0;bytesOut=0;rttMs=0;pingSentAt=0;async makeOffer(){try{await this.pc.setLocalDescription(await this.pc.createOffer()),this.waitForGathering();}catch(e){this.close(`offer failed: ${String(e)}`);}}async handle(e){if(this.state!=="closed")try{if(e.t==="offer"&&!this.offerer)await this.pc.setRemoteDescription({type:"offer",sdp:e.sdp}),await this.drainRemoteIce(),await this.pc.setLocalDescription(await this.pc.createAnswer()),this.waitForGathering();else if(e.t==="answer"&&this.offerer){if(this.pc.signalingState!=="have-local-offer")return;await this.pc.setRemoteDescription({type:"answer",sdp:e.sdp}),await this.drainRemoteIce();}else if(e.t==="ice")if(!this.pc.remoteDescription)this.pendingRemoteIce.push(...e.c);else for(let s of e.c)await this.addIce(s);else e.t==="bye"&&this.close("peer closed the link");}catch(s){this.close(`signaling failed: ${String(s)}`);}}async drainRemoteIce(){let e=this.pendingRemoteIce.splice(0);for(let s of e)await this.addIce(s);}async addIce(e){try{await this.pc.addIceCandidate(e);}catch{}}waitForGathering(){if(this.pc.iceGatheringState==="complete"){this.sendDescriptionIfReady();return}this.gatherTimer=setTimeout(()=>this.sendDescriptionIfReady(),this.o.iceGatherTimeoutMs);}sendDescriptionIfReady(){if(this.descriptionSent||this.state==="closed")return;let e=this.pc.localDescription;e?.sdp&&(this.gatherTimer&&clearTimeout(this.gatherTimer),this.gatherTimer=null,this.descriptionSent=true,this.o.signal(this.offerer?{t:"offer",lid:this.lid,sdp:e.sdp}:{t:"answer",lid:this.lid,sdp:e.sdp}),this.flushLateIce());}flushLateIce(){if(!this.descriptionSent||this.lateIce.length===0)return;let e=this.lateIce;this.lateIce=[],this.o.signal({t:"ice",lid:this.lid,c:e});}adopt(e){if(e.binaryType="arraybuffer",e.label==="rel")this.rel=e;else if(e.label==="fast")this.fast=e;else return;e.onopen=()=>this.maybeOpen(),e.onclose=()=>this.close(`channel ${e.label} closed`),e.onmessage=s=>this.receive(e.label,s.data),e.readyState==="open"&&queueMicrotask(()=>this.maybeOpen());}maybeOpen(){this.state==="connecting"&&(this.rel?.readyState!=="open"||this.fast?.readyState!=="open"||(this.state="open",this.openTimer&&clearTimeout(this.openTimer),this.openTimer=null,this.lastRecv=Date.now(),this.keepaliveTimer=setInterval(()=>this.keepalive(),this.o.keepaliveMs),this.o.onOpen()));}keepalive(){if(this.state!=="open")return;let e=Date.now();if(e-this.lastRecv>this.o.peerTimeoutMs){this.close("peer timeout");return}(e-this.lastSend>=this.o.keepaliveMs||e-this.pingSentAt>=A)&&(this.pingSentAt=e,this.raw("fast",new Uint8Array([2])));}receive(e,s){if(!(s instanceof ArrayBuffer))return;let t=new Uint8Array(s);this.lastRecv=Date.now(),this.bytesIn+=t.byteLength;let i=t[0];if(i===0)this.o.onMessage(e,t.subarray(1));else if(i===1&&e==="rel"){let r=this.reassembler.push(t);r&&this.o.onMessage(e,r);}else i===2?this.raw("fast",new Uint8Array([3])):i===3?this.pingSentAt&&(this.rttMs=Date.now()-this.pingSentAt):i===4&&e==="rel"&&this.o.onNotice?.(t[1]??0);}send(e,s){if(this.state!=="open")return false;if(e==="fast")return s.byteLength+1>16384?false:this.raw("fast",g(s));if((this.rel?.bufferedAmount??0)>C)return false;let t=v(s,this.msgSeq++);for(let i of t)if(!this.raw("rel",i))return false;return true}notice(e){return this.state!=="open"?false:this.raw("rel",new Uint8Array([4,e]))}get relBuffered(){return this.rel?.bufferedAmount??0}raw(e,s){let t=e==="rel"?this.rel:this.fast;if(!t||t.readyState!=="open")return false;try{return t.send(s),this.lastSend=Date.now(),this.bytesOut+=s.byteLength,!0}catch{return false}}close(e="closed",s=false){if(this.state!=="closed"){this.state="closed",s&&this.descriptionSent&&this.o.signal({t:"bye",lid:this.lid}),this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.gatherTimer&&clearTimeout(this.gatherTimer),this.openTimer&&clearTimeout(this.openTimer),this.keepaliveTimer=this.gatherTimer=this.openTimer=null;for(let t of [this.rel,this.fast])if(t){t.onopen=t.onclose=t.onmessage=null;try{t.close();}catch{}}this.pc.onicecandidate=this.pc.onconnectionstatechange=this.pc.ondatachannel=null;try{this.pc.close();}catch{}this.reassembler.reset(),this.o.onClose(e);}}};function R(n){if(!n)return [];try{let e=JSON.parse(n);return !e||e.v!==1||!Array.isArray(e.m)?[]:e.m.filter(s=>!!s&&typeof s=="object"&&typeof s.t=="string")}catch{return []}}var u=class{constructor(e,s={}){this.send=e;this.perTargetGapMs=s.perTargetGapMs??650,this.globalGapMs=s.globalGapMs??180,this.maxPayloadBytes=s.maxPayloadBytes??15e3,this.maxAttempts=s.maxAttempts??4;}send;queues=new Map;lastSent=new Map;lastAny=0;inflight=false;timer=null;closed=false;perTargetGapMs;globalGapMs;maxPayloadBytes;maxAttempts;get busy(){return this.inflight||this.queues.size>0}enqueue(e,s){if(this.closed)return;let t=this.queues.get(e)??{msgs:[],attempts:0},i=t.msgs[t.msgs.length-1];s.t==="ice"&&i?.t==="ice"&&i.lid===s.lid?i.c.push(...s.c):t.msgs.push(s),this.queues.set(e,t),this.pump();}forget(e){this.queues.delete(e),this.lastSent.delete(e);}close(){this.closed=true,this.queues.clear(),this.timer&&clearTimeout(this.timer),this.timer=null;}pump(){if(this.closed||this.inflight||this.timer)return;let e=Date.now(),s=null,t=1/0;for(let i of this.queues.keys()){let r=Math.max((this.lastSent.get(i)??0)+this.perTargetGapMs,this.lastAny+this.globalGapMs);if(r<=e){s=i;break}t=Math.min(t,r-e);}if(s===null){t!==1/0&&(this.timer=setTimeout(()=>{this.timer=null,this.pump();},t));return}this.flush(s);}async flush(e){let s=this.queues.get(e);if(!s||s.msgs.length===0){this.queues.delete(e),this.pump();return}let t=[],i="";for(let l of s.msgs){let h=JSON.stringify({v:1,m:[...t,l]});if(t.length>0&&E(h)>this.maxPayloadBytes)break;t.push(l),i=h;}let r=s.msgs.slice(t.length);r.length?this.queues.set(e,{msgs:r,attempts:0}):this.queues.delete(e),this.inflight=true;let o=null;try{o=await this.send(e,"rtc",i);}catch{o=null;}this.inflight=false;let a=Date.now();if(this.lastSent.set(e,a),this.lastAny=a,!o?.ok&&!this.closed){let l=o?.ok===false?o.reason:"connection";if((l==="throttled"||l==="connection")&&s.attempts+1<this.maxAttempts){let T=this.queues.get(e);this.queues.set(e,{msgs:[...t,...T?.msgs??[]],attempts:s.attempts+1});}}this.pump();}};function E(n){return new TextEncoder().encode(n).byteLength}var O={pollFastMs:1e3,pollHostIdleMs:2500,pollClientIdleMs:2e4,fastWindowMs:15e3,keepaliveMs:1e3,peerTimeoutMs:6e3,iceGatherTimeoutMs:1200,maxSignalPayloadBytes:15e3,signalPerTargetGapMs:650,signalGlobalGapMs:180},y=class n{constructor(e,s,t,i){this.client=e;this.selfId=s,this.roomId=t.RoomID??"",this.topology=t.Topology??"Mesh",this.chatMode=t.ChatMode??"ServerRelay",this.ownerId=t.OwnerUserID??"",this.hostId=t.HostUserID??"",this.lastSeq=t.Seq??0,this.iceServers=c(t.IceServers),this.o={...O,leaveOnPageHide:true,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0)),createPeerConnection:i.createPeerConnection??(r=>new RTCPeerConnection(r))};for(let r of t.Members??[])r.UserID&&this.members.set(r.UserID,r);this.outbox=new u((r,o,a)=>this.client.multiplayer.sendSignal(this.roomId,r,o,a),{maxPayloadBytes:this.o.maxSignalPayloadBytes,perTargetGapMs:this.o.signalPerTargetGapMs,globalGapMs:this.o.signalGlobalGapMs}),this.fastUntil=Date.now()+this.o.fastWindowMs,this.o.leaveOnPageHide&&typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide);}client;roomId;selfId;topology;chatMode;ownerId;hostId;members=new Map;o;iceServers;lastSeq;links=new Map;everOpen=new Set;retry=new Map;wantSentAt=new Map;extraPeers=new Set;outbox;pollTimer=null;polling=false;pollSoonMs=null;pollBackoff=0;fastUntil=0;refreshTimer=null;stopped=false;successor=null;listeners=new Map;onPageHide=()=>this.leaveOnUnload();static async create(e,s,t={},i={}){let r=e.auth.context?.userID;if(!r)return m("unauthorized","Not logged in.");let o=await e.multiplayer.createRoom(s,t);return o.ok?{ok:true,data:n.start(e,r,o.data,i)}:o}static async join(e,s,t,i={}){let r=e.auth.context?.userID;if(!r)return m("unauthorized","Not logged in.");let o=await e.multiplayer.joinRoom(s,t);return o.ok?{ok:true,data:n.start(e,r,o.data,i)}:o}static start(e,s,t,i){let r=new n(e,s,t,i);return r.reconcile(),r.schedulePoll(0),r}get isHost(){return this.hostId===this.selfId}get isOwner(){return this.ownerId===this.selfId}get closed(){return this.stopped}on(e,s){let t=this.listeners.get(e)??new Set;return t.add(s),this.listeners.set(e,t),()=>t.delete(s)}openPeers(){return [...this.links.values()].filter(e=>e.state==="open").map(e=>e.peerId)}isOpen(e){return this.links.get(e)?.state==="open"}linkStats(e){let s=this.links.get(e);return s?{rttMs:s.rttMs,bytesIn:s.bytesIn,bytesOut:s.bytesOut,buffered:s.relBuffered}:null}send(e,s,t){return this.links.get(e)?.send(s,t)??false}broadcast(e,s,t){let i=0;for(let r of this.links.values())r.peerId!==t&&r.state==="open"&&r.send(e,s)&&i++;return i}setExtraPeers(e){this.extraPeers=new Set([...e].filter(s=>s!==this.selfId)),this.reconcile();}setSuccessor(e){this.successor=e&&e!==this.selfId?e:null;}async claimHost(){let e=await this.client.multiplayer.claimHost(this.roomId);return e.ok&&this.applySnapshot(e.data),e}async kick(e,s=false){let t=await this.client.multiplayer.kickMember(this.roomId,e,s);return t.ok&&this.links.get(e)?.notice(1),t}unban(e){return this.client.multiplayer.unbanMember(this.roomId,e)}async leave(){if(this.stopped)return;let e=this.isHost?this.successor??void 0:void 0;this.stop(),await this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e});}async refreshMembers(){let e=await this.client.multiplayer.getRoom(this.roomId);e.ok&&this.applySnapshot(e.data);}schedulePoll(e){if(!this.stopped){if(this.polling){this.pollSoonMs=Math.min(this.pollSoonMs??e,e);return}this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=setTimeout(()=>{this.pollOnce();},e);}}nextPollDelay(){return Date.now()<this.fastUntil||this.outbox.busy||[...this.links.values()].some(s=>s.state==="connecting")||[...this.wanted()].some(s=>!this.links.has(s))?this.o.pollFastMs:this.isHost?this.o.pollHostIdleMs:this.o.pollClientIdleMs}async pollOnce(){if(this.stopped)return;this.pollTimer=null,this.polling=true,this.pollSoonMs=null;let e=await this.client.multiplayer.poll(this.roomId,this.lastSeq);if(this.polling=false,this.stopped)return;let s=this.pollSoonMs;if(this.pollSoonMs=null,e.ok){this.pollBackoff=0;for(let t of e.data.Envelopes??[])this.handleEnvelope(t);this.lastSeq=e.data.MaxSeq??this.lastSeq,this.reconcile(),this.schedulePoll(Math.min(this.nextPollDelay(),s??1/0));return}if(e.reason==="server"){let t=e.error??"";if(/not a member/i.test(t))return this.end("removed",{reason:t});if(/no longer exists|not found/i.test(t))return this.end("roomClosed",{});if(/disabled/i.test(t))return this.end("roomClosed",{})}this.pollBackoff=Math.min(this.pollBackoff+1,5),this.schedulePoll(this.o.pollFastMs*(1+this.pollBackoff));}handleEnvelope(e){let s=e.FromUserID??"";switch(e.Type){case "Signal":e.ToUserID===this.selfId&&e.Kind==="rtc"&&this.handleSignals(s,R(e.Payload));break;case "PlayerJoined":{let t=e.Payload||s;if(!t||t===this.selfId)break;if(!this.members.has(t)){let i={UserID:t};this.members.set(t,i),this.emit("memberJoined",{member:i});}this.fastUntil=Date.now()+this.o.fastWindowMs,this.scheduleRefresh();break}case "PlayerLeft":{let t=e.Payload||s,i=e.Kind==="kicked"?"kicked":e.Kind==="timeout"?"timeout":"left";if(t===this.selfId){i!=="left"&&this.end("removed",{reason:i});break}this.dropMember(t,i,i==="kicked"?s:void 0);break}case "HostChanged":{let t=e.Payload??"";if(t&&t!==this.hostId){let i=this.hostId||null;this.hostId=t,this.fastUntil=Date.now()+this.o.fastWindowMs,this.emit("hostChanged",{hostId:t,previousHostId:i});}break}case "RoomClosed":this.end("roomClosed",{});break;case "MemberState":this.scheduleRefresh();break;case "Chat":this.emit("chat",{from:s,text:e.Payload??""});break}}dropMember(e,s,t){let i=this.members.delete(e);this.closeLink(e,"member left"),this.outbox.forget(e),this.wantSentAt.delete(e);let r=this.retry.get(e);r?.timer&&clearTimeout(r.timer),this.retry.delete(e),this.extraPeers.delete(e),this.successor===e&&(this.successor=null),i&&this.emit("memberLeft",{userId:e,kind:s,by:t});}scheduleRefresh(){this.refreshTimer||this.stopped||(this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.refreshMembers();},400));}applySnapshot(e){if(this.stopped)return;e.IceServers?.length&&(this.iceServers=c(e.IceServers)),e.OwnerUserID&&(this.ownerId=e.OwnerUserID);let s=new Map;for(let t of e.Members??[])t.UserID&&s.set(t.UserID,t);for(let t of [...this.members.keys()])!s.has(t)&&t!==this.selfId&&this.dropMember(t,"left");for(let[t,i]of s){let r=this.members.has(t);this.members.set(t,i),!r&&t!==this.selfId&&this.emit("memberJoined",{member:i});}if(e.HostUserID&&e.HostUserID!==this.hostId){let t=this.hostId||null;this.hostId=e.HostUserID,this.emit("hostChanged",{hostId:e.HostUserID,previousHostId:t});}this.emit("membersUpdated",{members:[...this.members.values()]}),this.reconcile();}wanted(){let e=new Set,s=[...this.members.keys()].filter(t=>t!==this.selfId);if(this.topology==="Mesh"||this.isHost)for(let t of s)e.add(t);else this.hostId&&this.hostId!==this.selfId&&this.members.has(this.hostId)&&e.add(this.hostId);for(let t of this.extraPeers)this.members.has(t)&&e.add(t);return e}reconcile(){if(this.stopped)return;let e=Date.now();for(let s of this.wanted())if(!(this.links.has(s)||this.retry.get(s)?.timer))if(this.selfId<s)this.openLink(s,true,I());else {let t=this.wantSentAt.get(s)??0;e-t>8e3&&(this.wantSentAt.set(s,e),this.outbox.enqueue(s,{t:"want"}));}}handleSignals(e,s){if(!(!e||e===this.selfId)){this.members.has(e)||(this.members.set(e,{UserID:e}),this.scheduleRefresh());for(let t of s){let i=this.links.get(e);if(t.t==="want"){(!i||i.state==="closed")&&this.openLink(e,true,I());continue}if(t.t==="offer"){if(i?.lid===t.lid)continue;i&&this.closeLink(e,"replaced by a new offer"),this.openLink(e,false,t.lid).handle(t);continue}i&&i.lid===t.lid&&i.handle(t);}}}openLink(e,s,t){this.wantSentAt.delete(e);let i=new d({peerId:e,offerer:s,lid:t,iceServers:this.iceServers,createPeerConnection:this.o.createPeerConnection,signal:r=>this.outbox.enqueue(e,r),iceGatherTimeoutMs:this.o.iceGatherTimeoutMs,keepaliveMs:this.o.keepaliveMs,peerTimeoutMs:this.o.peerTimeoutMs,onOpen:()=>{this.everOpen.add(e),this.retry.delete(e),this.emit("peerOpen",{peerId:e});},onClose:r=>this.onLinkClosed(i,r),onMessage:(r,o)=>this.emit("message",{from:e,channel:r,data:o}),onNotice:r=>{r===1&&this.schedulePoll(0);}});return this.links.set(e,i),this.schedulePoll(Math.min(this.o.pollFastMs,250)),i}closeLink(e,s){let t=this.links.get(e);t&&(this.links.delete(e),t.close(s,true));}onLinkClosed(e,s){let t=e.peerId,i=this.links.get(t)===e;if(i&&this.links.delete(t),this.everOpen.delete(t)&&this.emit("peerClose",{peerId:t,reason:s}),!i||this.stopped||!this.members.has(t)||!this.wanted().has(t))return;let r=this.retry.get(t)??{attempts:0,timer:null},o=Math.min(15e3,1e3*2**r.attempts);r.attempts++,r.timer=setTimeout(()=>{r.timer=null,this.wantSentAt.delete(t),this.reconcile();},o),this.retry.set(t,r);}emit(e,s){for(let t of this.listeners.get(e)??[])try{t(s);}catch(i){console.error(`[RealtimeSession] ${String(e)} handler failed`,i);}}end(e,s){this.stopped||(this.stop(),this.emit(e,s));}stop(){this.stopped=true,this.pollTimer&&clearTimeout(this.pollTimer),this.refreshTimer&&clearTimeout(this.refreshTimer),this.pollTimer=this.refreshTimer=null;for(let e of this.retry.values())e.timer&&clearTimeout(e.timer);this.retry.clear(),this.outbox.close();for(let e of [...this.links.keys()]){let s=this.links.get(e);this.links.delete(e),s?.close("session closed");}typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide);}leaveOnUnload(){if(this.stopped)return;let e=this.isHost?this.successor??void 0:void 0;this.stop(),this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e,keepalive:true});}};function I(){let n=globalThis.crypto;return n&&"randomUUID"in n?n.randomUUID().slice(0,12):Math.random().toString(36).slice(2,14)}exports.MAX_MESSAGE_BYTES=f;exports.RealtimeSession=y;exports.toRtcIceServers=c;
1
+ 'use strict';function m(n,e){return {ok:false,reason:n,error:e}}var f=16384;function g(n){let e=new Uint8Array(n.byteLength+1);return e[0]=0,e.set(n,1),e}function v(n,e){if(n.byteLength+1<=16384)return [g(n)];if(n.byteLength>67108864)throw new RangeError(`Message of ${n.byteLength} bytes exceeds 67108864.`);let s=Math.ceil(n.byteLength/16375),t=[];for(let i=0;i<s;i++){let r=n.subarray(i*16375,Math.min(n.byteLength,(i+1)*16375)),o=new Uint8Array(9+r.byteLength),a=new DataView(o.buffer);o[0]=1,a.setUint32(1,e>>>0),a.setUint16(5,i),a.setUint16(7,s),o.set(r,9),t.push(o);}return t}var p=class{id=-1;count=0;parts=[];bytes=0;push(e){if(e.byteLength<9)return null;let s=new DataView(e.buffer,e.byteOffset,e.byteLength),t=s.getUint32(1),i=s.getUint16(5),r=s.getUint16(7);if(i===0&&(this.id=t,this.count=r,this.parts=[],this.bytes=0),t!==this.id||i!==this.parts.length||r!==this.count)return this.reset(),null;let o=e.subarray(9);if(this.bytes+=o.byteLength,this.bytes>67108864)return this.reset(),null;if(this.parts.push(o),this.parts.length<this.count)return null;let a=new Uint8Array(this.bytes),l=0;for(let h of this.parts)a.set(h,l),l+=h.byteLength;return this.reset(),a}reset(){this.id=-1,this.count=0,this.parts=[],this.bytes=0;}};function c(n){let e=new Map;for(let s of n??[]){let t=s.Urls?.trim();if(!t)continue;let i=s.Username??void 0,r=s.Credential??void 0,o=`${i??""}\0${r??""}`,a=e.get(o);if(a){let h=Array.isArray(a.urls)?a.urls:[a.urls];h.includes(t)||h.push(t),a.urls=h;continue}let l={urls:[t]};i&&(l.username=i),r&&(l.credential=r),e.set(o,l);}return [...e.values()]}var C=4*1024*1024,A=5e3,d=class{constructor(e){this.o=e;this.peerId=e.peerId,this.offerer=e.offerer,this.lid=e.lid,this.pc=e.createPeerConnection({iceServers:e.iceServers}),this.pc.onicecandidate=s=>{if(!s.candidate){this.sendDescriptionIfReady();return}this.descriptionSent&&this.lateIce.push(s.candidate.toJSON()),this.flushLateIce();},this.pc.onconnectionstatechange=()=>{let s=this.pc.connectionState;(s==="failed"||s==="closed")&&this.close(`connection ${s}`);},this.pc.ondatachannel=s=>this.adopt(s.channel),this.openTimer=setTimeout(()=>{this.state==="connecting"&&this.close("connect timeout");},Math.max(15e3,e.peerTimeoutMs*3)),this.offerer&&(this.adopt(this.pc.createDataChannel("rel",{ordered:true})),this.adopt(this.pc.createDataChannel("fast",{ordered:false,maxRetransmits:0})),this.makeOffer());}o;peerId;offerer;lid;state="connecting";pc;rel=null;fast=null;reassembler=new p;pendingRemoteIce=[];descriptionSent=false;lateIce=[];lastRecv=Date.now();lastSend=0;msgSeq=1;keepaliveTimer=null;gatherTimer=null;openTimer=null;bytesIn=0;bytesOut=0;rttMs=0;pingSentAt=0;async makeOffer(){try{await this.pc.setLocalDescription(await this.pc.createOffer()),this.waitForGathering();}catch(e){this.close(`offer failed: ${String(e)}`);}}async handle(e){if(this.state!=="closed")try{if(e.t==="offer"&&!this.offerer)await this.pc.setRemoteDescription({type:"offer",sdp:e.sdp}),await this.drainRemoteIce(),await this.pc.setLocalDescription(await this.pc.createAnswer()),this.waitForGathering();else if(e.t==="answer"&&this.offerer){if(this.pc.signalingState!=="have-local-offer")return;await this.pc.setRemoteDescription({type:"answer",sdp:e.sdp}),await this.drainRemoteIce();}else if(e.t==="ice")if(!this.pc.remoteDescription)this.pendingRemoteIce.push(...e.c);else for(let s of e.c)await this.addIce(s);else e.t==="bye"&&this.close("peer closed the link");}catch(s){this.close(`signaling failed: ${String(s)}`);}}async drainRemoteIce(){let e=this.pendingRemoteIce.splice(0);for(let s of e)await this.addIce(s);}async addIce(e){try{await this.pc.addIceCandidate(e);}catch{}}waitForGathering(){if(this.pc.iceGatheringState==="complete"){this.sendDescriptionIfReady();return}this.gatherTimer=setTimeout(()=>this.sendDescriptionIfReady(),this.o.iceGatherTimeoutMs);}sendDescriptionIfReady(){if(this.descriptionSent||this.state==="closed")return;let e=this.pc.localDescription;e?.sdp&&(this.gatherTimer&&clearTimeout(this.gatherTimer),this.gatherTimer=null,this.descriptionSent=true,this.o.signal(this.offerer?{t:"offer",lid:this.lid,sdp:e.sdp}:{t:"answer",lid:this.lid,sdp:e.sdp}),this.flushLateIce());}flushLateIce(){if(!this.descriptionSent||this.lateIce.length===0)return;let e=this.lateIce;this.lateIce=[],this.o.signal({t:"ice",lid:this.lid,c:e});}adopt(e){if(e.binaryType="arraybuffer",e.label==="rel")this.rel=e;else if(e.label==="fast")this.fast=e;else return;e.onopen=()=>this.maybeOpen(),e.onclose=()=>this.close(`channel ${e.label} closed`),e.onmessage=s=>this.receive(e.label,s.data),e.readyState==="open"&&queueMicrotask(()=>this.maybeOpen());}maybeOpen(){this.state==="connecting"&&(this.rel?.readyState!=="open"||this.fast?.readyState!=="open"||(this.state="open",this.openTimer&&clearTimeout(this.openTimer),this.openTimer=null,this.lastRecv=Date.now(),this.keepaliveTimer=setInterval(()=>this.keepalive(),this.o.keepaliveMs),this.o.onOpen()));}keepalive(){if(this.state!=="open")return;let e=Date.now();if(e-this.lastRecv>this.o.peerTimeoutMs){this.close("peer timeout");return}(e-this.lastSend>=this.o.keepaliveMs||e-this.pingSentAt>=A)&&(this.pingSentAt=e,this.raw("fast",new Uint8Array([2])));}receive(e,s){if(!(s instanceof ArrayBuffer))return;let t=new Uint8Array(s);this.lastRecv=Date.now(),this.bytesIn+=t.byteLength;let i=t[0];if(i===0)this.o.onMessage(e,t.subarray(1));else if(i===1&&e==="rel"){let r=this.reassembler.push(t);r&&this.o.onMessage(e,r);}else i===2?this.raw("fast",new Uint8Array([3])):i===3?this.pingSentAt&&(this.rttMs=Date.now()-this.pingSentAt):i===4&&e==="rel"&&this.o.onNotice?.(t[1]??0);}send(e,s){if(this.state!=="open")return false;if(e==="fast")return s.byteLength+1>16384?false:this.raw("fast",g(s));if((this.rel?.bufferedAmount??0)>C)return false;let t=v(s,this.msgSeq++);for(let i of t)if(!this.raw("rel",i))return false;return true}notice(e){return this.state!=="open"?false:this.raw("rel",new Uint8Array([4,e]))}get relBuffered(){return this.rel?.bufferedAmount??0}raw(e,s){let t=e==="rel"?this.rel:this.fast;if(!t||t.readyState!=="open")return false;try{return t.send(s),this.lastSend=Date.now(),this.bytesOut+=s.byteLength,!0}catch{return false}}close(e="closed",s=false){if(this.state!=="closed"){this.state="closed",s&&this.descriptionSent&&this.o.signal({t:"bye",lid:this.lid}),this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.gatherTimer&&clearTimeout(this.gatherTimer),this.openTimer&&clearTimeout(this.openTimer),this.keepaliveTimer=this.gatherTimer=this.openTimer=null;for(let t of [this.rel,this.fast])if(t){t.onopen=t.onclose=t.onmessage=null;try{t.close();}catch{}}this.pc.onicecandidate=this.pc.onconnectionstatechange=this.pc.ondatachannel=null;try{this.pc.close();}catch{}this.reassembler.reset(),this.o.onClose(e);}}};function R(n){if(!n)return [];try{let e=JSON.parse(n);return !e||e.v!==1||!Array.isArray(e.m)?[]:e.m.filter(s=>!!s&&typeof s=="object"&&typeof s.t=="string")}catch{return []}}var u=class{constructor(e,s={}){this.send=e;this.perTargetGapMs=s.perTargetGapMs??650,this.globalGapMs=s.globalGapMs??180,this.maxPayloadBytes=s.maxPayloadBytes??15e3,this.maxAttempts=s.maxAttempts??4;}send;queues=new Map;lastSent=new Map;lastAny=0;inflight=false;timer=null;closed=false;perTargetGapMs;globalGapMs;maxPayloadBytes;maxAttempts;get busy(){return this.inflight||this.queues.size>0}enqueue(e,s){if(this.closed)return;let t=this.queues.get(e)??{msgs:[],attempts:0},i=t.msgs[t.msgs.length-1];s.t==="ice"&&i?.t==="ice"&&i.lid===s.lid?i.c.push(...s.c):t.msgs.push(s),this.queues.set(e,t),this.pump();}forget(e){this.queues.delete(e),this.lastSent.delete(e);}close(){this.closed=true,this.queues.clear(),this.timer&&clearTimeout(this.timer),this.timer=null;}pump(){if(this.closed||this.inflight||this.timer)return;let e=Date.now(),s=null,t=1/0;for(let i of this.queues.keys()){let r=Math.max((this.lastSent.get(i)??0)+this.perTargetGapMs,this.lastAny+this.globalGapMs);if(r<=e){s=i;break}t=Math.min(t,r-e);}if(s===null){t!==1/0&&(this.timer=setTimeout(()=>{this.timer=null,this.pump();},t));return}this.flush(s);}async flush(e){let s=this.queues.get(e);if(!s||s.msgs.length===0){this.queues.delete(e),this.pump();return}let t=[],i="";for(let l of s.msgs){let h=JSON.stringify({v:1,m:[...t,l]});if(t.length>0&&E(h)>this.maxPayloadBytes)break;t.push(l),i=h;}let r=s.msgs.slice(t.length);r.length?this.queues.set(e,{msgs:r,attempts:0}):this.queues.delete(e),this.inflight=true;let o=null;try{o=await this.send(e,"rtc",i);}catch{o=null;}this.inflight=false;let a=Date.now();if(this.lastSent.set(e,a),this.lastAny=a,!o?.ok&&!this.closed){let l=o?.ok===false?o.reason:"connection";if((l==="throttled"||l==="connection")&&s.attempts+1<this.maxAttempts){let T=this.queues.get(e);this.queues.set(e,{msgs:[...t,...T?.msgs??[]],attempts:s.attempts+1});}}this.pump();}};function E(n){return new TextEncoder().encode(n).byteLength}var O={pollFastMs:1e3,pollHostIdleMs:2500,pollClientIdleMs:2e4,fastWindowMs:15e3,keepaliveMs:1e3,peerTimeoutMs:6e3,iceGatherTimeoutMs:1200,maxSignalPayloadBytes:15e3,signalPerTargetGapMs:650,signalGlobalGapMs:180},y=class n{constructor(e,s,t,i){this.client=e;this.selfId=s,this.roomId=t.RoomID??"",this.topology=t.Topology??"Mesh",this.chatMode=t.ChatMode??"ServerRelay",this.mode=t.Mode??null,this.ownerId=t.OwnerUserID??"",this.hostId=t.HostUserID??"",this.lastSeq=t.Seq??0,this.iceServers=c(t.IceServers),this.o={...O,leaveOnPageHide:true,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0)),createPeerConnection:i.createPeerConnection??(r=>new RTCPeerConnection(r))};for(let r of t.Members??[])r.UserID&&this.members.set(r.UserID,r);this.outbox=new u((r,o,a)=>this.client.multiplayer.sendSignal(this.roomId,r,o,a),{maxPayloadBytes:this.o.maxSignalPayloadBytes,perTargetGapMs:this.o.signalPerTargetGapMs,globalGapMs:this.o.signalGlobalGapMs}),this.fastUntil=Date.now()+this.o.fastWindowMs,this.o.leaveOnPageHide&&typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide);}client;roomId;selfId;topology;chatMode;mode;ownerId;hostId;members=new Map;o;iceServers;lastSeq;links=new Map;everOpen=new Set;retry=new Map;wantSentAt=new Map;extraPeers=new Set;outbox;pollTimer=null;polling=false;pollSoonMs=null;pollBackoff=0;fastUntil=0;refreshTimer=null;stopped=false;successor=null;listeners=new Map;onPageHide=()=>this.leaveOnUnload();static async create(e,s,t={},i={}){let r=e.auth.context?.userID;if(!r)return m("unauthorized","Not logged in.");let o=await e.multiplayer.createRoom(s,t);return o.ok?{ok:true,data:n.start(e,r,o.data,i)}:o}static async join(e,s,t,i={}){let r=e.auth.context?.userID;if(!r)return m("unauthorized","Not logged in.");let o=await e.multiplayer.joinRoom(s,t);return o.ok?{ok:true,data:n.start(e,r,o.data,i)}:o}static start(e,s,t,i){let r=new n(e,s,t,i);return r.reconcile(),r.schedulePoll(0),r}get isHost(){return this.hostId===this.selfId}get isOwner(){return this.ownerId===this.selfId}get closed(){return this.stopped}on(e,s){let t=this.listeners.get(e)??new Set;return t.add(s),this.listeners.set(e,t),()=>t.delete(s)}openPeers(){return [...this.links.values()].filter(e=>e.state==="open").map(e=>e.peerId)}isOpen(e){return this.links.get(e)?.state==="open"}linkStats(e){let s=this.links.get(e);return s?{rttMs:s.rttMs,bytesIn:s.bytesIn,bytesOut:s.bytesOut,buffered:s.relBuffered}:null}send(e,s,t){return this.links.get(e)?.send(s,t)??false}broadcast(e,s,t){let i=0;for(let r of this.links.values())r.peerId!==t&&r.state==="open"&&r.send(e,s)&&i++;return i}setExtraPeers(e){this.extraPeers=new Set([...e].filter(s=>s!==this.selfId)),this.reconcile();}setSuccessor(e){this.successor=e&&e!==this.selfId?e:null;}async claimHost(){let e=await this.client.multiplayer.claimHost(this.roomId);return e.ok&&this.applySnapshot(e.data),e}async kick(e,s=false){let t=await this.client.multiplayer.kickMember(this.roomId,e,s);return t.ok&&this.links.get(e)?.notice(1),t}unban(e){return this.client.multiplayer.unbanMember(this.roomId,e)}async leave(){if(this.stopped)return;let e=this.isHost?this.successor??void 0:void 0;this.stop(),await this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e});}async refreshMembers(){let e=await this.client.multiplayer.getRoom(this.roomId);e.ok&&this.applySnapshot(e.data);}schedulePoll(e){if(!this.stopped){if(this.polling){this.pollSoonMs=Math.min(this.pollSoonMs??e,e);return}this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=setTimeout(()=>{this.pollOnce();},e);}}nextPollDelay(){return Date.now()<this.fastUntil||this.outbox.busy||[...this.links.values()].some(s=>s.state==="connecting")||[...this.wanted()].some(s=>!this.links.has(s))?this.o.pollFastMs:this.isHost?this.o.pollHostIdleMs:this.o.pollClientIdleMs}async pollOnce(){if(this.stopped)return;this.pollTimer=null,this.polling=true,this.pollSoonMs=null;let e=await this.client.multiplayer.poll(this.roomId,this.lastSeq);if(this.polling=false,this.stopped)return;let s=this.pollSoonMs;if(this.pollSoonMs=null,e.ok){this.pollBackoff=0;for(let t of e.data.Envelopes??[])this.handleEnvelope(t);this.lastSeq=e.data.MaxSeq??this.lastSeq,this.reconcile(),this.schedulePoll(Math.min(this.nextPollDelay(),s??1/0));return}if(e.reason==="server"){let t=e.error??"";if(/not a member/i.test(t))return this.end("removed",{reason:t});if(/no longer exists|not found/i.test(t))return this.end("roomClosed",{});if(/disabled/i.test(t))return this.end("roomClosed",{})}this.pollBackoff=Math.min(this.pollBackoff+1,5),this.schedulePoll(this.o.pollFastMs*(1+this.pollBackoff));}handleEnvelope(e){let s=e.FromUserID??"";switch(e.Type){case "Signal":e.ToUserID===this.selfId&&e.Kind==="rtc"&&this.handleSignals(s,R(e.Payload));break;case "PlayerJoined":{let t=e.Payload||s;if(!t||t===this.selfId)break;if(!this.members.has(t)){let i={UserID:t};this.members.set(t,i),this.emit("memberJoined",{member:i});}this.fastUntil=Date.now()+this.o.fastWindowMs,this.scheduleRefresh();break}case "PlayerLeft":{let t=e.Payload||s,i=e.Kind==="kicked"?"kicked":e.Kind==="timeout"?"timeout":"left";if(t===this.selfId){i!=="left"&&this.end("removed",{reason:i});break}this.dropMember(t,i,i==="kicked"?s:void 0);break}case "HostChanged":{let t=e.Payload??"";if(t&&t!==this.hostId){let i=this.hostId||null;this.hostId=t,this.fastUntil=Date.now()+this.o.fastWindowMs,this.emit("hostChanged",{hostId:t,previousHostId:i});}break}case "RoomClosed":this.end("roomClosed",{});break;case "MemberState":this.scheduleRefresh();break;case "Chat":this.emit("chat",{from:s,text:e.Payload??""});break}}dropMember(e,s,t){let i=this.members.delete(e);this.closeLink(e,"member left"),this.outbox.forget(e),this.wantSentAt.delete(e);let r=this.retry.get(e);r?.timer&&clearTimeout(r.timer),this.retry.delete(e),this.extraPeers.delete(e),this.successor===e&&(this.successor=null),i&&this.emit("memberLeft",{userId:e,kind:s,by:t});}scheduleRefresh(){this.refreshTimer||this.stopped||(this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.refreshMembers();},400));}applySnapshot(e){if(this.stopped)return;e.IceServers?.length&&(this.iceServers=c(e.IceServers)),e.OwnerUserID&&(this.ownerId=e.OwnerUserID);let s=new Map;for(let t of e.Members??[])t.UserID&&s.set(t.UserID,t);for(let t of [...this.members.keys()])!s.has(t)&&t!==this.selfId&&this.dropMember(t,"left");for(let[t,i]of s){let r=this.members.has(t);this.members.set(t,i),!r&&t!==this.selfId&&this.emit("memberJoined",{member:i});}if(e.HostUserID&&e.HostUserID!==this.hostId){let t=this.hostId||null;this.hostId=e.HostUserID,this.emit("hostChanged",{hostId:e.HostUserID,previousHostId:t});}this.emit("membersUpdated",{members:[...this.members.values()]}),this.reconcile();}wanted(){let e=new Set,s=[...this.members.keys()].filter(t=>t!==this.selfId);if(this.topology==="Mesh"||this.isHost)for(let t of s)e.add(t);else this.hostId&&this.hostId!==this.selfId&&this.members.has(this.hostId)&&e.add(this.hostId);for(let t of this.extraPeers)this.members.has(t)&&e.add(t);return e}reconcile(){if(this.stopped)return;let e=Date.now();for(let s of this.wanted())if(!(this.links.has(s)||this.retry.get(s)?.timer))if(this.selfId<s)this.openLink(s,true,I());else {let t=this.wantSentAt.get(s)??0;e-t>8e3&&(this.wantSentAt.set(s,e),this.outbox.enqueue(s,{t:"want"}));}}handleSignals(e,s){if(!(!e||e===this.selfId)){this.members.has(e)||(this.members.set(e,{UserID:e}),this.scheduleRefresh());for(let t of s){let i=this.links.get(e);if(t.t==="want"){(!i||i.state==="closed")&&this.openLink(e,true,I());continue}if(t.t==="offer"){if(i?.lid===t.lid)continue;i&&this.closeLink(e,"replaced by a new offer"),this.openLink(e,false,t.lid).handle(t);continue}i&&i.lid===t.lid&&i.handle(t);}}}openLink(e,s,t){this.wantSentAt.delete(e);let i=new d({peerId:e,offerer:s,lid:t,iceServers:this.iceServers,createPeerConnection:this.o.createPeerConnection,signal:r=>this.outbox.enqueue(e,r),iceGatherTimeoutMs:this.o.iceGatherTimeoutMs,keepaliveMs:this.o.keepaliveMs,peerTimeoutMs:this.o.peerTimeoutMs,onOpen:()=>{this.everOpen.add(e),this.retry.delete(e),this.emit("peerOpen",{peerId:e});},onClose:r=>this.onLinkClosed(i,r),onMessage:(r,o)=>this.emit("message",{from:e,channel:r,data:o}),onNotice:r=>{r===1&&this.schedulePoll(0);}});return this.links.set(e,i),this.schedulePoll(Math.min(this.o.pollFastMs,250)),i}closeLink(e,s){let t=this.links.get(e);t&&(this.links.delete(e),t.close(s,true));}onLinkClosed(e,s){let t=e.peerId,i=this.links.get(t)===e;if(i&&this.links.delete(t),this.everOpen.delete(t)&&this.emit("peerClose",{peerId:t,reason:s}),!i||this.stopped||!this.members.has(t)||!this.wanted().has(t))return;let r=this.retry.get(t)??{attempts:0,timer:null},o=Math.min(15e3,1e3*2**r.attempts);r.attempts++,r.timer=setTimeout(()=>{r.timer=null,this.wantSentAt.delete(t),this.reconcile();},o),this.retry.set(t,r);}emit(e,s){for(let t of this.listeners.get(e)??[])try{t(s);}catch(i){console.error(`[RealtimeSession] ${String(e)} handler failed`,i);}}end(e,s){this.stopped||(this.stop(),this.emit(e,s));}stop(){this.stopped=true,this.pollTimer&&clearTimeout(this.pollTimer),this.refreshTimer&&clearTimeout(this.refreshTimer),this.pollTimer=this.refreshTimer=null;for(let e of this.retry.values())e.timer&&clearTimeout(e.timer);this.retry.clear(),this.outbox.close();for(let e of [...this.links.keys()]){let s=this.links.get(e);this.links.delete(e),s?.close("session closed");}typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide);}leaveOnUnload(){if(this.stopped)return;let e=this.isHost?this.successor??void 0:void 0;this.stop(),this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e,keepalive:true});}};function I(){let n=globalThis.crypto;return n&&"randomUUID"in n?n.randomUUID().slice(0,12):Math.random().toString(36).slice(2,14)}exports.MAX_MESSAGE_BYTES=f;exports.RealtimeSession=y;exports.toRtcIceServers=c;
@@ -1,229 +1,9 @@
1
- import { M as MultiplayerService, a as MultiplayerTopology, b as MultiplayerChatMode, R as RoomVisibility, O as OperationResult, c as RoomMemberView, d as RoomSnapshotResponse, K as KickMemberResponse, I as IceServer } from '../ClientContext-BYReJCTF.cjs';
1
+ import { I as IceServer } from '../RealtimeSession-Cg-wm6i4.cjs';
2
+ export { C as ChannelName, M as MemberLeftKind, R as RealtimeClient, a as RealtimeSession, b as RealtimeSessionEvents, c as RealtimeSessionOptions } from '../RealtimeSession-Cg-wm6i4.cjs';
2
3
  import 'zod';
3
4
  import '../PlatformAdapter-DU_8HalI.cjs';
4
5
  import 'decimal.js';
5
6
 
6
- /** The two channels of every link. */
7
- type ChannelName = "rel" | "fast";
8
-
9
- /** What the session needs from the SDK client — `client.multiplayer` and the player's id. */
10
- interface RealtimeClient {
11
- multiplayer: Pick<MultiplayerService, "createRoom" | "joinRoom" | "getRoom" | "leaveRoom" | "poll" | "sendSignal" | "claimHost" | "kickMember" | "unbanMember">;
12
- auth: {
13
- context: {
14
- userID: string;
15
- } | null;
16
- };
17
- }
18
- interface RealtimeSessionOptions {
19
- /** Poll interval while anything is being set up (joins, links connecting, signals queued). */
20
- pollFastMs?: number;
21
- /** Idle poll of the HOST: it has to notice new players joining. */
22
- pollHostIdleMs?: number;
23
- /**
24
- * Idle poll of everyone else: only keeps the membership alive — once links are up, news comes
25
- * over the DataChannels. Every poll is a paid server call, so this is deliberately slow.
26
- */
27
- pollClientIdleMs?: number;
28
- /** How long to stay on the fast poll after a membership or host change. */
29
- fastWindowMs?: number;
30
- /** Keepalive ping period on an idle link. */
31
- keepaliveMs?: number;
32
- /** A peer silent this long is considered gone (link closed, `peerClose`). */
33
- peerTimeoutMs?: number;
34
- /** Wait for ICE gathering up to this long before sending a description. */
35
- iceGatherTimeoutMs?: number;
36
- /** Signal payload ceiling (the title's MaxSignalPayloadBytes minus headroom). */
37
- maxSignalPayloadBytes?: number;
38
- /**
39
- * Spacing of signals to ONE peer. Default 650 ms — just over the SDK transport's per-key throttle
40
- * window (600 ms); lower it only together with the client's `throttleMs`.
41
- */
42
- signalPerTargetGapMs?: number;
43
- /** Spacing of ANY two signals. Default 180 ms — over the engine's 150 ms per-action lock. */
44
- signalGlobalGapMs?: number;
45
- /** Leave the room with `keepalive` on `pagehide` (default true in a browser). */
46
- leaveOnPageHide?: boolean;
47
- /** Test seam / custom stack. Default: `new RTCPeerConnection(config)`. */
48
- createPeerConnection?: (config: RTCConfiguration) => RTCPeerConnection;
49
- }
50
- type MemberLeftKind = "left" | "kicked" | "timeout";
51
- interface RealtimeSessionEvents {
52
- /** A DataChannel link to this peer is open — `send` works now. */
53
- peerOpen: {
54
- peerId: string;
55
- };
56
- /** The link to this peer is gone (it may reconnect by itself if the peer is still in the room). */
57
- peerClose: {
58
- peerId: string;
59
- reason: string;
60
- };
61
- /** An app message from a peer. */
62
- message: {
63
- from: string;
64
- channel: ChannelName;
65
- data: Uint8Array;
66
- };
67
- memberJoined: {
68
- member: RoomMemberView;
69
- };
70
- memberLeft: {
71
- userId: string;
72
- kind: MemberLeftKind;
73
- by?: string;
74
- };
75
- /** Fresh member list (profiles, ready flags, member state). */
76
- membersUpdated: {
77
- members: RoomMemberView[];
78
- };
79
- hostChanged: {
80
- hostId: string;
81
- previousHostId: string | null;
82
- };
83
- /** Server-relayed lobby chat. */
84
- chat: {
85
- from: string;
86
- text: string;
87
- };
88
- roomClosed: Record<string, never>;
89
- /** This player is no longer in the room (kicked, displaced as a silent host, or expired). */
90
- removed: {
91
- reason: string;
92
- };
93
- }
94
- type Listener<T> = (e: T) => void;
95
- /**
96
- * WebRTC session over the engine's Multiplayer signaling (room + poll + SendSignal).
97
- *
98
- * Topology decides who connects to whom:
99
- * • `Host` (star) — the host links to every member, everyone else links only to the host, plus
100
- * any `extraPeers` the game asks for (e.g. a standby link to the host's successor so a host
101
- * handover does not have to wait for signaling).
102
- * • `Mesh` — everyone links to everyone.
103
- *
104
- * Who offers: for a pair that both want a link, the smaller user id offers; a peer that wants a
105
- * link but is not the offerer by that rule sends "want" and the other side offers. No offer glare
106
- * by construction.
107
- *
108
- * Costs are shaped for the backend: polling is fast only while something is being set up and slow
109
- * afterwards (the host 2.5 s to see newcomers, others 20 s just to stay members); signals go through
110
- * a single-flight, per-peer-batched outbox (see signals.ts).
111
- */
112
- declare class RealtimeSession {
113
- private readonly client;
114
- readonly roomId: string;
115
- readonly selfId: string;
116
- readonly topology: MultiplayerTopology;
117
- readonly chatMode: MultiplayerChatMode;
118
- ownerId: string;
119
- hostId: string;
120
- /** Members by user id (self included). */
121
- readonly members: Map<string, {
122
- [x: string]: unknown;
123
- UserID?: string | null | undefined;
124
- Username?: string | null | undefined;
125
- AvatarUrl?: string | null | undefined;
126
- Level?: number | null | undefined;
127
- Power?: number | null | undefined;
128
- Ready?: boolean | null | undefined;
129
- State?: Record<string, string> | null | undefined;
130
- JoinedAt?: number | null | undefined;
131
- IsHost?: boolean | null | undefined;
132
- LastSeenMs?: number | null | undefined;
133
- }>;
134
- private readonly o;
135
- private iceServers;
136
- private lastSeq;
137
- private readonly links;
138
- private readonly everOpen;
139
- private readonly retry;
140
- private readonly wantSentAt;
141
- private extraPeers;
142
- private readonly outbox;
143
- private pollTimer;
144
- private polling;
145
- private pollSoonMs;
146
- private pollBackoff;
147
- private fastUntil;
148
- private refreshTimer;
149
- private stopped;
150
- private successor;
151
- private readonly listeners;
152
- private readonly onPageHide;
153
- private constructor();
154
- /** Create a room and start the session as its host. */
155
- static create(client: RealtimeClient, roomName: string, room?: {
156
- topology?: MultiplayerTopology;
157
- chatMode?: MultiplayerChatMode;
158
- maxPlayers?: number;
159
- visibility?: RoomVisibility;
160
- joinCode?: string;
161
- }, options?: RealtimeSessionOptions): Promise<OperationResult<RealtimeSession>>;
162
- /** Join a room and start the session. */
163
- static join(client: RealtimeClient, roomID: string, joinCode?: string, options?: RealtimeSessionOptions): Promise<OperationResult<RealtimeSession>>;
164
- private static start;
165
- get isHost(): boolean;
166
- get isOwner(): boolean;
167
- get closed(): boolean;
168
- on<K extends keyof RealtimeSessionEvents>(event: K, fn: Listener<RealtimeSessionEvents[K]>): () => void;
169
- /** Peers with an open link right now. */
170
- openPeers(): string[];
171
- isOpen(peerId: string): boolean;
172
- /** Round trip to a peer (ms, 0 until measured) and traffic counters — for a network HUD. */
173
- linkStats(peerId: string): {
174
- rttMs: number;
175
- bytesIn: number;
176
- bytesOut: number;
177
- buffered: number;
178
- } | null;
179
- /** Send to one peer. false — no open link, too large for `fast`, or `rel` backed up. */
180
- send(peerId: string, channel: ChannelName, data: Uint8Array): boolean;
181
- /** Send to every open link (optionally except one). Returns how many links took it. */
182
- broadcast(channel: ChannelName, data: Uint8Array, except?: string): number;
183
- /**
184
- * Links the game wants on top of the topology (e.g. standby links to the host's successor).
185
- * Both sides of such a link should ask for it; the session connects them without an offer race.
186
- */
187
- setExtraPeers(ids: Iterable<string>): void;
188
- /** The member that takes over if this (host) player leaves — used by `leave()` and on page close. */
189
- setSuccessor(userId: string | null): void;
190
- /** Take over a host that stopped responding (see MultiplayerService.claimHost). */
191
- claimHost(): Promise<OperationResult<RoomSnapshotResponse>>;
192
- kick(userId: string, ban?: boolean): Promise<OperationResult<KickMemberResponse>>;
193
- unban(userId: string): Promise<OperationResult<{
194
- [x: string]: unknown;
195
- WasBanned?: boolean | null | undefined;
196
- }>>;
197
- /** Leave the room and close every link. */
198
- leave(): Promise<void>;
199
- /** Re-read the room (profiles, host, ready flags) now. */
200
- refreshMembers(): Promise<void>;
201
- /**
202
- * One poll at a time: a second concurrent Poll is dropped by the transport as a duplicate and
203
- * would only push the loop into back-off. A request for an earlier poll made while one is in
204
- * flight is remembered and honoured when it returns.
205
- */
206
- private schedulePoll;
207
- private nextPollDelay;
208
- private pollOnce;
209
- private handleEnvelope;
210
- private dropMember;
211
- private scheduleRefresh;
212
- private applySnapshot;
213
- /** Peers this side wants a link to, by topology + extra peers. */
214
- private wanted;
215
- private reconcile;
216
- private handleSignals;
217
- private openLink;
218
- private closeLink;
219
- private onLinkClosed;
220
- private emit;
221
- private end;
222
- private stop;
223
- /** `pagehide`: leave with keepalive so the room learns at once, handing the host role over. */
224
- private leaveOnUnload;
225
- }
226
-
227
7
  /**
228
8
  * Server ICE list → `RTCIceServer[]`.
229
9
  *
@@ -238,4 +18,4 @@ declare function toRtcIceServers(list: readonly IceServer[] | null | undefined):
238
18
  /** Largest single message put on a channel, header included. */
239
19
  declare const MAX_MESSAGE_BYTES: number;
240
20
 
241
- export { type ChannelName, MAX_MESSAGE_BYTES, type MemberLeftKind, type RealtimeClient, RealtimeSession, type RealtimeSessionEvents, type RealtimeSessionOptions, toRtcIceServers };
21
+ export { MAX_MESSAGE_BYTES, toRtcIceServers };
@@ -1,229 +1,9 @@
1
- import { M as MultiplayerService, a as MultiplayerTopology, b as MultiplayerChatMode, R as RoomVisibility, O as OperationResult, c as RoomMemberView, d as RoomSnapshotResponse, K as KickMemberResponse, I as IceServer } from '../ClientContext-CrMomCH-.js';
1
+ import { I as IceServer } from '../RealtimeSession-BjBq5iJG.js';
2
+ export { C as ChannelName, M as MemberLeftKind, R as RealtimeClient, a as RealtimeSession, b as RealtimeSessionEvents, c as RealtimeSessionOptions } from '../RealtimeSession-BjBq5iJG.js';
2
3
  import 'zod';
3
4
  import '../PlatformAdapter-DU_8HalI.js';
4
5
  import 'decimal.js';
5
6
 
6
- /** The two channels of every link. */
7
- type ChannelName = "rel" | "fast";
8
-
9
- /** What the session needs from the SDK client — `client.multiplayer` and the player's id. */
10
- interface RealtimeClient {
11
- multiplayer: Pick<MultiplayerService, "createRoom" | "joinRoom" | "getRoom" | "leaveRoom" | "poll" | "sendSignal" | "claimHost" | "kickMember" | "unbanMember">;
12
- auth: {
13
- context: {
14
- userID: string;
15
- } | null;
16
- };
17
- }
18
- interface RealtimeSessionOptions {
19
- /** Poll interval while anything is being set up (joins, links connecting, signals queued). */
20
- pollFastMs?: number;
21
- /** Idle poll of the HOST: it has to notice new players joining. */
22
- pollHostIdleMs?: number;
23
- /**
24
- * Idle poll of everyone else: only keeps the membership alive — once links are up, news comes
25
- * over the DataChannels. Every poll is a paid server call, so this is deliberately slow.
26
- */
27
- pollClientIdleMs?: number;
28
- /** How long to stay on the fast poll after a membership or host change. */
29
- fastWindowMs?: number;
30
- /** Keepalive ping period on an idle link. */
31
- keepaliveMs?: number;
32
- /** A peer silent this long is considered gone (link closed, `peerClose`). */
33
- peerTimeoutMs?: number;
34
- /** Wait for ICE gathering up to this long before sending a description. */
35
- iceGatherTimeoutMs?: number;
36
- /** Signal payload ceiling (the title's MaxSignalPayloadBytes minus headroom). */
37
- maxSignalPayloadBytes?: number;
38
- /**
39
- * Spacing of signals to ONE peer. Default 650 ms — just over the SDK transport's per-key throttle
40
- * window (600 ms); lower it only together with the client's `throttleMs`.
41
- */
42
- signalPerTargetGapMs?: number;
43
- /** Spacing of ANY two signals. Default 180 ms — over the engine's 150 ms per-action lock. */
44
- signalGlobalGapMs?: number;
45
- /** Leave the room with `keepalive` on `pagehide` (default true in a browser). */
46
- leaveOnPageHide?: boolean;
47
- /** Test seam / custom stack. Default: `new RTCPeerConnection(config)`. */
48
- createPeerConnection?: (config: RTCConfiguration) => RTCPeerConnection;
49
- }
50
- type MemberLeftKind = "left" | "kicked" | "timeout";
51
- interface RealtimeSessionEvents {
52
- /** A DataChannel link to this peer is open — `send` works now. */
53
- peerOpen: {
54
- peerId: string;
55
- };
56
- /** The link to this peer is gone (it may reconnect by itself if the peer is still in the room). */
57
- peerClose: {
58
- peerId: string;
59
- reason: string;
60
- };
61
- /** An app message from a peer. */
62
- message: {
63
- from: string;
64
- channel: ChannelName;
65
- data: Uint8Array;
66
- };
67
- memberJoined: {
68
- member: RoomMemberView;
69
- };
70
- memberLeft: {
71
- userId: string;
72
- kind: MemberLeftKind;
73
- by?: string;
74
- };
75
- /** Fresh member list (profiles, ready flags, member state). */
76
- membersUpdated: {
77
- members: RoomMemberView[];
78
- };
79
- hostChanged: {
80
- hostId: string;
81
- previousHostId: string | null;
82
- };
83
- /** Server-relayed lobby chat. */
84
- chat: {
85
- from: string;
86
- text: string;
87
- };
88
- roomClosed: Record<string, never>;
89
- /** This player is no longer in the room (kicked, displaced as a silent host, or expired). */
90
- removed: {
91
- reason: string;
92
- };
93
- }
94
- type Listener<T> = (e: T) => void;
95
- /**
96
- * WebRTC session over the engine's Multiplayer signaling (room + poll + SendSignal).
97
- *
98
- * Topology decides who connects to whom:
99
- * • `Host` (star) — the host links to every member, everyone else links only to the host, plus
100
- * any `extraPeers` the game asks for (e.g. a standby link to the host's successor so a host
101
- * handover does not have to wait for signaling).
102
- * • `Mesh` — everyone links to everyone.
103
- *
104
- * Who offers: for a pair that both want a link, the smaller user id offers; a peer that wants a
105
- * link but is not the offerer by that rule sends "want" and the other side offers. No offer glare
106
- * by construction.
107
- *
108
- * Costs are shaped for the backend: polling is fast only while something is being set up and slow
109
- * afterwards (the host 2.5 s to see newcomers, others 20 s just to stay members); signals go through
110
- * a single-flight, per-peer-batched outbox (see signals.ts).
111
- */
112
- declare class RealtimeSession {
113
- private readonly client;
114
- readonly roomId: string;
115
- readonly selfId: string;
116
- readonly topology: MultiplayerTopology;
117
- readonly chatMode: MultiplayerChatMode;
118
- ownerId: string;
119
- hostId: string;
120
- /** Members by user id (self included). */
121
- readonly members: Map<string, {
122
- [x: string]: unknown;
123
- UserID?: string | null | undefined;
124
- Username?: string | null | undefined;
125
- AvatarUrl?: string | null | undefined;
126
- Level?: number | null | undefined;
127
- Power?: number | null | undefined;
128
- Ready?: boolean | null | undefined;
129
- State?: Record<string, string> | null | undefined;
130
- JoinedAt?: number | null | undefined;
131
- IsHost?: boolean | null | undefined;
132
- LastSeenMs?: number | null | undefined;
133
- }>;
134
- private readonly o;
135
- private iceServers;
136
- private lastSeq;
137
- private readonly links;
138
- private readonly everOpen;
139
- private readonly retry;
140
- private readonly wantSentAt;
141
- private extraPeers;
142
- private readonly outbox;
143
- private pollTimer;
144
- private polling;
145
- private pollSoonMs;
146
- private pollBackoff;
147
- private fastUntil;
148
- private refreshTimer;
149
- private stopped;
150
- private successor;
151
- private readonly listeners;
152
- private readonly onPageHide;
153
- private constructor();
154
- /** Create a room and start the session as its host. */
155
- static create(client: RealtimeClient, roomName: string, room?: {
156
- topology?: MultiplayerTopology;
157
- chatMode?: MultiplayerChatMode;
158
- maxPlayers?: number;
159
- visibility?: RoomVisibility;
160
- joinCode?: string;
161
- }, options?: RealtimeSessionOptions): Promise<OperationResult<RealtimeSession>>;
162
- /** Join a room and start the session. */
163
- static join(client: RealtimeClient, roomID: string, joinCode?: string, options?: RealtimeSessionOptions): Promise<OperationResult<RealtimeSession>>;
164
- private static start;
165
- get isHost(): boolean;
166
- get isOwner(): boolean;
167
- get closed(): boolean;
168
- on<K extends keyof RealtimeSessionEvents>(event: K, fn: Listener<RealtimeSessionEvents[K]>): () => void;
169
- /** Peers with an open link right now. */
170
- openPeers(): string[];
171
- isOpen(peerId: string): boolean;
172
- /** Round trip to a peer (ms, 0 until measured) and traffic counters — for a network HUD. */
173
- linkStats(peerId: string): {
174
- rttMs: number;
175
- bytesIn: number;
176
- bytesOut: number;
177
- buffered: number;
178
- } | null;
179
- /** Send to one peer. false — no open link, too large for `fast`, or `rel` backed up. */
180
- send(peerId: string, channel: ChannelName, data: Uint8Array): boolean;
181
- /** Send to every open link (optionally except one). Returns how many links took it. */
182
- broadcast(channel: ChannelName, data: Uint8Array, except?: string): number;
183
- /**
184
- * Links the game wants on top of the topology (e.g. standby links to the host's successor).
185
- * Both sides of such a link should ask for it; the session connects them without an offer race.
186
- */
187
- setExtraPeers(ids: Iterable<string>): void;
188
- /** The member that takes over if this (host) player leaves — used by `leave()` and on page close. */
189
- setSuccessor(userId: string | null): void;
190
- /** Take over a host that stopped responding (see MultiplayerService.claimHost). */
191
- claimHost(): Promise<OperationResult<RoomSnapshotResponse>>;
192
- kick(userId: string, ban?: boolean): Promise<OperationResult<KickMemberResponse>>;
193
- unban(userId: string): Promise<OperationResult<{
194
- [x: string]: unknown;
195
- WasBanned?: boolean | null | undefined;
196
- }>>;
197
- /** Leave the room and close every link. */
198
- leave(): Promise<void>;
199
- /** Re-read the room (profiles, host, ready flags) now. */
200
- refreshMembers(): Promise<void>;
201
- /**
202
- * One poll at a time: a second concurrent Poll is dropped by the transport as a duplicate and
203
- * would only push the loop into back-off. A request for an earlier poll made while one is in
204
- * flight is remembered and honoured when it returns.
205
- */
206
- private schedulePoll;
207
- private nextPollDelay;
208
- private pollOnce;
209
- private handleEnvelope;
210
- private dropMember;
211
- private scheduleRefresh;
212
- private applySnapshot;
213
- /** Peers this side wants a link to, by topology + extra peers. */
214
- private wanted;
215
- private reconcile;
216
- private handleSignals;
217
- private openLink;
218
- private closeLink;
219
- private onLinkClosed;
220
- private emit;
221
- private end;
222
- private stop;
223
- /** `pagehide`: leave with keepalive so the room learns at once, handing the host role over. */
224
- private leaveOnUnload;
225
- }
226
-
227
7
  /**
228
8
  * Server ICE list → `RTCIceServer[]`.
229
9
  *
@@ -238,4 +18,4 @@ declare function toRtcIceServers(list: readonly IceServer[] | null | undefined):
238
18
  /** Largest single message put on a channel, header included. */
239
19
  declare const MAX_MESSAGE_BYTES: number;
240
20
 
241
- export { type ChannelName, MAX_MESSAGE_BYTES, type MemberLeftKind, type RealtimeClient, RealtimeSession, type RealtimeSessionEvents, type RealtimeSessionOptions, toRtcIceServers };
21
+ export { MAX_MESSAGE_BYTES, toRtcIceServers };