@idosgames/core 0.21.6 → 0.22.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.
- package/CHANGELOG.md +18 -0
- package/dist/{RealtimeSession-BBJ3gAb8.d.cts → VoiceController-ClFmHUGH.d.cts} +199 -19
- package/dist/{RealtimeSession-D7evucmN.d.ts → VoiceController-JKfvxpjs.d.ts} +199 -19
- package/dist/chunk-ZR2KDXJV.js +2 -0
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/platform/index.cjs +2 -2
- package/dist/platform/index.d.cts +29 -1
- package/dist/platform/index.d.ts +29 -1
- package/dist/platform/index.js +1 -1
- package/dist/realtime/index.cjs +1 -1
- package/dist/realtime/index.d.cts +2 -2
- package/dist/realtime/index.d.ts +2 -2
- package/dist/realtime/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-YEBYHDZG.js +0 -2
package/dist/platform/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
exports.BrowserPlatformAdapter=
|
|
1
|
+
'use strict';var s=class{getString(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}setString(e,r){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,r);}catch{}}remove(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e);}catch{}}},l=class{map=new Map;getString(e){return this.map.get(e)??null}setString(e,r){this.map.set(e,r);}remove(e){this.map.delete(e);}};function o(){return globalThis.Telegram?.WebApp??null}function y(){return crypto.randomUUID()}var R="idos_device_id",c=class{storage;constructor(e=new s){this.storage=e;}getPlatform(){return o()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=o()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){if(typeof document>"u")return null;let e=document.referrer;return e&&e.length>0?e:null}getTelegramInitDataRaw(){let e=o()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(R);return e||(e=y(),this.storage.setString(R,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let r=o();if(r?.openTelegramLink){r.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let r=o();if(r?.openInvoice){r.openInvoice(e);return}typeof window<"u"&&window.open(e,"_blank");}async showAd(e){let r=globalThis;typeof r.showAd=="function"&&await r.showAd(e);}async copyToClipboard(e){typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(e);}};var E="idos_device_id",d=class{storage;constructor(e=new l){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(E);return e||(e="noop-device",this.storage.setString(E,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};var i=["https://idosgames.com","https://www.idosgames.com"];function v(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost")}function p(t){if(i.includes(t))return true;if(typeof window>"u"||!v(window.location.hostname))return false;try{return v(new URL(t).hostname)}catch{return false}}var O="IDOS_PLATFORM_WALLET_ACK",D="PLATFORM_WALLET_UNAVAILABLE",M=5e3,x=18e4;function k(){let t=[...i],e=window.location.ancestorOrigins?.[0];return e&&!t.includes(e)&&p(e)&&t.push(e),t}function b(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function g(t,e,r,U={}){let u={ok:false,error:D,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(u);let S=window.parent;if(!S)return Promise.resolve(u);let I=b(),h=U.answerTimeoutMs??x;return new Promise(L=>{let A=false,f,m=a=>{A||(A=true,window.removeEventListener("message",_),clearTimeout(f),L(a));},_=a=>{if(!p(a.origin))return;let n=a.data;if(!(!n||n.requestId!==I)){if(n.type===O){clearTimeout(f),f=setTimeout(()=>m({ok:false,error:"TIMEOUT",data:{}}),h);return}n.type===e&&m({ok:n.ok===true,error:typeof n.error=="string"?n.error:void 0,data:n});}};f=setTimeout(()=>m(u),M),window.addEventListener("message",_);for(let a of k())try{S.postMessage({type:t,requestId:I,...r},a);}catch{}})}var w={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},F=15*6e4,N=/^[a-z0-9]{8}-preview\.idos\.games$/;function W(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !N.test(window.location.hostname.toLowerCase())}async function K(t){let e=await g(w.request,w.response,{titleID:t.titleID,userID:t.userID,currencyID:t.currencyID,amount:t.amount},{answerTimeoutMs:F});return e.ok?{ok:true}:{ok:false,error:e.error}}var P={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},V=30*6e4,G=/^[a-z0-9]{8}-preview\.idos\.games$/,T="idos:platformSignIn:declined:";function q(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(G.test(window.location.hostname.toLowerCase()))return false;let t=window.location.ancestorOrigins?.[0];if(t&&!i.includes(t))try{let e=new URL(t).hostname;if(e!=="localhost"&&e!=="127.0.0.1")return !1}catch{return false}return true}async function C(t){let e=await g(P.request,P.response,{titleID:t},{answerTimeoutMs:V}),r=e.data.code;return e.ok&&typeof r=="string"&&r.length>0?{code:r}:{error:e.error??"no_code"}}function B(t){try{window.localStorage.setItem(T+t,"1");}catch{}}function H(t){try{window.localStorage.removeItem(T+t);}catch{}}function $(t){try{return window.localStorage.getItem(T+t)==="1"}catch{return false}}
|
|
2
|
+
exports.BrowserPlatformAdapter=c;exports.BrowserStorage=s;exports.MemoryStorage=l;exports.NoopPlatformAdapter=d;exports.PLATFORM_BRIDGE_ACK=O;exports.PLATFORM_ORIGINS=i;exports.PLATFORM_PAGE_UNAVAILABLE=D;exports.PLATFORM_SIGN_IN_MESSAGES=P;exports.PLATFORM_TOPUP_MESSAGES=w;exports.askPlatformPage=g;exports.canUsePlatformSignIn=q;exports.canUsePlatformTopUp=W;exports.clearPlatformSignInDeclined=H;exports.getTelegramWebApp=o;exports.isPlatformParentOrigin=p;exports.isPlatformSignInDeclined=$;exports.markPlatformSignInDeclined=B;exports.requestPlatformSignIn=C;exports.requestPlatformTopUp=K;
|
|
@@ -130,4 +130,32 @@ declare function canUsePlatformTopUp(): boolean;
|
|
|
130
130
|
/** Asks the idosgames.com page around the game to top the player's balance up. Never rejects. */
|
|
131
131
|
declare function requestPlatformTopUp(request: PlatformTopUpRequest): Promise<PlatformTopUpResult>;
|
|
132
132
|
|
|
133
|
-
|
|
133
|
+
/** Message names. Shared with the website's `PlatformWebGLAuthBridge` — keep both in step. */
|
|
134
|
+
declare const PLATFORM_SIGN_IN_MESSAGES: {
|
|
135
|
+
readonly request: "IDOS_PLATFORM_AUTH_REQUEST";
|
|
136
|
+
readonly response: "IDOS_PLATFORM_AUTH_RESPONSE";
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* Whether the page around this game is the platform's own `/app/{id}` page: a frame exactly one level
|
|
140
|
+
* deep (on a foreign site the game sits two frames deep, behind our `/embed` page), not the AI Coder
|
|
141
|
+
* preview, and — where the browser names it — a parent on a platform origin. The site's ACK is still
|
|
142
|
+
* what really decides; this only spares a 5-second wait where an answer cannot come.
|
|
143
|
+
*/
|
|
144
|
+
declare function canUsePlatformSignIn(): boolean;
|
|
145
|
+
interface PlatformSignInAnswer {
|
|
146
|
+
/** The one-time SSO code — exchange it with `client.auth.loginWithSsoCode`. */
|
|
147
|
+
code?: string;
|
|
148
|
+
/** Why not: `no_session`, `wrong_title`, `no_title`, `issue_failed`, `TIMEOUT`, `PLATFORM_WALLET_UNAVAILABLE` (no answer). */
|
|
149
|
+
error?: string;
|
|
150
|
+
}
|
|
151
|
+
/** Asks the idosgames.com page around the game for a sign-in code. Never rejects. */
|
|
152
|
+
declare function requestPlatformSignIn(titleID: string): Promise<PlatformSignInAnswer>;
|
|
153
|
+
/**
|
|
154
|
+
* The player signed out of this game themselves: the site must not sign them straight back in on the
|
|
155
|
+
* next visit. Cleared by the next sign-in of any kind (`clearPlatformSignInDeclined`).
|
|
156
|
+
*/
|
|
157
|
+
declare function markPlatformSignInDeclined(titleID: string): void;
|
|
158
|
+
declare function clearPlatformSignInDeclined(titleID: string): void;
|
|
159
|
+
declare function isPlatformSignInDeclined(titleID: string): boolean;
|
|
160
|
+
|
|
161
|
+
export { BrowserPlatformAdapter, BrowserStorage, KeyValueStorage, MemoryStorage, NoopPlatformAdapter, PLATFORM_BRIDGE_ACK, PLATFORM_ORIGINS, PLATFORM_PAGE_UNAVAILABLE, PLATFORM_SIGN_IN_MESSAGES, PLATFORM_TOPUP_MESSAGES, PlatformAdapter, type PlatformPageAnswer, type PlatformSignInAnswer, type PlatformTopUpRequest, type PlatformTopUpResult, type TelegramInitDataUnsafe, type TelegramWebApp, askPlatformPage, canUsePlatformSignIn, canUsePlatformTopUp, clearPlatformSignInDeclined, getTelegramWebApp, isPlatformParentOrigin, isPlatformSignInDeclined, markPlatformSignInDeclined, requestPlatformSignIn, requestPlatformTopUp };
|
package/dist/platform/index.d.ts
CHANGED
|
@@ -130,4 +130,32 @@ declare function canUsePlatformTopUp(): boolean;
|
|
|
130
130
|
/** Asks the idosgames.com page around the game to top the player's balance up. Never rejects. */
|
|
131
131
|
declare function requestPlatformTopUp(request: PlatformTopUpRequest): Promise<PlatformTopUpResult>;
|
|
132
132
|
|
|
133
|
-
|
|
133
|
+
/** Message names. Shared with the website's `PlatformWebGLAuthBridge` — keep both in step. */
|
|
134
|
+
declare const PLATFORM_SIGN_IN_MESSAGES: {
|
|
135
|
+
readonly request: "IDOS_PLATFORM_AUTH_REQUEST";
|
|
136
|
+
readonly response: "IDOS_PLATFORM_AUTH_RESPONSE";
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* Whether the page around this game is the platform's own `/app/{id}` page: a frame exactly one level
|
|
140
|
+
* deep (on a foreign site the game sits two frames deep, behind our `/embed` page), not the AI Coder
|
|
141
|
+
* preview, and — where the browser names it — a parent on a platform origin. The site's ACK is still
|
|
142
|
+
* what really decides; this only spares a 5-second wait where an answer cannot come.
|
|
143
|
+
*/
|
|
144
|
+
declare function canUsePlatformSignIn(): boolean;
|
|
145
|
+
interface PlatformSignInAnswer {
|
|
146
|
+
/** The one-time SSO code — exchange it with `client.auth.loginWithSsoCode`. */
|
|
147
|
+
code?: string;
|
|
148
|
+
/** Why not: `no_session`, `wrong_title`, `no_title`, `issue_failed`, `TIMEOUT`, `PLATFORM_WALLET_UNAVAILABLE` (no answer). */
|
|
149
|
+
error?: string;
|
|
150
|
+
}
|
|
151
|
+
/** Asks the idosgames.com page around the game for a sign-in code. Never rejects. */
|
|
152
|
+
declare function requestPlatformSignIn(titleID: string): Promise<PlatformSignInAnswer>;
|
|
153
|
+
/**
|
|
154
|
+
* The player signed out of this game themselves: the site must not sign them straight back in on the
|
|
155
|
+
* next visit. Cleared by the next sign-in of any kind (`clearPlatformSignInDeclined`).
|
|
156
|
+
*/
|
|
157
|
+
declare function markPlatformSignInDeclined(titleID: string): void;
|
|
158
|
+
declare function clearPlatformSignInDeclined(titleID: string): void;
|
|
159
|
+
declare function isPlatformSignInDeclined(titleID: string): boolean;
|
|
160
|
+
|
|
161
|
+
export { BrowserPlatformAdapter, BrowserStorage, KeyValueStorage, MemoryStorage, NoopPlatformAdapter, PLATFORM_BRIDGE_ACK, PLATFORM_ORIGINS, PLATFORM_PAGE_UNAVAILABLE, PLATFORM_SIGN_IN_MESSAGES, PLATFORM_TOPUP_MESSAGES, PlatformAdapter, type PlatformPageAnswer, type PlatformSignInAnswer, type PlatformTopUpRequest, type PlatformTopUpResult, type TelegramInitDataUnsafe, type TelegramWebApp, askPlatformPage, canUsePlatformSignIn, canUsePlatformTopUp, clearPlatformSignInDeclined, getTelegramWebApp, isPlatformParentOrigin, isPlatformSignInDeclined, markPlatformSignInDeclined, requestPlatformSignIn, requestPlatformTopUp };
|
package/dist/platform/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{e as BrowserPlatformAdapter,a as BrowserStorage,b as MemoryStorage,n as NoopPlatformAdapter,h as PLATFORM_BRIDGE_ACK,f as PLATFORM_ORIGINS,i as PLATFORM_PAGE_UNAVAILABLE,k as PLATFORM_TOPUP_MESSAGES,j as askPlatformPage,l as canUsePlatformTopUp,c as getTelegramWebApp,g as isPlatformParentOrigin,m as requestPlatformTopUp}from'../chunk-
|
|
1
|
+
export{e as BrowserPlatformAdapter,a as BrowserStorage,b as MemoryStorage,n as NoopPlatformAdapter,h as PLATFORM_BRIDGE_ACK,f as PLATFORM_ORIGINS,i as PLATFORM_PAGE_UNAVAILABLE,o as PLATFORM_SIGN_IN_MESSAGES,k as PLATFORM_TOPUP_MESSAGES,j as askPlatformPage,p as canUsePlatformSignIn,l as canUsePlatformTopUp,s as clearPlatformSignInDeclined,c as getTelegramWebApp,g as isPlatformParentOrigin,t as isPlatformSignInDeclined,r as markPlatformSignInDeclined,q as requestPlatformSignIn,m as requestPlatformTopUp}from'../chunk-ZR2KDXJV.js';
|
package/dist/realtime/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';function p(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 c=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 d(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,u=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 c;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 m=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 P={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=d(t.IceServers),this.o={...P,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 m((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 p("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 p("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(),this.emit("left",{}),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=d(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 u({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.emit("left",{}),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=d;
|
|
1
|
+
'use strict';function d(o){return {ok:true,data:o}}function c(o,e){return {ok:false,reason:o,error:e}}var g=16384;function v(o){let e=new Uint8Array(o.byteLength+1);return e[0]=0,e.set(o,1),e}function b(o,e){if(o.byteLength+1<=16384)return [v(o)];if(o.byteLength>67108864)throw new RangeError(`Message of ${o.byteLength} bytes exceeds 67108864.`);let i=Math.ceil(o.byteLength/16375),t=[];for(let s=0;s<i;s++){let r=o.subarray(s*16375,Math.min(o.byteLength,(s+1)*16375)),n=new Uint8Array(9+r.byteLength),a=new DataView(n.buffer);n[0]=1,a.setUint32(1,e>>>0),a.setUint16(5,s),a.setUint16(7,i),n.set(r,9),t.push(n);}return t}var u=class{id=-1;count=0;parts=[];bytes=0;push(e){if(e.byteLength<9)return null;let i=new DataView(e.buffer,e.byteOffset,e.byteLength),t=i.getUint32(1),s=i.getUint16(5),r=i.getUint16(7);if(s===0&&(this.id=t,this.count=r,this.parts=[],this.bytes=0),t!==this.id||s!==this.parts.length||r!==this.count)return this.reset(),null;let n=e.subarray(9);if(this.bytes+=n.byteLength,this.bytes>67108864)return this.reset(),null;if(this.parts.push(n),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 p(o){let e=new Map;for(let i of o??[]){let t=i.Urls?.trim();if(!t)continue;let s=i.Username??void 0,r=i.Credential??void 0,n=`${s??""}\0${r??""}`,a=e.get(n);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]};s&&(l.username=s),r&&(l.credential=r),e.set(n,l);}return [...e.values()]}var E=4*1024*1024,P=5e3,m=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=i=>{if(!i.candidate){this.sendDescriptionIfReady();return}this.descriptionSent&&this.lateIce.push(i.candidate.toJSON()),this.flushLateIce();},this.pc.onconnectionstatechange=()=>{let i=this.pc.connectionState;(i==="failed"||i==="closed")&&this.close(`connection ${i}`);},this.pc.ondatachannel=i=>this.adopt(i.channel),this.pc.ontrack=i=>{i.track?.kind!=="audio"||this.state==="closed"||(this.remoteAudio=i.track,this.o.onAudio?.(i.track));},this.openTimer=setTimeout(()=>{this.state==="connecting"&&this.close("connect timeout");},Math.max(15e3,e.peerTimeoutMs*3)),this.offerer&&(e.audio&&(this.audioTx=this.pc.addTransceiver("audio",{direction:"sendrecv"})),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 u;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;audioTx=null;micTrack=null;remoteAudio=null;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}),this.o.audio&&this.adoptAudio(),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 i of e.c)await this.addIce(i);else e.t==="bye"&&this.close("peer closed the link");}catch(i){this.close(`signaling failed: ${String(i)}`);}}adoptAudio(){let e=this.pc.getTransceivers().find(i=>i.receiver.track?.kind==="audio"&&i.currentDirection!=="stopped")??null;e&&(e.direction="sendrecv",this.audioTx=e,this.micTrack&&this.applyMic());}setMicTrack(e){this.micTrack=e,this.applyMic();}applyMic(){!this.audioTx||this.state==="closed"||this.audioTx.sender.replaceTrack(this.micTrack).catch(()=>{});}async drainRemoteIce(){let e=this.pendingRemoteIce.splice(0);for(let i of e)await this.addIce(i);}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=i=>this.receive(e.label,i.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>=P)&&(this.pingSentAt=e,this.raw("fast",new Uint8Array([2])));}receive(e,i){if(!(i instanceof ArrayBuffer))return;let t=new Uint8Array(i);this.lastRecv=Date.now(),this.bytesIn+=t.byteLength;let s=t[0];if(s===0)this.o.onMessage(e,t.subarray(1));else if(s===1&&e==="rel"){let r=this.reassembler.push(t);r&&this.o.onMessage(e,r);}else s===2?this.raw("fast",new Uint8Array([3])):s===3?this.pingSentAt&&(this.rttMs=Date.now()-this.pingSentAt):s===4&&e==="rel"&&this.o.onNotice?.(t[1]??0);}send(e,i){if(this.state!=="open")return false;if(e==="fast")return i.byteLength+1>16384?false:this.raw("fast",v(i));if((this.rel?.bufferedAmount??0)>E)return false;let t=b(i,this.msgSeq++);for(let s of t)if(!this.raw("rel",s))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,i){let t=e==="rel"?this.rel:this.fast;if(!t||t.readyState!=="open")return false;try{return t.send(i),this.lastSend=Date.now(),this.bytesOut+=i.byteLength,!0}catch{return false}}close(e="closed",i=false){if(this.state!=="closed"){this.state="closed",i&&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=this.pc.ontrack=null,this.audioTx=null,this.remoteAudio=null;try{this.pc.close();}catch{}this.reassembler.reset(),this.o.onClose(e);}}};function R(o){if(!o)return [];try{let e=JSON.parse(o);return !e||e.v!==1||!Array.isArray(e.m)?[]:e.m.filter(i=>!!i&&typeof i=="object"&&typeof i.t=="string")}catch{return []}}var f=class{constructor(e,i={}){this.send=e;this.perTargetGapMs=i.perTargetGapMs??650,this.globalGapMs=i.globalGapMs??180,this.maxPayloadBytes=i.maxPayloadBytes??15e3,this.maxAttempts=i.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,i){if(this.closed)return;let t=this.queues.get(e)??{msgs:[],attempts:0},s=t.msgs[t.msgs.length-1];i.t==="ice"&&s?.t==="ice"&&s.lid===i.lid?s.c.push(...i.c):t.msgs.push(i),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(),i=null,t=1/0;for(let s of this.queues.keys()){let r=Math.max((this.lastSent.get(s)??0)+this.perTargetGapMs,this.lastAny+this.globalGapMs);if(r<=e){i=s;break}t=Math.min(t,r-e);}if(i===null){t!==1/0&&(this.timer=setTimeout(()=>{this.timer=null,this.pump();},t));return}this.flush(i);}async flush(e){let i=this.queues.get(e);if(!i||i.msgs.length===0){this.queues.delete(e),this.pump();return}let t=[],s="";for(let l of i.msgs){let h=JSON.stringify({v:1,m:[...t,l]});if(t.length>0&&O(h)>this.maxPayloadBytes)break;t.push(l),s=h;}let r=i.msgs.slice(t.length);r.length?this.queues.set(e,{msgs:r,attempts:0}):this.queues.delete(e),this.inflight=true;let n=null;try{n=await this.send(e,"rtc",s);}catch{n=null;}this.inflight=false;let a=Date.now();if(this.lastSent.set(e,a),this.lastAny=a,!n?.ok&&!this.closed){let l=n?.ok===false?n.reason:"connection";if((l==="throttled"||l==="connection")&&i.attempts+1<this.maxAttempts){let A=this.queues.get(e);this.queues.set(e,{msgs:[...t,...A?.msgs??[]],attempts:i.attempts+1});}}this.pump();}};function O(o){return new TextEncoder().encode(o).byteLength}var L={pollFastMs:1e3,pollHostIdleMs:2500,pollClientIdleMs:2e4,fastWindowMs:15e3,keepaliveMs:1e3,peerTimeoutMs:6e3,iceGatherTimeoutMs:1200,maxSignalPayloadBytes:15e3,signalPerTargetGapMs:650,signalGlobalGapMs:180},y=class o{constructor(e,i,t,s){this.client=e;this.selfId=i,this.roomId=t.RoomID??"",this.topology=t.Topology??"Mesh",this.chatMode=t.ChatMode??"ServerRelay",this.mode=t.Mode??null,this.voice=t.Voice===true,this.ownerId=t.OwnerUserID??"",this.hostId=t.HostUserID??"",this.lastSeq=t.Seq??0,this.iceServers=p(t.IceServers),this.o={...L,leaveOnPageHide:true,...Object.fromEntries(Object.entries(s).filter(([,r])=>r!==void 0)),createPeerConnection:s.createPeerConnection??(r=>new RTCPeerConnection(r))};for(let r of t.Members??[])r.UserID&&this.members.set(r.UserID,r);this.outbox=new f((r,n,a)=>this.client.multiplayer.sendSignal(this.roomId,r,n,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;voice;ownerId;hostId;members=new Map;o;iceServers;lastSeq;links=new Map;dataPeers=new Set;micTrack=null;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,i,t={},s={}){let r=e.auth.context?.userID;if(!r)return c("unauthorized","Not logged in.");let n=await e.multiplayer.createRoom(i,t);return n.ok?{ok:true,data:o.start(e,r,n.data,s)}:n}static async join(e,i,t,s={}){let r=e.auth.context?.userID;if(!r)return c("unauthorized","Not logged in.");let n=await e.multiplayer.joinRoom(i,t);return n.ok?{ok:true,data:o.start(e,r,n.data,s)}:n}static start(e,i,t,s){let r=new o(e,i,t,s);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,i){let t=this.listeners.get(e)??new Set;return t.add(i),this.listeners.set(e,t),()=>t.delete(i)}openPeers(){return [...this.links.values()].filter(e=>e.state==="open"&&this.dataPeers.has(e.peerId)).map(e=>e.peerId)}isOpen(e){return this.dataPeers.has(e)&&this.links.get(e)?.state==="open"}linkStats(e){let i=this.links.get(e);return i?{rttMs:i.rttMs,bytesIn:i.bytesIn,bytesOut:i.bytesOut,buffered:i.relBuffered}:null}send(e,i,t){return this.dataPeers.has(e)?this.links.get(e)?.send(i,t)??false:false}broadcast(e,i,t){let s=0;for(let r of this.links.values())r.peerId!==t&&r.state==="open"&&this.dataPeers.has(r.peerId)&&r.send(e,i)&&s++;return s}setMicTrack(e){this.micTrack=this.voice?e:null;for(let i of this.links.values())i.setMicTrack(this.micTrack);}remoteAudio(e){return this.links.get(e)?.remoteAudio??null}setExtraPeers(e){this.extraPeers=new Set([...e].filter(i=>i!==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,i=false){let t=await this.client.multiplayer.kickMember(this.roomId,e,i);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(),this.emit("left",{}),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(i=>i.state==="connecting")||[...this.wanted()].some(i=>!this.links.has(i))?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 i=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(),i??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 i=e.FromUserID??"";switch(e.Type){case "Signal":e.ToUserID===this.selfId&&e.Kind==="rtc"&&this.handleSignals(i,R(e.Payload));break;case "PlayerJoined":{let t=e.Payload||i;if(!t||t===this.selfId)break;if(!this.members.has(t)){let s={UserID:t};this.members.set(t,s),this.emit("memberJoined",{member:s});}if(this.fastUntil=Date.now()+this.o.fastWindowMs,this.scheduleRefresh(),this.voice&&this.isHost)for(let s of this.links.values())s.peerId!==t&&s.state==="open"&&s.notice(1);break}case "PlayerLeft":{let t=e.Payload||i,s=e.Kind==="kicked"?"kicked":e.Kind==="timeout"?"timeout":"left";if(t===this.selfId){s!=="left"&&this.end("removed",{reason:s});break}this.dropMember(t,s,s==="kicked"?i:void 0);break}case "HostChanged":{let t=e.Payload??"";if(t&&t!==this.hostId){let s=this.hostId||null;this.hostId=t,this.fastUntil=Date.now()+this.o.fastWindowMs,this.emit("hostChanged",{hostId:t,previousHostId:s});}break}case "RoomClosed":this.end("roomClosed",{});break;case "MemberState":this.scheduleRefresh();break;case "Chat":this.emit("chat",{from:i,text:e.Payload??""});break}}dropMember(e,i,t){let s=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),s&&this.emit("memberLeft",{userId:e,kind:i,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=p(e.IceServers)),e.OwnerUserID&&(this.ownerId=e.OwnerUserID);let i=new Map;for(let t of e.Members??[])t.UserID&&i.set(t.UserID,t);for(let t of [...this.members.keys()])!i.has(t)&&t!==this.selfId&&this.dropMember(t,"left");for(let[t,s]of i){let r=this.members.has(t);this.members.set(t,s),!r&&t!==this.selfId&&this.emit("memberJoined",{member:s});}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=this.dataWanted();if(this.voice)for(let i of this.members.keys())i!==this.selfId&&e.add(i);return e}dataWanted(){let e=new Set,i=[...this.members.keys()].filter(t=>t!==this.selfId);if(this.topology==="Mesh"||this.isHost)for(let t of i)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(),i=this.dataWanted();for(let t of this.links.values())t.state==="open"&&i.has(t.peerId)&&this.announce(t.peerId);for(let t of this.wanted())if(!(this.links.has(t)||this.retry.get(t)?.timer))if(this.selfId<t)this.openLink(t,true,w());else {let s=this.wantSentAt.get(t)??0;e-s>8e3&&(this.wantSentAt.set(t,e),this.outbox.enqueue(t,{t:"want"}));}}handleSignals(e,i){if(!(!e||e===this.selfId)){this.members.has(e)||(this.members.set(e,{UserID:e}),this.scheduleRefresh());for(let t of i){let s=this.links.get(e);if(t.t==="want"){(!s||s.state==="closed")&&this.openLink(e,true,w());continue}if(t.t==="offer"){if(s?.lid===t.lid)continue;s&&this.closeLink(e,"replaced by a new offer"),this.openLink(e,false,t.lid).handle(t);continue}s&&s.lid===t.lid&&s.handle(t);}}}openLink(e,i,t){this.wantSentAt.delete(e);let s=new m({peerId:e,offerer:i,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.retry.delete(e),this.dataWanted().has(e)&&this.announce(e);},onClose:r=>this.onLinkClosed(s,r),onMessage:(r,n)=>this.emit("message",{from:e,channel:r,data:n}),onNotice:r=>{r===1&&this.schedulePoll(0);},audio:this.voice,onAudio:r=>{this.links.get(e)===s&&this.emit("peerAudio",{peerId:e,track:r});}});return this.micTrack&&s.setMicTrack(this.micTrack),this.links.set(e,s),this.schedulePoll(Math.min(this.o.pollFastMs,250)),s}closeLink(e,i){let t=this.links.get(e);t&&(this.links.delete(e),t.close(i,true));}onLinkClosed(e,i){let t=e.peerId,s=this.links.get(t)===e;if(s&&this.links.delete(t),this.voice&&!this.links.has(t)&&this.emit("peerAudio",{peerId:t,track:null}),this.dataPeers.delete(t)&&this.emit("peerClose",{peerId:t,reason:i}),!s||this.stopped||!this.members.has(t)||!this.wanted().has(t))return;let r=this.retry.get(t)??{attempts:0,timer:null},n=Math.min(15e3,1e3*2**r.attempts);r.attempts++,r.timer=setTimeout(()=>{r.timer=null,this.wantSentAt.delete(t),this.reconcile();},n),this.retry.set(t,r);}announce(e){this.dataPeers.has(e)||(this.dataPeers.add(e),this.emit("peerOpen",{peerId:e}));}emit(e,i){for(let t of this.listeners.get(e)??[])try{t(i);}catch(s){console.error(`[RealtimeSession] ${String(e)} handler failed`,s);}}end(e,i){this.stopped||(this.stop(),this.emit(e,i));}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 i=this.links.get(e);this.links.delete(e),i?.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.emit("left",{}),this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e,keepalive:true});}};function w(){let o=globalThis.crypto;return o&&"randomUUID"in o?o.randomUUID().slice(0,12):Math.random().toString(36).slice(2,14)}var M=class{constructor(e,i={}){this.session=e;if(this.o={speakingThreshold:i.speakingThreshold??.02,levelIntervalMs:i.levelIntervalMs??100,speakingHoldMs:i.speakingHoldMs??300,attachElement:i.attachElement??D,getUserMedia:i.getUserMedia,createAudioContext:i.createAudioContext,createStream:i.createStream},!!e.voice){this.offs.push(e.on("peerAudio",({peerId:t,track:s})=>s?this.addPeer(t,s):this.removePeer(t)),e.on("memberLeft",({userId:t})=>this.removePeer(t)),e.on("left",()=>this.destroy()),e.on("removed",()=>this.destroy()),e.on("roomClosed",()=>this.destroy()));for(let t of e.members.keys()){let s=e.remoteAudio(t);s&&this.addPeer(t,s);}typeof document<"u"&&(document.addEventListener("pointerdown",this.onGesture,true),document.addEventListener("keydown",this.onGesture,true));}}session;o;ctx=null;micStream=null;self=null;peers=new Map;muted=new Set;volumes=new Map;speakingIds=new Set;levelMap=new Map;modeValue="off";modeSeq=0;wantMode="off";acquiring=null;pushed=false;timer=null;destroyed=false;offs=[];listeners=new Map;onGesture=()=>{this.resume(),this.ctx?.state==="running"&&this.stopGestureWatch();};stopGestureWatch(){typeof document>"u"||(document.removeEventListener("pointerdown",this.onGesture,true),document.removeEventListener("keydown",this.onGesture,true));}get available(){return this.session.voice&&!this.destroyed}get mode(){return this.modeValue}get transmitting(){return this.micStream!=null&&(this.modeValue==="open"||this.modeValue==="push"&&this.pushed)}micTrack(){return this.micStream?.getAudioTracks()[0]??null}peerTracks(){let e=[];for(let i of this.peers.keys()){let t=this.session.remoteAudio(i);t&&e.push(t);}return e}isSpeaking(e){return this.speakingIds.has(e)}speaking(){return [...this.speakingIds]}level(e){return this.levelMap.get(e)??0}isPeerMuted(e){return this.muted.has(e)}peerVolume(e){return this.volumes.get(e)??1}hasVoice(e){return this.peers.has(e)}on(e,i){let t=this.listeners.get(e)??new Set;return t.add(i),this.listeners.set(e,t),()=>t.delete(i)}graph(){if(!this.ctx)return null;let e=new Map;for(let[i,t]of this.peers)e.set(i,t.gain??t.source);return {context:this.ctx,mic:this.self?.source??null,peers:e}}async setMode(e){if(!this.available)return c("client","Voice chat is off in this room.");let i=++this.modeSeq;if(this.wantMode=e,this.resume(),e==="off")return this.modeValue="off",this.pushed=false,this.releaseMic(),this.emit("change",{}),d(e);if(!this.micStream){this.acquiring??=this.acquireMic().finally(()=>{this.acquiring=null;});let t=await this.acquiring;if(!t.ok)return t}return this.destroyed?c("client","The room is closed."):i!==this.modeSeq?(this.wantMode==="off"&&this.releaseMic(),d(this.wantMode)):(this.modeValue=e,this.applyTransmit(),this.emit("change",{}),d(e))}setPushed(e){this.pushed!==e&&(this.pushed=e,this.modeValue==="push"&&(this.applyTransmit(),this.emit("change",{})));}setPeerMuted(e,i){i?this.muted.add(e):this.muted.delete(e),this.applyGain(e),this.emit("change",{});}setPeerVolume(e,i){let t=Number.isFinite(i)?Math.min(2,Math.max(0,i)):1;this.volumes.set(e,t),this.applyGain(e),this.emit("change",{});}resume(){this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume();}destroy(){if(this.destroyed)return;this.destroyed=true;for(let i of this.offs.splice(0))i();this.stopGestureWatch(),this.releaseMic();for(let i of [...this.peers.keys()])this.removePeer(i);this.stopTimer();let e=this.ctx;this.ctx=null,e&&e.state!=="closed"&&e.close().catch(()=>{}),this.modeValue="off",this.emit("change",{}),this.listeners.clear();}async acquireMic(){let e=this.o.getUserMedia??(typeof navigator<"u"&&navigator.mediaDevices?.getUserMedia?r=>navigator.mediaDevices.getUserMedia(r):null);if(!e)return c("client","This browser has no microphone access.");let i;try{i=await e({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1});}catch(r){return c("unauthorized",`Microphone refused: ${String(r)}`)}let t=i.getAudioTracks()[0];if(!t||this.destroyed){for(let r of i.getTracks())r.stop();return c("client","No microphone track.")}this.micStream=i,t.enabled=false,t.onended=()=>{this.micStream?.getAudioTracks()[0]===t&&(this.modeValue=this.wantMode="off",this.pushed=false,this.releaseMic(),this.emit("change",{}));},this.session.setMicTrack(t);let s=this.context();return s&&(this.self=this.makeVoice(s,i,false)),this.ensureTimer(),d(this.modeValue)}releaseMic(){if(this.micStream){this.session.setMicTrack(null);for(let e of this.micStream.getTracks())e.stop();this.micStream=null,this.self&&(this.disposeVoice(this.self),this.self=null),this.setSpeaking(this.session.selfId,false),this.levelMap.delete(this.session.selfId);}}applyTransmit(){let e=this.micStream?.getAudioTracks()[0];e&&(e.enabled=this.transmitting);}addPeer(e,i){if(this.destroyed)return;this.removePeer(e,false);let t=this.context();if(!t)return;let s=this.o.createStream?this.o.createStream([i]):new MediaStream([i]);this.peers.set(e,this.makeVoice(t,s,true)),this.applyGain(e),this.ensureTimer(),this.emit("change",{});}removePeer(e,i=true){let t=this.peers.get(e);t&&(this.peers.delete(e),this.disposeVoice(t),this.setSpeaking(e,false),this.levelMap.delete(e),!this.peers.size&&!this.self&&this.stopTimer(),i&&this.emit("change",{}));}applyGain(e){let i=this.peers.get(e);i?.gain&&(i.gain.gain.value=this.muted.has(e)?0:this.peerVolume(e));}makeVoice(e,i,t){let s=e.createMediaStreamSource(i),r=e.createAnalyser();r.fftSize=512,s.connect(r);let n=null,a=()=>{};return t&&(n=e.createGain(),s.connect(n),n.connect(e.destination),a=this.o.attachElement(i)),{source:s,analyser:r,gain:n,detach:a,level:0,loudUntil:0}}disposeVoice(e){try{e.source.disconnect(),e.analyser.disconnect(),e.gain?.disconnect();}catch{}e.detach();}context(){if(this.ctx)return this.ctx;try{this.ctx=this.o.createAudioContext?this.o.createAudioContext():new AudioContext;}catch{return null}return this.ctx}ensureTimer(){this.timer||this.destroyed||(this.timer=setInterval(()=>this.measure(),this.o.levelIntervalMs));}stopTimer(){this.timer&&clearInterval(this.timer),this.timer=null;}measure(){let e=Date.now(),i=new Float32Array(512),t=(s,r,n)=>{r.analyser.getFloatTimeDomainData(i);let a=0;for(let h=0;h<i.length;h++)a+=i[h]*i[h];let l=n?Math.sqrt(a/i.length):0;r.level=l,this.levelMap.set(s,l),l>this.o.speakingThreshold&&(r.loudUntil=e+this.o.speakingHoldMs),this.setSpeaking(s,e<r.loudUntil);};this.self&&t(this.session.selfId,this.self,this.transmitting);for(let[s,r]of this.peers)t(s,r,!this.muted.has(s));this.emit("levels",{levels:this.levelMap});}setSpeaking(e,i){this.speakingIds.has(e)!==i&&(i?this.speakingIds.add(e):this.speakingIds.delete(e),this.emit("change",{}));}emit(e,i){for(let t of this.listeners.get(e)??[])try{t(i);}catch(s){console.error(`[VoiceController] ${String(e)} handler failed`,s);}}};function D(o){if(typeof Audio>"u")return ()=>{};let e=new Audio;return e.muted=true,e.srcObject=o,e.play().catch(()=>{}),()=>{e.pause(),e.srcObject=null;}}exports.MAX_MESSAGE_BYTES=g;exports.RealtimeSession=y;exports.VoiceController=M;exports.toRtcIceServers=p;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { I as IceServer } from '../
|
|
2
|
-
export { C as ChannelName, M as MemberLeftKind, R as RealtimeClient,
|
|
1
|
+
import { I as IceServer } from '../VoiceController-ClFmHUGH.cjs';
|
|
2
|
+
export { C as ChannelName, M as MemberLeftKind, a as MicMode, R as RealtimeClient, b as RealtimeSession, c as RealtimeSessionEvents, d as RealtimeSessionOptions, V as VoiceController, e as VoiceControllerEvents, f as VoiceControllerOptions } from '../VoiceController-ClFmHUGH.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '../PlatformAdapter-DU_8HalI.cjs';
|
|
5
5
|
import 'decimal.js';
|
package/dist/realtime/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { I as IceServer } from '../
|
|
2
|
-
export { C as ChannelName, M as MemberLeftKind, R as RealtimeClient,
|
|
1
|
+
import { I as IceServer } from '../VoiceController-JKfvxpjs.js';
|
|
2
|
+
export { C as ChannelName, M as MemberLeftKind, a as MicMode, R as RealtimeClient, b as RealtimeSession, c as RealtimeSessionEvents, d as RealtimeSessionOptions, V as VoiceController, e as VoiceControllerEvents, f as VoiceControllerOptions } from '../VoiceController-JKfvxpjs.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '../PlatformAdapter-DU_8HalI.js';
|
|
5
5
|
import 'decimal.js';
|
package/dist/realtime/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b}from'../chunk-CS7ACWDY.js';var f=16384;function g(o){let e=new Uint8Array(o.byteLength+1);return e[0]=0,e.set(o,1),e}function v(o,e){if(o.byteLength+1<=16384)return [g(o)];if(o.byteLength>67108864)throw new RangeError(`Message of ${o.byteLength} bytes exceeds 67108864.`);let s=Math.ceil(o.byteLength/16375),t=[];for(let i=0;i<s;i++){let r=o.subarray(i*16375,Math.min(o.byteLength,(i+1)*16375)),n=new Uint8Array(9+r.byteLength),a=new DataView(n.buffer);n[0]=1,a.setUint32(1,e>>>0),a.setUint16(5,i),a.setUint16(7,s),n.set(r,9),t.push(n);}return t}var c=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 n=e.subarray(9);if(this.bytes+=n.byteLength,this.bytes>67108864)return this.reset(),null;if(this.parts.push(n),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 p(o){let e=new Map;for(let s of o??[]){let t=s.Urls?.trim();if(!t)continue;let i=s.Username??void 0,r=s.Credential??void 0,n=`${i??""}\0${r??""}`,a=e.get(n);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(n,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 c;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(o){if(!o)return [];try{let e=JSON.parse(o);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 n=null;try{n=await this.send(e,"rtc",i);}catch{n=null;}this.inflight=false;let a=Date.now();if(this.lastSent.set(e,a),this.lastAny=a,!n?.ok&&!this.closed){let l=n?.ok===false?n.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(o){return new TextEncoder().encode(o).byteLength}var D={pollFastMs:1e3,pollHostIdleMs:2500,pollClientIdleMs:2e4,fastWindowMs:15e3,keepaliveMs:1e3,peerTimeoutMs:6e3,iceGatherTimeoutMs:1200,maxSignalPayloadBytes:15e3,signalPerTargetGapMs:650,signalGlobalGapMs:180},y=class o{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=p(t.IceServers),this.o={...D,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,n,a)=>this.client.multiplayer.sendSignal(this.roomId,r,n,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 b("unauthorized","Not logged in.");let n=await e.multiplayer.createRoom(s,t);return n.ok?{ok:true,data:o.start(e,r,n.data,i)}:n}static async join(e,s,t,i={}){let r=e.auth.context?.userID;if(!r)return b("unauthorized","Not logged in.");let n=await e.multiplayer.joinRoom(s,t);return n.ok?{ok:true,data:o.start(e,r,n.data,i)}:n}static start(e,s,t,i){let r=new o(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(),this.emit("left",{}),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=p(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,n)=>this.emit("message",{from:e,channel:r,data:n}),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},n=Math.min(15e3,1e3*2**r.attempts);r.attempts++,r.timer=setTimeout(()=>{r.timer=null,this.wantSentAt.delete(t),this.reconcile();},n),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.emit("left",{}),this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e,keepalive:true});}};function I(){let o=globalThis.crypto;return o&&"randomUUID"in o?o.randomUUID().slice(0,12):Math.random().toString(36).slice(2,14)}export{f as MAX_MESSAGE_BYTES,y as RealtimeSession,p as toRtcIceServers};
|
|
1
|
+
import {b as b$1,a}from'../chunk-CS7ACWDY.js';var g=16384;function v(o){let e=new Uint8Array(o.byteLength+1);return e[0]=0,e.set(o,1),e}function b(o,e){if(o.byteLength+1<=16384)return [v(o)];if(o.byteLength>67108864)throw new RangeError(`Message of ${o.byteLength} bytes exceeds 67108864.`);let i=Math.ceil(o.byteLength/16375),t=[];for(let s=0;s<i;s++){let r=o.subarray(s*16375,Math.min(o.byteLength,(s+1)*16375)),n=new Uint8Array(9+r.byteLength),a=new DataView(n.buffer);n[0]=1,a.setUint32(1,e>>>0),a.setUint16(5,s),a.setUint16(7,i),n.set(r,9),t.push(n);}return t}var u=class{id=-1;count=0;parts=[];bytes=0;push(e){if(e.byteLength<9)return null;let i=new DataView(e.buffer,e.byteOffset,e.byteLength),t=i.getUint32(1),s=i.getUint16(5),r=i.getUint16(7);if(s===0&&(this.id=t,this.count=r,this.parts=[],this.bytes=0),t!==this.id||s!==this.parts.length||r!==this.count)return this.reset(),null;let n=e.subarray(9);if(this.bytes+=n.byteLength,this.bytes>67108864)return this.reset(),null;if(this.parts.push(n),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 p(o){let e=new Map;for(let i of o??[]){let t=i.Urls?.trim();if(!t)continue;let s=i.Username??void 0,r=i.Credential??void 0,n=`${s??""}\0${r??""}`,a=e.get(n);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]};s&&(l.username=s),r&&(l.credential=r),e.set(n,l);}return [...e.values()]}var E=4*1024*1024,P=5e3,m=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=i=>{if(!i.candidate){this.sendDescriptionIfReady();return}this.descriptionSent&&this.lateIce.push(i.candidate.toJSON()),this.flushLateIce();},this.pc.onconnectionstatechange=()=>{let i=this.pc.connectionState;(i==="failed"||i==="closed")&&this.close(`connection ${i}`);},this.pc.ondatachannel=i=>this.adopt(i.channel),this.pc.ontrack=i=>{i.track?.kind!=="audio"||this.state==="closed"||(this.remoteAudio=i.track,this.o.onAudio?.(i.track));},this.openTimer=setTimeout(()=>{this.state==="connecting"&&this.close("connect timeout");},Math.max(15e3,e.peerTimeoutMs*3)),this.offerer&&(e.audio&&(this.audioTx=this.pc.addTransceiver("audio",{direction:"sendrecv"})),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 u;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;audioTx=null;micTrack=null;remoteAudio=null;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}),this.o.audio&&this.adoptAudio(),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 i of e.c)await this.addIce(i);else e.t==="bye"&&this.close("peer closed the link");}catch(i){this.close(`signaling failed: ${String(i)}`);}}adoptAudio(){let e=this.pc.getTransceivers().find(i=>i.receiver.track?.kind==="audio"&&i.currentDirection!=="stopped")??null;e&&(e.direction="sendrecv",this.audioTx=e,this.micTrack&&this.applyMic());}setMicTrack(e){this.micTrack=e,this.applyMic();}applyMic(){!this.audioTx||this.state==="closed"||this.audioTx.sender.replaceTrack(this.micTrack).catch(()=>{});}async drainRemoteIce(){let e=this.pendingRemoteIce.splice(0);for(let i of e)await this.addIce(i);}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=i=>this.receive(e.label,i.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>=P)&&(this.pingSentAt=e,this.raw("fast",new Uint8Array([2])));}receive(e,i){if(!(i instanceof ArrayBuffer))return;let t=new Uint8Array(i);this.lastRecv=Date.now(),this.bytesIn+=t.byteLength;let s=t[0];if(s===0)this.o.onMessage(e,t.subarray(1));else if(s===1&&e==="rel"){let r=this.reassembler.push(t);r&&this.o.onMessage(e,r);}else s===2?this.raw("fast",new Uint8Array([3])):s===3?this.pingSentAt&&(this.rttMs=Date.now()-this.pingSentAt):s===4&&e==="rel"&&this.o.onNotice?.(t[1]??0);}send(e,i){if(this.state!=="open")return false;if(e==="fast")return i.byteLength+1>16384?false:this.raw("fast",v(i));if((this.rel?.bufferedAmount??0)>E)return false;let t=b(i,this.msgSeq++);for(let s of t)if(!this.raw("rel",s))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,i){let t=e==="rel"?this.rel:this.fast;if(!t||t.readyState!=="open")return false;try{return t.send(i),this.lastSend=Date.now(),this.bytesOut+=i.byteLength,!0}catch{return false}}close(e="closed",i=false){if(this.state!=="closed"){this.state="closed",i&&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=this.pc.ontrack=null,this.audioTx=null,this.remoteAudio=null;try{this.pc.close();}catch{}this.reassembler.reset(),this.o.onClose(e);}}};function R(o){if(!o)return [];try{let e=JSON.parse(o);return !e||e.v!==1||!Array.isArray(e.m)?[]:e.m.filter(i=>!!i&&typeof i=="object"&&typeof i.t=="string")}catch{return []}}var f=class{constructor(e,i={}){this.send=e;this.perTargetGapMs=i.perTargetGapMs??650,this.globalGapMs=i.globalGapMs??180,this.maxPayloadBytes=i.maxPayloadBytes??15e3,this.maxAttempts=i.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,i){if(this.closed)return;let t=this.queues.get(e)??{msgs:[],attempts:0},s=t.msgs[t.msgs.length-1];i.t==="ice"&&s?.t==="ice"&&s.lid===i.lid?s.c.push(...i.c):t.msgs.push(i),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(),i=null,t=1/0;for(let s of this.queues.keys()){let r=Math.max((this.lastSent.get(s)??0)+this.perTargetGapMs,this.lastAny+this.globalGapMs);if(r<=e){i=s;break}t=Math.min(t,r-e);}if(i===null){t!==1/0&&(this.timer=setTimeout(()=>{this.timer=null,this.pump();},t));return}this.flush(i);}async flush(e){let i=this.queues.get(e);if(!i||i.msgs.length===0){this.queues.delete(e),this.pump();return}let t=[],s="";for(let l of i.msgs){let h=JSON.stringify({v:1,m:[...t,l]});if(t.length>0&&O(h)>this.maxPayloadBytes)break;t.push(l),s=h;}let r=i.msgs.slice(t.length);r.length?this.queues.set(e,{msgs:r,attempts:0}):this.queues.delete(e),this.inflight=true;let n=null;try{n=await this.send(e,"rtc",s);}catch{n=null;}this.inflight=false;let a=Date.now();if(this.lastSent.set(e,a),this.lastAny=a,!n?.ok&&!this.closed){let l=n?.ok===false?n.reason:"connection";if((l==="throttled"||l==="connection")&&i.attempts+1<this.maxAttempts){let A=this.queues.get(e);this.queues.set(e,{msgs:[...t,...A?.msgs??[]],attempts:i.attempts+1});}}this.pump();}};function O(o){return new TextEncoder().encode(o).byteLength}var L={pollFastMs:1e3,pollHostIdleMs:2500,pollClientIdleMs:2e4,fastWindowMs:15e3,keepaliveMs:1e3,peerTimeoutMs:6e3,iceGatherTimeoutMs:1200,maxSignalPayloadBytes:15e3,signalPerTargetGapMs:650,signalGlobalGapMs:180},y=class o{constructor(e,i,t,s){this.client=e;this.selfId=i,this.roomId=t.RoomID??"",this.topology=t.Topology??"Mesh",this.chatMode=t.ChatMode??"ServerRelay",this.mode=t.Mode??null,this.voice=t.Voice===true,this.ownerId=t.OwnerUserID??"",this.hostId=t.HostUserID??"",this.lastSeq=t.Seq??0,this.iceServers=p(t.IceServers),this.o={...L,leaveOnPageHide:true,...Object.fromEntries(Object.entries(s).filter(([,r])=>r!==void 0)),createPeerConnection:s.createPeerConnection??(r=>new RTCPeerConnection(r))};for(let r of t.Members??[])r.UserID&&this.members.set(r.UserID,r);this.outbox=new f((r,n,a)=>this.client.multiplayer.sendSignal(this.roomId,r,n,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;voice;ownerId;hostId;members=new Map;o;iceServers;lastSeq;links=new Map;dataPeers=new Set;micTrack=null;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,i,t={},s={}){let r=e.auth.context?.userID;if(!r)return b$1("unauthorized","Not logged in.");let n=await e.multiplayer.createRoom(i,t);return n.ok?{ok:true,data:o.start(e,r,n.data,s)}:n}static async join(e,i,t,s={}){let r=e.auth.context?.userID;if(!r)return b$1("unauthorized","Not logged in.");let n=await e.multiplayer.joinRoom(i,t);return n.ok?{ok:true,data:o.start(e,r,n.data,s)}:n}static start(e,i,t,s){let r=new o(e,i,t,s);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,i){let t=this.listeners.get(e)??new Set;return t.add(i),this.listeners.set(e,t),()=>t.delete(i)}openPeers(){return [...this.links.values()].filter(e=>e.state==="open"&&this.dataPeers.has(e.peerId)).map(e=>e.peerId)}isOpen(e){return this.dataPeers.has(e)&&this.links.get(e)?.state==="open"}linkStats(e){let i=this.links.get(e);return i?{rttMs:i.rttMs,bytesIn:i.bytesIn,bytesOut:i.bytesOut,buffered:i.relBuffered}:null}send(e,i,t){return this.dataPeers.has(e)?this.links.get(e)?.send(i,t)??false:false}broadcast(e,i,t){let s=0;for(let r of this.links.values())r.peerId!==t&&r.state==="open"&&this.dataPeers.has(r.peerId)&&r.send(e,i)&&s++;return s}setMicTrack(e){this.micTrack=this.voice?e:null;for(let i of this.links.values())i.setMicTrack(this.micTrack);}remoteAudio(e){return this.links.get(e)?.remoteAudio??null}setExtraPeers(e){this.extraPeers=new Set([...e].filter(i=>i!==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,i=false){let t=await this.client.multiplayer.kickMember(this.roomId,e,i);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(),this.emit("left",{}),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(i=>i.state==="connecting")||[...this.wanted()].some(i=>!this.links.has(i))?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 i=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(),i??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 i=e.FromUserID??"";switch(e.Type){case "Signal":e.ToUserID===this.selfId&&e.Kind==="rtc"&&this.handleSignals(i,R(e.Payload));break;case "PlayerJoined":{let t=e.Payload||i;if(!t||t===this.selfId)break;if(!this.members.has(t)){let s={UserID:t};this.members.set(t,s),this.emit("memberJoined",{member:s});}if(this.fastUntil=Date.now()+this.o.fastWindowMs,this.scheduleRefresh(),this.voice&&this.isHost)for(let s of this.links.values())s.peerId!==t&&s.state==="open"&&s.notice(1);break}case "PlayerLeft":{let t=e.Payload||i,s=e.Kind==="kicked"?"kicked":e.Kind==="timeout"?"timeout":"left";if(t===this.selfId){s!=="left"&&this.end("removed",{reason:s});break}this.dropMember(t,s,s==="kicked"?i:void 0);break}case "HostChanged":{let t=e.Payload??"";if(t&&t!==this.hostId){let s=this.hostId||null;this.hostId=t,this.fastUntil=Date.now()+this.o.fastWindowMs,this.emit("hostChanged",{hostId:t,previousHostId:s});}break}case "RoomClosed":this.end("roomClosed",{});break;case "MemberState":this.scheduleRefresh();break;case "Chat":this.emit("chat",{from:i,text:e.Payload??""});break}}dropMember(e,i,t){let s=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),s&&this.emit("memberLeft",{userId:e,kind:i,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=p(e.IceServers)),e.OwnerUserID&&(this.ownerId=e.OwnerUserID);let i=new Map;for(let t of e.Members??[])t.UserID&&i.set(t.UserID,t);for(let t of [...this.members.keys()])!i.has(t)&&t!==this.selfId&&this.dropMember(t,"left");for(let[t,s]of i){let r=this.members.has(t);this.members.set(t,s),!r&&t!==this.selfId&&this.emit("memberJoined",{member:s});}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=this.dataWanted();if(this.voice)for(let i of this.members.keys())i!==this.selfId&&e.add(i);return e}dataWanted(){let e=new Set,i=[...this.members.keys()].filter(t=>t!==this.selfId);if(this.topology==="Mesh"||this.isHost)for(let t of i)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(),i=this.dataWanted();for(let t of this.links.values())t.state==="open"&&i.has(t.peerId)&&this.announce(t.peerId);for(let t of this.wanted())if(!(this.links.has(t)||this.retry.get(t)?.timer))if(this.selfId<t)this.openLink(t,true,w());else {let s=this.wantSentAt.get(t)??0;e-s>8e3&&(this.wantSentAt.set(t,e),this.outbox.enqueue(t,{t:"want"}));}}handleSignals(e,i){if(!(!e||e===this.selfId)){this.members.has(e)||(this.members.set(e,{UserID:e}),this.scheduleRefresh());for(let t of i){let s=this.links.get(e);if(t.t==="want"){(!s||s.state==="closed")&&this.openLink(e,true,w());continue}if(t.t==="offer"){if(s?.lid===t.lid)continue;s&&this.closeLink(e,"replaced by a new offer"),this.openLink(e,false,t.lid).handle(t);continue}s&&s.lid===t.lid&&s.handle(t);}}}openLink(e,i,t){this.wantSentAt.delete(e);let s=new m({peerId:e,offerer:i,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.retry.delete(e),this.dataWanted().has(e)&&this.announce(e);},onClose:r=>this.onLinkClosed(s,r),onMessage:(r,n)=>this.emit("message",{from:e,channel:r,data:n}),onNotice:r=>{r===1&&this.schedulePoll(0);},audio:this.voice,onAudio:r=>{this.links.get(e)===s&&this.emit("peerAudio",{peerId:e,track:r});}});return this.micTrack&&s.setMicTrack(this.micTrack),this.links.set(e,s),this.schedulePoll(Math.min(this.o.pollFastMs,250)),s}closeLink(e,i){let t=this.links.get(e);t&&(this.links.delete(e),t.close(i,true));}onLinkClosed(e,i){let t=e.peerId,s=this.links.get(t)===e;if(s&&this.links.delete(t),this.voice&&!this.links.has(t)&&this.emit("peerAudio",{peerId:t,track:null}),this.dataPeers.delete(t)&&this.emit("peerClose",{peerId:t,reason:i}),!s||this.stopped||!this.members.has(t)||!this.wanted().has(t))return;let r=this.retry.get(t)??{attempts:0,timer:null},n=Math.min(15e3,1e3*2**r.attempts);r.attempts++,r.timer=setTimeout(()=>{r.timer=null,this.wantSentAt.delete(t),this.reconcile();},n),this.retry.set(t,r);}announce(e){this.dataPeers.has(e)||(this.dataPeers.add(e),this.emit("peerOpen",{peerId:e}));}emit(e,i){for(let t of this.listeners.get(e)??[])try{t(i);}catch(s){console.error(`[RealtimeSession] ${String(e)} handler failed`,s);}}end(e,i){this.stopped||(this.stop(),this.emit(e,i));}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 i=this.links.get(e);this.links.delete(e),i?.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.emit("left",{}),this.client.multiplayer.leaveRoom(this.roomId,{successorUserID:e,keepalive:true});}};function w(){let o=globalThis.crypto;return o&&"randomUUID"in o?o.randomUUID().slice(0,12):Math.random().toString(36).slice(2,14)}var M=class{constructor(e,i={}){this.session=e;if(this.o={speakingThreshold:i.speakingThreshold??.02,levelIntervalMs:i.levelIntervalMs??100,speakingHoldMs:i.speakingHoldMs??300,attachElement:i.attachElement??D,getUserMedia:i.getUserMedia,createAudioContext:i.createAudioContext,createStream:i.createStream},!!e.voice){this.offs.push(e.on("peerAudio",({peerId:t,track:s})=>s?this.addPeer(t,s):this.removePeer(t)),e.on("memberLeft",({userId:t})=>this.removePeer(t)),e.on("left",()=>this.destroy()),e.on("removed",()=>this.destroy()),e.on("roomClosed",()=>this.destroy()));for(let t of e.members.keys()){let s=e.remoteAudio(t);s&&this.addPeer(t,s);}typeof document<"u"&&(document.addEventListener("pointerdown",this.onGesture,true),document.addEventListener("keydown",this.onGesture,true));}}session;o;ctx=null;micStream=null;self=null;peers=new Map;muted=new Set;volumes=new Map;speakingIds=new Set;levelMap=new Map;modeValue="off";modeSeq=0;wantMode="off";acquiring=null;pushed=false;timer=null;destroyed=false;offs=[];listeners=new Map;onGesture=()=>{this.resume(),this.ctx?.state==="running"&&this.stopGestureWatch();};stopGestureWatch(){typeof document>"u"||(document.removeEventListener("pointerdown",this.onGesture,true),document.removeEventListener("keydown",this.onGesture,true));}get available(){return this.session.voice&&!this.destroyed}get mode(){return this.modeValue}get transmitting(){return this.micStream!=null&&(this.modeValue==="open"||this.modeValue==="push"&&this.pushed)}micTrack(){return this.micStream?.getAudioTracks()[0]??null}peerTracks(){let e=[];for(let i of this.peers.keys()){let t=this.session.remoteAudio(i);t&&e.push(t);}return e}isSpeaking(e){return this.speakingIds.has(e)}speaking(){return [...this.speakingIds]}level(e){return this.levelMap.get(e)??0}isPeerMuted(e){return this.muted.has(e)}peerVolume(e){return this.volumes.get(e)??1}hasVoice(e){return this.peers.has(e)}on(e,i){let t=this.listeners.get(e)??new Set;return t.add(i),this.listeners.set(e,t),()=>t.delete(i)}graph(){if(!this.ctx)return null;let e=new Map;for(let[i,t]of this.peers)e.set(i,t.gain??t.source);return {context:this.ctx,mic:this.self?.source??null,peers:e}}async setMode(e){if(!this.available)return b$1("client","Voice chat is off in this room.");let i=++this.modeSeq;if(this.wantMode=e,this.resume(),e==="off")return this.modeValue="off",this.pushed=false,this.releaseMic(),this.emit("change",{}),a(e);if(!this.micStream){this.acquiring??=this.acquireMic().finally(()=>{this.acquiring=null;});let t=await this.acquiring;if(!t.ok)return t}return this.destroyed?b$1("client","The room is closed."):i!==this.modeSeq?(this.wantMode==="off"&&this.releaseMic(),a(this.wantMode)):(this.modeValue=e,this.applyTransmit(),this.emit("change",{}),a(e))}setPushed(e){this.pushed!==e&&(this.pushed=e,this.modeValue==="push"&&(this.applyTransmit(),this.emit("change",{})));}setPeerMuted(e,i){i?this.muted.add(e):this.muted.delete(e),this.applyGain(e),this.emit("change",{});}setPeerVolume(e,i){let t=Number.isFinite(i)?Math.min(2,Math.max(0,i)):1;this.volumes.set(e,t),this.applyGain(e),this.emit("change",{});}resume(){this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume();}destroy(){if(this.destroyed)return;this.destroyed=true;for(let i of this.offs.splice(0))i();this.stopGestureWatch(),this.releaseMic();for(let i of [...this.peers.keys()])this.removePeer(i);this.stopTimer();let e=this.ctx;this.ctx=null,e&&e.state!=="closed"&&e.close().catch(()=>{}),this.modeValue="off",this.emit("change",{}),this.listeners.clear();}async acquireMic(){let e=this.o.getUserMedia??(typeof navigator<"u"&&navigator.mediaDevices?.getUserMedia?r=>navigator.mediaDevices.getUserMedia(r):null);if(!e)return b$1("client","This browser has no microphone access.");let i;try{i=await e({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1});}catch(r){return b$1("unauthorized",`Microphone refused: ${String(r)}`)}let t=i.getAudioTracks()[0];if(!t||this.destroyed){for(let r of i.getTracks())r.stop();return b$1("client","No microphone track.")}this.micStream=i,t.enabled=false,t.onended=()=>{this.micStream?.getAudioTracks()[0]===t&&(this.modeValue=this.wantMode="off",this.pushed=false,this.releaseMic(),this.emit("change",{}));},this.session.setMicTrack(t);let s=this.context();return s&&(this.self=this.makeVoice(s,i,false)),this.ensureTimer(),a(this.modeValue)}releaseMic(){if(this.micStream){this.session.setMicTrack(null);for(let e of this.micStream.getTracks())e.stop();this.micStream=null,this.self&&(this.disposeVoice(this.self),this.self=null),this.setSpeaking(this.session.selfId,false),this.levelMap.delete(this.session.selfId);}}applyTransmit(){let e=this.micStream?.getAudioTracks()[0];e&&(e.enabled=this.transmitting);}addPeer(e,i){if(this.destroyed)return;this.removePeer(e,false);let t=this.context();if(!t)return;let s=this.o.createStream?this.o.createStream([i]):new MediaStream([i]);this.peers.set(e,this.makeVoice(t,s,true)),this.applyGain(e),this.ensureTimer(),this.emit("change",{});}removePeer(e,i=true){let t=this.peers.get(e);t&&(this.peers.delete(e),this.disposeVoice(t),this.setSpeaking(e,false),this.levelMap.delete(e),!this.peers.size&&!this.self&&this.stopTimer(),i&&this.emit("change",{}));}applyGain(e){let i=this.peers.get(e);i?.gain&&(i.gain.gain.value=this.muted.has(e)?0:this.peerVolume(e));}makeVoice(e,i,t){let s=e.createMediaStreamSource(i),r=e.createAnalyser();r.fftSize=512,s.connect(r);let n=null,a=()=>{};return t&&(n=e.createGain(),s.connect(n),n.connect(e.destination),a=this.o.attachElement(i)),{source:s,analyser:r,gain:n,detach:a,level:0,loudUntil:0}}disposeVoice(e){try{e.source.disconnect(),e.analyser.disconnect(),e.gain?.disconnect();}catch{}e.detach();}context(){if(this.ctx)return this.ctx;try{this.ctx=this.o.createAudioContext?this.o.createAudioContext():new AudioContext;}catch{return null}return this.ctx}ensureTimer(){this.timer||this.destroyed||(this.timer=setInterval(()=>this.measure(),this.o.levelIntervalMs));}stopTimer(){this.timer&&clearInterval(this.timer),this.timer=null;}measure(){let e=Date.now(),i=new Float32Array(512),t=(s,r,n)=>{r.analyser.getFloatTimeDomainData(i);let a=0;for(let h=0;h<i.length;h++)a+=i[h]*i[h];let l=n?Math.sqrt(a/i.length):0;r.level=l,this.levelMap.set(s,l),l>this.o.speakingThreshold&&(r.loudUntil=e+this.o.speakingHoldMs),this.setSpeaking(s,e<r.loudUntil);};this.self&&t(this.session.selfId,this.self,this.transmitting);for(let[s,r]of this.peers)t(s,r,!this.muted.has(s));this.emit("levels",{levels:this.levelMap});}setSpeaking(e,i){this.speakingIds.has(e)!==i&&(i?this.speakingIds.add(e):this.speakingIds.delete(e),this.emit("change",{}));}emit(e,i){for(let t of this.listeners.get(e)??[])try{t(i);}catch(s){console.error(`[VoiceController] ${String(e)} handler failed`,s);}}};function D(o){if(typeof Audio>"u")return ()=>{};let e=new Audio;return e.muted=true,e.srcObject=o,e.play().catch(()=>{}),()=>{e.pause(),e.srcObject=null;}}export{g as MAX_MESSAGE_BYTES,y as RealtimeSession,M as VoiceController,p as toRtcIceServers};
|
package/package.json
CHANGED
package/dist/chunk-YEBYHDZG.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var i=class{getString(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}setString(e,r){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,r);}catch{}}remove(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e);}catch{}}},s=class{map=new Map;getString(e){return this.map.get(e)??null}setString(e,r){this.map.set(e,r);}remove(e){this.map.delete(e);}};function n(){return globalThis.Telegram?.WebApp??null}function I(){return crypto.randomUUID()}var S="idos_device_id",m=class{storage;constructor(e=new i){this.storage=e;}getPlatform(){return n()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=n()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){if(typeof document>"u")return null;let e=document.referrer;return e&&e.length>0?e:null}getTelegramInitDataRaw(){let e=n()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(S);return e||(e=I(),this.storage.setString(S,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let r=n();if(r?.openTelegramLink){r.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let r=n();if(r?.openInvoice){r.openInvoice(e);return}typeof window<"u"&&window.open(e,"_blank");}async showAd(e){let r=globalThis;typeof r.showAd=="function"&&await r.showAd(e);}async copyToClipboard(e){typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(e);}};var _="idos_device_id",d=class{storage;constructor(e=new s){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(_);return e||(e="noop-device",this.storage.setString(_,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};var g=["https://idosgames.com","https://www.idosgames.com"];function v(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost")}function p(t){if(g.includes(t))return true;if(typeof window>"u"||!v(window.location.hostname))return false;try{return v(new URL(t).hostname)}catch{return false}}var R="IDOS_PLATFORM_WALLET_ACK",U="PLATFORM_WALLET_UNAVAILABLE",h=5e3,E=18e4;function M(){let t=[...g],e=window.location.ancestorOrigins?.[0];return e&&!t.includes(e)&&p(e)&&t.push(e),t}function x(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function c(t,e,r,D={}){let u={ok:false,error:U,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(u);let P=window.parent;if(!P)return Promise.resolve(u);let T=x(),L=D.answerTimeoutMs??E;return new Promise(O=>{let A=false,l,f=a=>{A||(A=true,window.removeEventListener("message",y),clearTimeout(l),O(a));},y=a=>{if(!p(a.origin))return;let o=a.data;if(!(!o||o.requestId!==T)){if(o.type===R){clearTimeout(l),l=setTimeout(()=>f({ok:false,error:"TIMEOUT",data:{}}),L);return}o.type===e&&f({ok:o.ok===true,error:typeof o.error=="string"?o.error:void 0,data:o});}};l=setTimeout(()=>f(u),h),window.addEventListener("message",y);for(let a of M())try{P.postMessage({type:t,requestId:T,...r},a);}catch{}})}var w={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},k=15*6e4,b=/^[a-z0-9]{8}-preview\.idos\.games$/;function W(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !b.test(window.location.hostname.toLowerCase())}async function F(t){let e=await c(w.request,w.response,{titleID:t.titleID,userID:t.userID,currencyID:t.currencyID,amount:t.amount},{answerTimeoutMs:k});return e.ok?{ok:true}:{ok:false,error:e.error}}
|
|
2
|
-
export{i as a,s as b,n as c,I as d,m as e,g as f,p as g,R as h,U as i,c as j,w as k,W as l,F as m,d as n};
|