MWSE/frontend/index.ts

73 lines
2.1 KiB
TypeScript

import {Connection,IConnection} from "./Connection";
import EventPool from "./EventPool";
import EventTarget from "./EventTarget";
import Peer from "./Peer";
import Room, { IRoomOptions } from "./Room";
import WSTSProtocol from "./WSTSProtocol";
export default class MWSE extends EventTarget {
public server! : Connection;
public WSTSProtocol! : WSTSProtocol;
public EventPooling! : EventPool;
public rooms : Map<string, Room> = new Map();
public pairs : Map<string, Peer> = new Map();
public peers : Map<string, Peer> = new Map();
public me! : Peer;
constructor(options: IConnection){
super();
this.server = new Connection(options);
this.server.connect();
this.WSTSProtocol = new WSTSProtocol(this);
this.EventPooling = new EventPool(this);
this.me = new Peer(this);
this.me.scope(()=>{
this.peers.set('me', this.me);
this.peers.set(this.me.socketId as string, this.me);
})
this.server.onActive(async ()=>{
this.me.setSocketId('me');
await this.me.metadata();
this.emit('scope');
this.activeScope = true;
});
this.packMessagingSystem();
}
private packMessagingSystem()
{
this.EventPooling.signal('pack',(payload : {to:string,pack:any}) => {
let {to,pack} = payload;
this.peer(to).emit('message', pack);
})
}
public room(options: IRoomOptions)
{
let room = new Room(this);
room.setRoomOptions(options);
return room;
}
public peer(options: string | IRoomOptions) : Peer
{
if(typeof options == "string")
{
if(this.peers.has(options))
{
return this.peers.get(options) as Peer
}
if(this.pairs.has(options))
{
return this.pairs.get(options) as Peer
}
}
let peer = new Peer(this);
peer.setPeerOptions(options);
this.emit('peer', peer);
return peer;
}
};
declare global {
interface Window {
MWSE: any;
}
}
window.MWSE = MWSE;