!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).XPeer=e()}}((function(){return function r(e,t,n){function o(s,a){if(!t[s]){if(!e[s]){var c="function"==typeof require&&require;if(!a&&c)return c(s,!0);if(i)return i(s,!0);var d=new Error("Cannot find module '"+s+"'");throw d.code="MODULE_NOT_FOUND",d}var l=t[s]={exports:{}};e[s][0].call(l.exports,(function(t){return o(e[s][1][t]||t)}),l,l.exports,r,e,t,n)}return t[s].exports}for(var i="function"==typeof require&&require,s=0;s{this.ws&&(this.ws.addEventListener("open",(()=>{this.emit("signal:open");new a.SignalEventManager(this).handle(),e(this.ws)})),this.ws.addEventListener("error",(()=>{this.emit("signal:error"),t("ws error in initWebsocketEvent")})),this.ws.addEventListener("close",(()=>{this.emit("signal:close"),t("ws close in initWebsocketEvent")})))}))}join({roomId:e,nick:t}){return i(this,void 0,void 0,(function*(){this.ws&&this.ws.readyState!==WebSocket.CLOSED||(yield this.initWebsocketEvent());const{local:n}=this;t&&(n.nick=t);const i={type:"join",receiverId:null,payload:{roomId:e,nick:n.nick}};return this.signalSend(i),n}))}connectPeer(e){const t=new d.default(e.id,e.nick,new RTCPeerConnection(this.peerConfig),this);this.addPeer(t),t.connect()}addPeer(e){this.local.Peers.push(e)}findPeer(e){return this.local.Peers.find((t=>t.id===e))}signalSend(e){this.onSignalServerReady((()=>{var t;null===(t=this.ws)||void 0===t||t.send(JSON.stringify(e))}))}shareUser(e={}){if(this.isSharingUser)return Promise.reject("already exists camera sharing");const{local:t}=this;return navigator.mediaDevices.getUserMedia(e).then((e=>{this.isSharingUser=!0,t.media.user=e;const n=e.getTracks(),i=n.map((e=>`[user/${e.id}]`)).join("");return t.trackTags=i,t.Peers.forEach((t=>{n.forEach((n=>{((...e)=>{console.log("
",...e)})("添加track到peer中",{peer:t,track:n}),t.peerConnection.addTrack(n,e)}))})),e.addEventListener("inactive",(()=>{this.send("streamStop:user"),delete this.local.media.user,this.isSharingUser=!1})),t})).catch((e=>{throw new Error(`unable to get user media: ${e.message}`)}))}shareDisplay(e={}){if(this.isSharingDisplay)return Promise.reject("already exists display sharing");const{local:t}=this;return navigator.mediaDevices.getDisplayMedia(e).then((e=>{this.isSharingDisplay=!0,t.media.display=e;const n=e.getTracks(),i=n.map((e=>`[display/${e.id}]`)).join("");return t.trackTags=i,t.Peers.forEach((t=>{n.forEach((n=>{t.peerConnection.addTrack(n,e)}))})),e.addEventListener("inactive",(()=>{this.send("streamStop:display"),delete this.local.media.display,this.isSharingDisplay=!1})),t})).catch((e=>{throw new Error(`unable to get user media: ${e.message}`)}))}pushLocalStreamTo(e){const{user:t,display:n}=this.local.media,i=e.peerConnection;let s="";t&&t.getTracks().forEach((e=>{s+=`[user/${e.id}]`,i.addTrack(e,t)})),n&&n.getTracks().forEach((e=>{s+=`[display/${e.id}]`,i.addTrack(e,n)})),this.local.trackTags=s}onSignalServerReady(e){if(!this.ws)throw new Error("signal server not ready");this.ws.readyState===WebSocket.OPEN?e():this.ws.readyState===WebSocket.CONNECTING?this.ws.addEventListener("open",(()=>{e()})):this.ws.readyState===WebSocket.CLOSED&&this.initWebsocketEvent().then(e)}leave(){var e,t,n;null===(e=this.local.media.user)||void 0===e||e.getTracks().forEach((e=>e.stop())),null===(t=this.local.media.display)||void 0===t||t.getTracks().forEach((e=>e.stop())),delete this.local.media.user,delete this.local.media.display,this.local.Peers.forEach((e=>{var t;e.peerConnection.close(),null===(t=e.dataChannel)||void 0===t||t.close()})),this.local.Peers=[],null===(n=this.ws)||void 0===n||n.close(),delete this.ws,this.eventBus.removeAllListeners()}on(e,t){this.eventBus.on(e,t,this)}emit(e,t){this.eventBus.emit(e,t)}setMute(e,t){return this.local.media.user?(this.local.media.user.getTracks().forEach((n=>{n.kind===e&&(n.enabled=t)})),Promise.resolve()):Promise.reject(new Error("no user media"))}sendBinary(e){this.local.Peers.forEach((t=>t.sendBinary(e)))}send(e){this.local.Peers.forEach((t=>t.send(e)))}}},{"./peer":3,"./signalEventManager":4,eventemitter3:5}],3:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.TrackType=void 0;const i=e("eventemitter3"),log=(...e)=>console.log("",...e);var s;!function(e){e[e.User=0]="User",e[e.Display=1]="Display",e[e.Unknown=2]="Unknown"}(s=n.TrackType||(n.TrackType={}));n.default=class{constructor(e,t,n,s,a=2,c=0){this.id=e,this.nick=t,this.peerConnection=n,this.parentInstance=s,this.retryCount=a,this.connectAttemptCount=c,this._isConnected=!1,this.media={},this.dataChannel=null,this.id=e,this.nick=t,this.peerConnection=n,this.parentInstance=s,this.initPeerConnectionEvents(),this.eventBus=new i}get isConnected(){return this._isConnected}set isConnected(e){}connect(){if(this.isConnected)return Promise.reject(new Error("peer already connected"));const e=this.peerConnection;return new Promise(((t,n)=>{const i=e.createDataChannel("dc");i.addEventListener("open",(()=>{log("datachannel open"),t(this),this.dataChannel=i,this._isConnected=!0,this.parentInstance.emit("connect",this),this.initDataChannelEvents(i)})),setTimeout((()=>{this.connectAttemptCount<=this.retryCount?(this.connectAttemptCount++,this.connect()):(n(new Error("connect timeout")),this.connectAttemptCount=0)}),3e3)}))}receiveOffer(e){"offer"===e.type&&this.peerConnection.setRemoteDescription(new RTCSessionDescription(e.payload)).then((()=>this.replyAnswer(e)))}receiveAnswer(e){this.peerConnection.setRemoteDescription(new RTCSessionDescription(e))}receiveIceCandidate(e){log("收到icecandidate,并添加到本地"),this.peerConnection.addIceCandidate(new RTCIceCandidate(e))}replyAnswer(e){const t=this.peerConnection;"offer"===e.type&&t.createAnswer().then((e=>t.setLocalDescription(e))).then((()=>{var n;const i={type:"answer",receiverId:e.userInfo.id,payload:null===(n=t.localDescription)||void 0===n?void 0:n.toJSON()};this.parentInstance.signalSend(i)})).catch((e=>{throw new Error(`replayAnswer error: ${e}`)}))}initDataChannelEvents(e){e.onmessage=e=>{const t=e.data;"string"==typeof t?("streamStop:display"===t&&(delete this.media.display,this.parentInstance.emit("streamStop:display",this),this.emit("streamStop:display",void 0)),"streamStop:user"===t?(delete this.media.user,this.emit("streamStop:user",void 0),this.parentInstance.emit("streamStop:user",this)):this.parentInstance.emit("message",{peer:this,payload:t})):this.parentInstance.emit("binary",{peer:this,payload:t})},e.onclose=()=>{}}initPeerConnectionEvents(){const e=this,{peerConnection:t}=e;t.addEventListener("iceconnectionstatechange",e.onIceConnectionStateChange.bind(e)),t.addEventListener("icecandidate",e.onIceCandidate.bind(e)),t.addEventListener("track",e.onTrack.bind(e)),t.addEventListener("negotiationneeded",e.onNegotiationneeded.bind(e)),t.addEventListener("datachannel",e.onDataChannel.bind(e))}onIceConnectionStateChange(){log("ICE_STATE_CHANGE",this.peerConnection.iceConnectionState)}onIceCandidate(e){const t=this;log("PC:[icecandidate]",e),e.candidate&&t.parentInstance.signalSend({type:"icecandidate",receiverId:t.id,payload:e.candidate})}onTrack(e){log("PC:[track] 主动者收",e);const t=this,n=e.streams[0],i=function(e,t){if(-1!==e.indexOf(`[user/${t.id}]`))return s.User;if(-1!==e.indexOf(`[display/${t.id}]`))return s.Display;if(-1!==e.indexOf("[user/"))return s.User;if(-1!==e.indexOf("[display/"))return s.Display;return s.Unknown}(e.target.remoteDescription.sdp.toString(),e.track);i===s.User?t.media.user&&t.media.user.id===n.id||(t.media.user=n,t.parentInstance.emit("stream:user",t),t.emit("stream:user",n)):i===s.Display&&(t.media.display&&t.media.display.id===n.id||(t.media.display=n,t.parentInstance.emit("stream:display",t),t.emit("stream:display",n)))}onNegotiationneeded(){const e=this,{parentInstance:t,peerConnection:n}=e;n.createOffer().then((e=>(e.sdp=function(e="",t=""){return e.split("\n").map((e=>e.replace(/(a=extmap:[0-9]+) [^ \n]+/gi,`$1 ${t}`))).join("\n")}(e.sdp,t.local.trackTags),n.setLocalDescription(e).then((()=>e))))).then((t=>{e.parentInstance.emit("negotiationneeded:done",e),e.parentInstance.signalSend({type:"offer",receiverId:e.id,payload:t})}))}onDataChannel(e){const t=this,n=e.channel;t.dataChannel=n,t._isConnected=!0,t.parentInstance.emit("join",t),this.initDataChannelEvents(n)}send(e){const{dataChannel:t}=this;t&&t.send(e)}sendBinary(e){const{dataChannel:t}=this;t&&t.send(e)}on(e,t,n=!1){this.eventBus[n?"once":"on"](e,t),"stream:user"===e&&this.media.user?this.emit("stream:user",this.media.user):"stream:display"===e&&this.media.display&&this.emit("stream:display",this.media.display)}emit(e,t){this.eventBus.emit(e,t)}}},{eventemitter3:5}],4:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(s,a){function fulfilled(e){try{step(i.next(e))}catch(e){a(e)}}function rejected(e){try{step(i.throw(e))}catch(e){a(e)}}function step(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.SignalEventManager=void 0;const a=s(e("./peer"));n.SignalEventManager=class{constructor(e){this.xPeer=e,this.xPeer=e}roomInfo(e){if("roomInfo"===e.type){const{users:t,userInfo:n}=e.payload;this.xPeer.local.nick=n.nick,this.xPeer.local.id=n.id,t.forEach((e=>{this.xPeer.connectPeer(e)})),this.xPeer.emit("roomInfo",t)}}offer(e){return i(this,void 0,void 0,(function*(){if(e.userInfo&&"offer"===e.type){const{id:t,nick:n}=e.userInfo;let i=this.xPeer.findPeer(t);i||(i=new a.default(t,n,new RTCPeerConnection(this.xPeer.peerConfig),this.xPeer),this.xPeer.addPeer(i),this.xPeer.pushLocalStreamTo(i)),i.receiveOffer(e)}}))}answer(e){if("answer"===e.type&&e.userInfo){const t=e.userInfo,n=this.xPeer.findPeer(t.id);null==n||n.receiveAnswer(e.payload)}}icecandidate(e){if("icecandidate"===e.type&&e.userInfo){const t=e.userInfo,n=this.xPeer.findPeer(t.id);null==n||n.receiveIceCandidate(e.payload)}}leave(e){if("leave"===e.type){const t=this.xPeer.findPeer(e.payload.id);t&&(t.peerConnection.close(),this.xPeer.local.Peers=this.xPeer.local.Peers.filter((e=>e!==t))),this.xPeer.emit("leave",e.payload)}}join(e){}handle(){const e=this;if(!this.xPeer.ws)throw new Error("ws is not defined when handling signal event");{this.xPeer.ws.addEventListener("message",(function({data:t}){const n=JSON.parse(t);((...e)=>{console.log("",...e)})(`received [${n.type}]`,n),e[n.type](n)}));const t=setInterval((()=>{this.keepAlive()}),59e3);this.xPeer.ws.addEventListener("close",(()=>clearInterval(t)))}}keepAlive(){this.xPeer.signalSend({type:"ping"})}}},{"./peer":3}],5:[function(e,t,n){"use strict";var i=Object.prototype.hasOwnProperty,s="~";function Events(){}function EE(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function addListener(e,t,n,i,a){if("function"!=typeof n)throw new TypeError("The listener must be a function");var c=new EE(n,i||e,a),d=s?s+t:t;return e._events[d]?e._events[d].fn?e._events[d]=[e._events[d],c]:e._events[d].push(c):(e._events[d]=c,e._eventsCount++),e}function clearEvent(e,t){0==--e._eventsCount?e._events=new Events:delete e._events[t]}function EventEmitter(){this._events=new Events,this._eventsCount=0}Object.create&&(Events.prototype=Object.create(null),(new Events).__proto__||(s=!1)),EventEmitter.prototype.eventNames=function(){var e,t,n=[];if(0===this._eventsCount)return n;for(t in e=this._events)i.call(e,t)&&n.push(s?t.slice(1):t);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},EventEmitter.prototype.listeners=function(e){var t=s?s+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,c=new Array(a);i