@pulsebeam/peer 0.0.13 → 0.0.15

Sign up to get free protection for your applications and to get access to all the features.
package/README.md CHANGED
@@ -69,7 +69,7 @@ This example retrieves an authentication token (implementation details will vary
69
69
 
70
70
  For documentation, API keys, and usage scenarios, please refer to the official PulseBeam documentation:
71
71
 
72
- * https://pulsebeam.dev/docs/getting-started/
72
+ * https://pulsebeam.dev/docs/
73
73
 
74
74
  # WebRTC Resources
75
75
 
package/dist/index.cjs CHANGED
@@ -32,6 +32,6 @@ t=0 0\r
32
32
  `};l.getDirection=function(e,t){let r=l.splitLines(e);for(let n=0;n<r.length;n++)switch(r[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[n].substring(2);default:}return t?l.getDirection(t):"sendrecv"};l.getKind=function(e){return l.splitLines(e)[0].split(" ")[0].substring(2)};l.isRejected=function(e){return e.split(" ",2)[1]==="0"};l.parseMLine=function(e){let r=l.splitLines(e)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}};l.parseOLine=function(e){let r=l.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}};l.isValidSDP=function(e){if(typeof e!="string"||e.length===0)return!1;let t=l.splitLines(e);for(let r=0;r<t.length;r++)if(t[r].length<2||t[r].charAt(1)!=="=")return!1;return!0};typeof Ie=="object"&&(Ie.exports=l)});var dr={};b(dr,{Peer:()=>ee,createPeer:()=>pr});module.exports=Mt(dr);var rt=!0,nt=!0;function P(e,t,r){let n=e.match(t);return n&&n.length>=r&&parseInt(n[r],10)}function S(e,t,r){if(!e.RTCPeerConnection)return;let n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(o,a){if(o!==t)return s.apply(this,arguments);let d=c=>{let p=r(c);p&&(a.handleEvent?a.handleEvent(p):a(p))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(a,d),s.apply(this,[o,d])};let i=n.removeEventListener;n.removeEventListener=function(o,a){if(o!==t||!this._eventMap||!this._eventMap[t])return i.apply(this,arguments);if(!this._eventMap[t].has(a))return i.apply(this,arguments);let d=this._eventMap[t].get(a);return this._eventMap[t].delete(a),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,i.apply(this,[o,d])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(o){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),o&&this.addEventListener(t,this["_on"+t]=o)},enumerable:!0,configurable:!0})}function st(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(rt=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function it(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(nt=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function L(){if(typeof window=="object"){if(rt)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function v(e,t){nt&&console.warn(e+" is deprecated, please use "+t+" instead.")}function ot(e){let t={browser:null,version:null};if(typeof e>"u"||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;let{navigator:r}=e;if(r.userAgentData&&r.userAgentData.brands){let n=r.userAgentData.brands.find(s=>s.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(r.mozGetUserMedia)t.browser="firefox",t.version=P(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=P(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(e.RTCPeerConnection&&r.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser="safari",t.version=P(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype;else return t.browser="Not a supported browser.",t;return t}function tt(e){return Object.prototype.toString.call(e)==="[object Object]"}function re(e){return tt(e)?Object.keys(e).reduce(function(t,r){let n=tt(e[r]),s=n?re(e[r]):e[r],i=n&&!Object.keys(s).length;return s===void 0||i?t:Object.assign(t,{[r]:s})},{}):e}function te(e,t,r){!t||r.has(t.id)||(r.set(t.id,t),Object.keys(t).forEach(n=>{n.endsWith("Id")?te(e,e.get(t[n]),r):n.endsWith("Ids")&&t[n].forEach(s=>{te(e,e.get(s),r)})}))}function ne(e,t,r){let n=r?"outbound-rtp":"inbound-rtp",s=new Map;if(t===null)return s;let i=[];return e.forEach(o=>{o.type==="track"&&o.trackIdentifier===t.id&&i.push(o)}),i.forEach(o=>{e.forEach(a=>{a.type===n&&a.trackId===o.id&&te(e,a,s)})}),s}var U={};b(U,{fixNegotiationNeeded:()=>pe,shimAddTrackRemoveTrack:()=>ce,shimAddTrackRemoveTrackWithNative:()=>ct,shimGetSendersWithDtmf:()=>oe,shimGetUserMedia:()=>A,shimMediaStream:()=>se,shimOnTrack:()=>ie,shimPeerConnection:()=>j,shimSenderReceiverGetStats:()=>ae});var at=L;function A(e,t){let r=e&&e.navigator;if(!r.mediaDevices)return;let n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;let d={};return Object.keys(a).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;let p=typeof a[c]=="object"?a[c]:{ideal:a[c]};p.exact!==void 0&&typeof p.exact=="number"&&(p.min=p.max=p.exact);let u=function(m,h){return m?m+h.charAt(0).toUpperCase()+h.slice(1):h==="deviceId"?"sourceId":h};if(p.ideal!==void 0){d.optional=d.optional||[];let m={};typeof p.ideal=="number"?(m[u("min",c)]=p.ideal,d.optional.push(m),m={},m[u("max",c)]=p.ideal,d.optional.push(m)):(m[u("",c)]=p.ideal,d.optional.push(m))}p.exact!==void 0&&typeof p.exact!="number"?(d.mandatory=d.mandatory||{},d.mandatory[u("",c)]=p.exact):["min","max"].forEach(m=>{p[m]!==void 0&&(d.mandatory=d.mandatory||{},d.mandatory[u(m,c)]=p[m])})}),a.advanced&&(d.optional=(d.optional||[]).concat(a.advanced)),d},s=function(a,d){if(t.version>=61)return d(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){let c=function(p,u,m){u in p&&!(m in p)&&(p[m]=p[u],delete p[u])};a=JSON.parse(JSON.stringify(a)),c(a.audio,"autoGainControl","googAutoGainControl"),c(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let c=a.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});let p=t.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(r.mediaDevices.getSupportedConstraints&&r.mediaDevices.getSupportedConstraints().facingMode&&!p)){delete a.video.facingMode;let u;if(c.exact==="environment"||c.ideal==="environment"?u=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(u=["front"]),u)return r.mediaDevices.enumerateDevices().then(m=>{m=m.filter(g=>g.kind==="videoinput");let h=m.find(g=>u.some(y=>g.label.toLowerCase().includes(y)));return!h&&m.length&&u.includes("back")&&(h=m[m.length-1]),h&&(a.video.deviceId=c.exact?{exact:h.deviceId}:{ideal:h.deviceId}),a.video=n(a.video),at("chrome: "+JSON.stringify(a)),d(a)})}a.video=n(a.video)}return at("chrome: "+JSON.stringify(a)),d(a)},i=function(a){return t.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,d,c){s(a,p=>{r.webkitGetUserMedia(p,d,u=>{c&&c(i(u))})})};if(r.getUserMedia=o.bind(r),r.mediaDevices.getUserMedia){let a=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(d){return s(d,c=>a(c).then(p=>{if(c.audio&&!p.getAudioTracks().length||c.video&&!p.getVideoTracks().length)throw p.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return p},p=>Promise.reject(i(p))))}}}function se(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function ie(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(r){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=r)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",s=>{let i;e.RTCPeerConnection.prototype.getReceivers?i=this.getReceivers().find(a=>a.track&&a.track.id===s.track.id):i={track:s.track};let o=new Event("track");o.track=s.track,o.receiver=i,o.transceiver={receiver:i},o.streams=[n.stream],this.dispatchEvent(o)}),n.stream.getTracks().forEach(s=>{let i;e.RTCPeerConnection.prototype.getReceivers?i=this.getReceivers().find(a=>a.track&&a.track.id===s.id):i={track:s};let o=new Event("track");o.track=s,o.receiver=i,o.transceiver={receiver:i},o.streams=[n.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else S(e,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function oe(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){let t=function(s,i){return{track:i,get dtmf(){return this._dtmf===void 0&&(i.kind==="audio"?this._dtmf=s.createDTMFSender(i):this._dtmf=null),this._dtmf},_pc:s}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let s=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(a,d){let c=s.apply(this,arguments);return c||(c=t(this,a),this._senders.push(c)),c};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(a){i.apply(this,arguments);let d=this._senders.indexOf(a);d!==-1&&this._senders.splice(d,1)}}let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(i){this._senders=this._senders||[],r.apply(this,[i]),i.getTracks().forEach(o=>{this._senders.push(t(this,o))})};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(i){this._senders=this._senders||[],n.apply(this,[i]),i.getTracks().forEach(o=>{let a=this._senders.find(d=>d.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof e=="object"&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let n=t.apply(this,[]);return n.forEach(s=>s._pc=this),n},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function ae(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){let r=e.RTCPeerConnection.prototype.getSenders;r&&(e.RTCPeerConnection.prototype.getSenders=function(){let i=r.apply(this,[]);return i.forEach(o=>o._pc=this),i});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let i=n.apply(this,arguments);return i._pc=this,i}),e.RTCRtpSender.prototype.getStats=function(){let i=this;return this._pc.getStats().then(o=>ne(o,i.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){let r=e.RTCPeerConnection.prototype.getReceivers;r&&(e.RTCPeerConnection.prototype.getReceivers=function(){let s=r.apply(this,[]);return s.forEach(i=>i._pc=this),s}),S(e,"track",n=>(n.receiver._pc=n.srcElement,n)),e.RTCRtpReceiver.prototype.getStats=function(){let s=this;return this._pc.getStats().then(i=>ne(i,s.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype))return;let t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let n=arguments[0],s,i,o;return this.getSenders().forEach(a=>{a.track===n&&(s?o=!0:s=a)}),this.getReceivers().forEach(a=>(a.track===n&&(i?o=!0:i=a),a.track===n)),o||s&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ct(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let d=t.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(d)===-1&&this._shimmedLocalStreams[a.id].push(d):this._shimmedLocalStreams[a.id]=[a,d],d};let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(c=>{if(this.getSenders().find(u=>u.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});let a=this.getSenders();r.apply(this,arguments);let d=this.getSenders().filter(c=>a.indexOf(c)===-1);this._shimmedLocalStreams[o.id]=[o].concat(d)};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};let s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{let d=this._shimmedLocalStreams[a].indexOf(o);d!==-1&&this._shimmedLocalStreams[a].splice(d,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),s.apply(this,arguments)}}function ce(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ct(e);let r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let p=r.apply(this);return this._reverseStreams=this._reverseStreams||{},p.map(u=>this._reverseStreams[u.id])};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(p){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},p.getTracks().forEach(u=>{if(this.getSenders().find(h=>h.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[p.id]){let u=new e.MediaStream(p.getTracks());this._streams[p.id]=u,this._reverseStreams[u.id]=p,p=u}n.apply(this,[p])};let s=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(p){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[p.id]||p]),delete this._reverseStreams[this._streams[p.id]?this._streams[p.id].id:p.id],delete this._streams[p.id]},e.RTCPeerConnection.prototype.addTrack=function(p,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let m=[].slice.call(arguments,1);if(m.length!==1||!m[0].getTracks().find(y=>y===p))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(y=>y.track===p))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let g=this._streams[u.id];if(g)g.addTrack(p),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let y=new e.MediaStream([p]);this._streams[u.id]=y,this._reverseStreams[y.id]=u,this.addStream(y)}return this.getSenders().find(y=>y.track===p)};function i(c,p){let u=p.sdp;return Object.keys(c._reverseStreams||[]).forEach(m=>{let h=c._reverseStreams[m],g=c._streams[h.id];u=u.replace(new RegExp(g.id,"g"),h.id)}),new RTCSessionDescription({type:p.type,sdp:u})}function o(c,p){let u=p.sdp;return Object.keys(c._reverseStreams||[]).forEach(m=>{let h=c._reverseStreams[m],g=c._streams[h.id];u=u.replace(new RegExp(h.id,"g"),g.id)}),new RTCSessionDescription({type:p.type,sdp:u})}["createOffer","createAnswer"].forEach(function(c){let p=e.RTCPeerConnection.prototype[c],u={[c](){let m=arguments;return arguments.length&&typeof arguments[0]=="function"?p.apply(this,[g=>{let y=i(this,g);m[0].apply(null,[y])},g=>{m[1]&&m[1].apply(null,g)},arguments[2]]):p.apply(this,arguments).then(g=>i(this,g))}};e.RTCPeerConnection.prototype[c]=u[c]});let a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};let d=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let c=d.get.apply(this);return c.type===""?c:i(this,c)}}),e.RTCPeerConnection.prototype.removeTrack=function(p){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!p._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(p._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let m;Object.keys(this._streams).forEach(h=>{this._streams[h].getTracks().find(y=>p.track===y)&&(m=this._streams[h])}),m&&(m.getTracks().length===1?this.removeStream(this._reverseStreams[m.id]):m.removeTrack(p.track),this.dispatchEvent(new Event("negotiationneeded")))}}function j(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){let n=e.RTCPeerConnection.prototype[r],s={[r](){return arguments[0]=new(r==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[r]=s[r]})}function pe(e,t){S(e,"negotiationneeded",r=>{let n=r.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return r})}var q={};b(q,{shimAddTransceiver:()=>fe,shimCreateAnswer:()=>ye,shimCreateOffer:()=>Ce,shimGetDisplayMedia:()=>pt,shimGetParameters:()=>ge,shimGetUserMedia:()=>F,shimOnTrack:()=>de,shimPeerConnection:()=>N,shimRTCDataChannel:()=>he,shimReceiverGetStats:()=>ue,shimRemoveStream:()=>me,shimSenderGetStats:()=>le});function F(e,t){let r=e&&e.navigator,n=e&&e.MediaStreamTrack;if(r.getUserMedia=function(s,i,o){v("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(s).then(i,o)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){let s=function(o,a,d){a in o&&!(d in o)&&(o[d]=o[a],delete o[a])},i=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),i(o)},n&&n.prototype.getSettings){let o=n.prototype.getSettings;n.prototype.getSettings=function(){let a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){let o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function pt(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return n.video===!0?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})}function de(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function N(e,t){if(typeof e!="object"||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){let i=e.RTCPeerConnection.prototype[s],o={[s](){return arguments[0]=new(s==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[s]=o[s]});let r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[i,o,a]=arguments;return n.apply(this,[i||null]).then(d=>{if(t.version<53&&!o)try{d.forEach(c=>{c.type=r[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;d.forEach((p,u)=>{d.set(u,Object.assign({},p,{type:r[p.type]||p.type}))})}return d}).then(o,a)}}function le(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let s=t.apply(this,[]);return s.forEach(i=>i._pc=this),s});let r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){let s=r.apply(this,arguments);return s._pc=this,s}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function ue(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let n=t.apply(this,[]);return n.forEach(s=>s._pc=this),n}),S(e,"track",r=>(r.receiver._pc=r.srcElement,r)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function me(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(r){v("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&r.getTracks().includes(n.track)&&this.removeTrack(n)})})}function he(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function fe(e){if(!(typeof e=="object"&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];let s=n.length>0;s&&n.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});let i=t.apply(this,arguments);if(s){let{sender:o}=i,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=n,o.sendEncodings=n,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return i})}function ge(e){if(!(typeof e=="object"&&e.RTCRtpSender))return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let n=t.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function Ce(e){if(!(typeof e=="object"&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function ye(e){if(!(typeof e=="object"&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var G={};b(G,{shimAudioContext:()=>ke,shimCallbacksAPI:()=>ve,shimConstraints:()=>dt,shimCreateOfferLegacy:()=>xe,shimGetUserMedia:()=>Te,shimLocalStreamsAPI:()=>Se,shimRTCIceServerUrls:()=>be,shimRemoteStreamsAPI:()=>Re,shimTrackEventTransceiver:()=>Pe});function Se(e){if(!(typeof e!="object"||!e.RTCPeerConnection)){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(s=>t.call(this,s,n)),n.getVideoTracks().forEach(s=>t.call(this,s,n))},e.RTCPeerConnection.prototype.addTrack=function(n,...s){return s&&s.forEach(i=>{this._localStreams?this._localStreams.includes(i)||this._localStreams.push(i):this._localStreams=[i]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(r){this._localStreams||(this._localStreams=[]);let n=this._localStreams.indexOf(r);if(n===-1)return;this._localStreams.splice(n,1);let s=r.getTracks();this.getSenders().forEach(i=>{s.includes(i.track)&&this.removeTrack(i)})})}}function Re(e){if(!(typeof e!="object"||!e.RTCPeerConnection)&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(r){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=r),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);let i=new Event("addstream");i.stream=s,this.dispatchEvent(i)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(i=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(i)>=0)return;n._remoteStreams.push(i);let o=new Event("addstream");o.stream=i,n.dispatchEvent(o)})}),t.apply(n,arguments)}}}function ve(e){if(typeof e!="object"||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,r=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,i=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(c,p){let u=arguments.length>=2?arguments[2]:arguments[0],m=r.apply(this,[u]);return p?(m.then(c,p),Promise.resolve()):m},t.createAnswer=function(c,p){let u=arguments.length>=2?arguments[2]:arguments[0],m=n.apply(this,[u]);return p?(m.then(c,p),Promise.resolve()):m};let a=function(d,c,p){let u=s.apply(this,[d]);return p?(u.then(c,p),Promise.resolve()):u};t.setLocalDescription=a,a=function(d,c,p){let u=i.apply(this,[d]);return p?(u.then(c,p),Promise.resolve()):u},t.setRemoteDescription=a,a=function(d,c,p){let u=o.apply(this,[d]);return p?(u.then(c,p),Promise.resolve()):u},t.addIceCandidate=a}function Te(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let r=t.mediaDevices,n=r.getUserMedia.bind(r);t.mediaDevices.getUserMedia=s=>n(dt(s))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(n,s,i){t.mediaDevices.getUserMedia(n).then(s,i)}.bind(t))}function dt(e){return e&&e.video!==void 0?Object.assign({},e,{video:re(e.video)}):e}function be(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(n,s){if(n&&n.iceServers){let i=[];for(let o=0;o<n.iceServers.length;o++){let a=n.iceServers[o];a.urls===void 0&&a.url?(v("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,i.push(a)):i.push(n.iceServers[o])}n.iceServers=i}return new t(n,s)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get(){return t.generateCertificate}})}function Pe(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function xe(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);let s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);let i=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):n.offerToReceiveVideo===!0&&!i&&this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function ke(e){typeof e!="object"||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Ee={};b(Ee,{removeExtmapAllowMixed:()=>J,shimAddIceCandidateNullOrEmpty:()=>_,shimConnectionState:()=>K,shimMaxMessageSize:()=>k,shimParameterlessSetLocalDescription:()=>E,shimRTCIceCandidate:()=>x,shimRTCIceCandidateRelayProtocol:()=>z,shimSendThrowTypeError:()=>I});var T=et(_e());function x(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){let s=new t(n),i=T.default.parseCandidate(n.candidate);for(let o in i)o in s||Object.defineProperty(s,o,{value:i[o]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new t(n)},e.RTCIceCandidate.prototype=t.prototype,S(e,"icecandidate",r=>(r.candidate&&Object.defineProperty(r,"candidate",{value:new e.RTCIceCandidate(r.candidate),writable:"false"}),r))}function z(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||S(e,"icecandidate",t=>{if(t.candidate){let r=T.default.parseCandidate(t.candidate.candidate);r.type==="relay"&&(t.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[r.priority>>24])}return t})}function k(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});let r=function(a){if(!a||!a.sdp)return!1;let d=T.default.splitSections(a.sdp);return d.shift(),d.some(c=>{let p=T.default.parseMLine(c);return p&&p.kind==="application"&&p.protocol.indexOf("SCTP")!==-1})},n=function(a){let d=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(d===null||d.length<2)return-1;let c=parseInt(d[1],10);return c!==c?-1:c},s=function(a){let d=65536;return t.browser==="firefox"&&(t.version<57?a===-1?d=16384:d=2147483637:t.version<60?d=t.version===57?65535:65536:d=2147483637),d},i=function(a,d){let c=65536;t.browser==="firefox"&&t.version===57&&(c=65535);let p=T.default.matchPrefix(a.sdp,"a=max-message-size:");return p.length>0?c=parseInt(p[0].substring(19),10):t.browser==="firefox"&&d!==-1&&(c=2147483637),c},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser==="chrome"&&t.version>=76){let{sdpSemantics:d}=this.getConfiguration();d==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){let d=n(arguments[0]),c=s(d),p=i(arguments[0],d),u;c===0&&p===0?u=Number.POSITIVE_INFINITY:c===0||p===0?u=Math.max(c,p):u=Math.min(c,p);let m={};Object.defineProperty(m,"maxMessageSize",{get(){return u}}),this._sctp=m}return o.apply(this,arguments)}}function I(e){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype))return;function t(n,s){let i=n.send;n.send=function(){let a=arguments[0],d=a.length||a.size||a.byteLength;if(n.readyState==="open"&&s.sctp&&d>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return i.apply(n,arguments)}}let r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let s=r.apply(this,arguments);return t(s,this),s},S(e,"datachannel",n=>(t(n.channel,n.target),n))}function K(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(r){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),r&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=r)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(r=>{let n=t[r];t[r]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{let i=s.target;if(i._lastConnectionState!==i.connectionState){i._lastConnectionState=i.connectionState;let o=new Event("connectionstatechange",s);i.dispatchEvent(o)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function J(e,t){if(!e.RTCPeerConnection||t.browser==="chrome"&&t.version>=71||t.browser==="safari"&&t.version>=605)return;let r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
33
33
  a=extmap-allow-mixed`)!==-1){let i=s.sdp.split(`
34
34
  `).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
35
- `);e.RTCSessionDescription&&s instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:s.type,sdp:i}):s.sdp=i}return r.apply(this,arguments)}}function _(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let r=e.RTCPeerConnection.prototype.addIceCandidate;!r||r.length===0||(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser==="chrome"&&t.version<78||t.browser==="firefox"&&t.version<68||t.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function E(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let r=e.RTCPeerConnection.prototype.setLocalDescription;!r||r.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return r.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?r.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>r.apply(this,[o]))})}var Dt=et(_e());function lt({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){let r=L,n=ot(e),s={browserDetails:n,commonShim:Ee,extractVersion:P,disableLog:st,disableWarnings:it,sdp:Dt};switch(n.browser){case"chrome":if(!U||!j||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),s;if(n.version===null)return r("Chrome shim can not determine version, not shimming."),s;r("adapter.js shimming chrome."),s.browserShim=U,_(e,n),E(e,n),A(e,n),se(e,n),j(e,n),ie(e,n),ce(e,n),oe(e,n),ae(e,n),pe(e,n),x(e,n),z(e,n),K(e,n),k(e,n),I(e,n),J(e,n);break;case"firefox":if(!q||!N||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),s;r("adapter.js shimming firefox."),s.browserShim=q,_(e,n),E(e,n),F(e,n),N(e,n),de(e,n),me(e,n),le(e,n),ue(e,n),he(e,n),fe(e,n),ge(e,n),Ce(e,n),ye(e,n),x(e,n),K(e,n),k(e,n),I(e,n);break;case"safari":if(!G||!t.shimSafari)return r("Safari shim is not included in this adapter release."),s;r("adapter.js shimming safari."),s.browserShim=G,_(e,n),E(e,n),be(e,n),xe(e,n),ve(e,n),Se(e,n),Re(e,n),Pe(e,n),Te(e,n),ke(e,n),x(e,n),z(e,n),k(e,n),I(e,n),J(e,n);break;default:r("Unsupported browser!");break}return s}var Ot=lt({window:typeof window>"u"?void 0:window}),M=Ot;var ut=require("@protobuf-ts/runtime-rpc"),f=require("@protobuf-ts/runtime"),Qe=(i=>(i[i.UNSPECIFIED=0]="UNSPECIFIED",i[i.OFFER=1]="OFFER",i[i.ANSWER=2]="ANSWER",i[i.PRANSWER=3]="PRANSWER",i[i.ROLLBACK=4]="ROLLBACK",i))(Qe||{}),Me=class extends f.MessageType{constructor(){super("pulsebeam.v1.PrepareReq",[])}},Lt=new Me,De=class extends f.MessageType{constructor(){super("pulsebeam.v1.PrepareResp",[{no:1,name:"ice_servers",kind:"message",repeat:1,T:()=>jt}])}},At=new De,Oe=class extends f.MessageType{constructor(){super("pulsebeam.v1.IceServer",[{no:1,name:"urls",kind:"scalar",repeat:2,T:9},{no:2,name:"username",kind:"scalar",opt:!0,T:9},{no:3,name:"credential",kind:"scalar",opt:!0,T:9}])}},jt=new Oe,Le=class extends f.MessageType{constructor(){super("pulsebeam.v1.SendReq",[{no:1,name:"msg",kind:"message",T:()=>mt}])}},Ut=new Le,Ae=class extends f.MessageType{constructor(){super("pulsebeam.v1.SendResp",[])}},Ft=new Ae,je=class extends f.MessageType{constructor(){super("pulsebeam.v1.RecvReq",[{no:1,name:"info",kind:"message",T:()=>Gt}])}},Nt=new je,Ue=class extends f.MessageType{constructor(){super("pulsebeam.v1.RecvResp",[{no:1,name:"msgs",kind:"message",repeat:1,T:()=>mt}])}},qt=new Ue,Fe=class extends f.MessageType{constructor(){super("pulsebeam.v1.PeerInfo",[{no:1,name:"conn_id",kind:"scalar",T:13},{no:2,name:"enable_discovery",kind:"scalar",T:8}])}},Gt=new Fe,Ne=class extends f.MessageType{constructor(){super("pulsebeam.v1.Message",[{no:1,name:"header",kind:"message",T:()=>Kt},{no:2,name:"payload",kind:"message",T:()=>zt}])}},mt=new Ne,qe=class extends f.MessageType{constructor(){super("pulsebeam.v1.MessagePayload",[{no:1,name:"signal",kind:"message",oneof:"payloadType",T:()=>Jt},{no:2,name:"join",kind:"message",oneof:"payloadType",T:()=>Ht},{no:3,name:"bye",kind:"message",oneof:"payloadType",T:()=>Yt},{no:4,name:"ack",kind:"message",oneof:"payloadType",T:()=>Wt}])}},zt=new qe,Ge=class extends f.MessageType{constructor(){super("pulsebeam.v1.MessageHeader",[{no:1,name:"group_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"conn_id",kind:"scalar",T:13},{no:4,name:"other_group_id",kind:"scalar",T:9},{no:5,name:"other_peer_id",kind:"scalar",T:9},{no:6,name:"other_conn_id",kind:"scalar",T:13},{no:7,name:"seqnum",kind:"scalar",T:13},{no:8,name:"reliable",kind:"scalar",T:8}])}},Kt=new Ge,ze=class extends f.MessageType{constructor(){super("pulsebeam.v1.Signal",[{no:1,name:"generation_counter",kind:"scalar",T:13},{no:9,name:"sdp",kind:"message",oneof:"data",T:()=>Bt},{no:10,name:"ice_candidate",kind:"message",oneof:"data",T:()=>Vt}])}},Jt=new ze,Ke=class extends f.MessageType{constructor(){super("pulsebeam.v1.Sdp",[{no:1,name:"kind",kind:"enum",T:()=>["pulsebeam.v1.SdpKind",Qe,"SDP_KIND_"]},{no:2,name:"sdp",kind:"scalar",T:9}])}},Bt=new Ke,Je=class extends f.MessageType{constructor(){super("pulsebeam.v1.ICECandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"sdp_m_line_index",kind:"scalar",opt:!0,T:13},{no:3,name:"sdp_mid",kind:"scalar",opt:!0,T:9},{no:4,name:"username",kind:"scalar",opt:!0,T:9},{no:5,name:"password",kind:"scalar",opt:!0,T:9}])}},Vt=new Je,Be=class extends f.MessageType{constructor(){super("pulsebeam.v1.Join",[])}},Ht=new Be,Ve=class extends f.MessageType{constructor(){super("pulsebeam.v1.Bye",[])}},Yt=new Ve,He=class extends f.MessageType{constructor(){super("pulsebeam.v1.Ack",[{no:1,name:"ack_ranges",kind:"message",repeat:1,T:()=>Xt}])}},Wt=new He,Ye=class extends f.MessageType{constructor(){super("pulsebeam.v1.AckRange",[{no:1,name:"seqnum_start",kind:"scalar",T:13},{no:2,name:"seqnum_end",kind:"scalar",T:13}])}},Xt=new Ye,We=class extends f.MessageType{constructor(){super("pulsebeam.v1.DataChannel",[{no:10,name:"heartbeat",kind:"message",oneof:"payload",T:()=>Qt}])}},Tr=new We,Xe=class extends f.MessageType{constructor(){super("pulsebeam.v1.DataChannelHeartbeat",[])}},Qt=new Xe,B=new ut.ServiceType("pulsebeam.v1.Tunnel",[{name:"Prepare",options:{},I:Lt,O:At},{name:"Send",options:{},I:Ut,O:Ft},{name:"Recv",options:{},I:Nt,O:qt}]);var V=require("@protobuf-ts/runtime-rpc"),H=class{constructor(t){this._transport=t;this.typeName=B.typeName;this.methods=B.methods;this.options=B.options}prepare(t,r){let n=this.methods[0],s=this._transport.mergeOptions(r);return(0,V.stackIntercept)("unary",this._transport,n,s,t)}send(t,r){let n=this.methods[1],s=this._transport.mergeOptions(r);return(0,V.stackIntercept)("unary",this._transport,n,s,t)}recv(t,r){let n=this.methods[2],s=this._transport.mergeOptions(r);return(0,V.stackIntercept)("unary",this._transport,n,s,t)}};function Y(e,t){return new Promise(r=>{let n=setTimeout(()=>r(!0),e);t&&t.addEventListener("abort",()=>{clearTimeout(n),r(!1)})})}function W(...e){let t=new AbortController,r=()=>{t.abort();for(let n of e)n.removeEventListener("abort",r)};for(let n of e)n.addEventListener("abort",r);return t.signal}async function D(e,t){let{maxRetries:r,baseDelay:n,maxDelay:s,jitterFactor:i=.3,isRecoverable:o=()=>!0,abortSignal:a}=t,d=0;for(;(d<=r||r<0)&&!a?.aborted;)try{return await e()}catch(c){if(!o(c)||(d++,r>=0&&d>r))throw c;let p=Zt(d,n,s,i);await Y(p,a).catch(()=>{})}if(a?.aborted)return null;throw new Error("Retry failed: max retries exceeded")}function Zt(e,t,r,n){let s=Math.min(t*2**(e-1),r),i=Math.random()*n*s;return s+i}var ht=6e4,ft=50,X=1e3,$t=5,wt=3e4,er=5e3;var tr=Y,rr=e=>Math.floor(Math.random()*(2**32-e))+e,nr=e=>!0,Ze=class{constructor(t){this.onmsg=async t=>{};this.logger=t.sub("queue"),this.map=new Map,this.emitted=new Map,this.unreliable=[],this.processing=!1}enqueue(t){if(!t.header?.reliable)this.unreliable.push(t);else{let r=t.header.seqnum;if(this.map.has(r)||this.emitted.has(r))return;this.map.set(r,[performance.now(),t])}this.processNext()}async processNext(){if(this.processing)return;let t=this.unreliable.pop();if(!t){let r=this.map.entries().next().value;if(!r)return;let[n,s]=r;this.map.delete(n),this.emitted.set(n,s);let[i,o]=s;if(!o.header)return;t=o}this.processing=!0;try{await this.onmsg(t)}catch(r){let n={msg:t};r instanceof Error&&(n.err=r),this.logger.error("error processing message",n)}this.processing=!1,this.processNext()}},Q=class{constructor(t,r){this.client=t;this.opts=r;this.onstream=t=>{};this.onclosed=t=>{};this.handleMessages=t=>{for(let r of t){if(this.logger.debug("received",{msg:r}),this.abort.signal.aborted)return;if(!r.header)continue;if(r.header.otherConnId>=16&&r.header.otherConnId!=this.connId){this.logger.warn("received messages from a stale connection, ignoring",{receivedConnID:r.header.otherConnId});continue}let n=null;for(let s of this.streams)if(r.header.groupId===s.otherGroupId&&r.header.peerId===s.otherPeerId&&r.header.connId===s.otherConnId){n=s;break}if(!n){if(this.logger.debug(`session not found, creating one for ${r.header.peerId}:${r.header.connId}`),r.header.peerId==this.peerId){this.logger.warn("loopback detected, ignoring messages");return}n=new $e(this,r.header.groupId,r.header.peerId,r.header.connId,this.logger),this.streams.push(n),this.onstream(n)}n.enqueue(r)}};this.asleep=r.asleep||tr,this.randUint32=r.randUint32||rr,this.isRecoverable=r.isRecoverable||nr,this.groupId=r.groupId,this.peerId=r.peerId,this.connId=this.randUint32(16),this.info={connId:this.connId,enableDiscovery:r.enableDiscovery},this.abort=new AbortController,this.logger=r.logger.sub("transport",{groupId:this.opts.groupId,peerId:this.opts.peerId,connId:this.connId}),this.streams=[]}async listen(){await Promise.all([this.pollLoop(),this.gcLoop()])}async gcLoop(){for(;!this.abort.signal.aborted;)this.streams=this.streams.filter(t=>!t.isClosed()),await Y(er,this.abort.signal);this.logger.debug("gc loop is closed")}async pollLoop(){let t={abort:this.abort.signal,timeout:ht},r={baseDelay:ft,maxDelay:X,maxRetries:-1,abortSignal:this.abort.signal,isRecoverable:this.isRecoverable};for(;!this.abort.signal.aborted;)try{let n=await D(async()=>await this.client.recv({info:this.info},t),r);if(n===null)break;new Promise(()=>this.handleMessages(n.response.msgs))}catch(n){this.logger.error("unrecoverable error, force closing",{err:n}),this.close();return}this.logger.debug("poll loop is closed")}async close(t){this.abort.signal.aborted||(t=t||"transport is closed",await Promise.all(this.streams.map(r=>r.close(t))),this.abort.abort(t),this.logger.debug("transport is now closed",{reason:t}),this.streams=[],this.onclosed(t))}async connect(t,r,n){let s={payloadType:{oneofKind:"join",join:{}}},i={groupId:this.groupId,peerId:this.peerId,connId:this.connId,otherGroupId:t,otherPeerId:r,otherConnId:0,seqnum:0,reliable:!1},o=!1,a=W(n,this.abort.signal);for(;!a.aborted&&!o;)await this.send(a,{header:i,payload:s}),await this.asleep(X,a).catch(()=>{}),o=!!this.streams.find(d=>d.otherGroupId===t&&d.otherPeerId===r)}async send(t,r){let n=W(t,this.abort.signal),s={abort:n,timeout:ht},i={baseDelay:ft,maxDelay:X,maxRetries:-1,abortSignal:n,isRecoverable:this.isRecoverable};try{if(await D(async()=>await this.client.send({msg:r},s),i)===null){this.logger.warn("aborted, message dropped from sending",{msg:r});return}return}catch(o){this.logger.error("unrecoverable error, force closing",{err:o}),this.close();return}}},$e=class{constructor(t,r,n,s,i){this.transport=t;this.otherGroupId=r;this.otherPeerId=n;this.otherConnId=s;this.onpayload=async t=>{};this.onclosed=t=>{};this.logger=i.sub("stream",{otherGroupId:r,otherPeerId:n,otherConnId:s}),this.groupId=t.groupId,this.peerId=t.peerId,this.connId=t.connId,this.abort=new AbortController,this.ackedbuf={},this.recvq=new Ze(this.logger),this.recvq.onmsg=o=>this.handleMessage(o),this.lastSeqnum=0,this.closedAt=0}createSignal(...t){return W(this.abort.signal,...t)}isClosed(){let t=this.abort.signal.aborted&&performance.now()-this.closedAt>wt;return t&&this.logger.debug("stream is ready for GC"),t}enqueue(t){if(this.abort.signal.aborted){this.logger.warn("received a message in closed state, ignoring new messages.");return}this.recvq.enqueue(t)}async send(t,r,n){n||(n=this.abort.signal);let s={header:{groupId:this.transport.groupId,peerId:this.transport.peerId,connId:this.transport.connId,otherGroupId:this.otherGroupId,otherPeerId:this.otherPeerId,otherConnId:this.otherConnId,seqnum:0,reliable:r},payload:{...t}};if(!r){await this.transport.send(n,s);return}this.lastSeqnum++,s.header.seqnum=this.lastSeqnum,this.ackedbuf[s.header.seqnum]=!1;let i=$t,o=i,a=s.header.seqnum;for(;!n.aborted&&(await this.transport.send(this.abort.signal,s),await this.transport.asleep(5*X,this.abort.signal).catch(()=>{}),!this.ackedbuf[a]);){if(o<=0){let d="reached the maximum resend limit, dropping message";throw this.logger.warn(d,{seqnum:a,resendLimit:i,reliable:r}),new Error(d)}o--,this.logger.debug("resending",{...s.header})}}async handleMessage(t){let r=t.payload.payloadType;switch(r.oneofKind){case"ack":this.handleAck(r.ack);break;case"bye":this.close("received bye from other peer");break;case void 0:break;default:{if(t.header.reliable){let s={payloadType:{oneofKind:"ack",ack:{ackRanges:[{seqnumStart:t.header.seqnum,seqnumEnd:t.header.seqnum+1}]}}};this.logger.debug("ack",{seqnum:t.header.seqnum}),this.send(s,!1)}if(!t.payload)return;await this.onpayload(t.payload);break}}}handleAck(t){for(let r of t.ackRanges)for(let n=r.seqnumStart;n<r.seqnumEnd;n++)this.logger.debug("received ack",{seqnum:n}),this.ackedbuf[n]=!0}async close(t){this.abort.signal.aborted||(t=t||"session is closed",await this.send({payloadType:{oneofKind:"bye",bye:{}}},!1).catch(r=>this.logger.warn("failed to send bye",{e:r})),this.abort.abort(t),this.closedAt=performance.now(),this.onclosed(t),this.logger.debug("sent bye to the other peer",{reason:t}))}};var sr={DEBUG:console.debug,INFO:console.info,WARN:console.warn,ERROR:console.error},gt={DEBUG:e=>console.debug(Z(e)),INFO:e=>console.info(Z(e)),WARN:e=>console.warn(Z(e)),ERROR:e=>console.error(Z(e))};function Ct(e,t,r="root",n=new Set){let s=".";if(!n.has(e)){n.add(e);for(let i in e)if(typeof e[i]=="object"&&e[i]!==null){let o=r+s+i;Ct(e[i],t,o,n)}else{let o=t[r]||[];o.push(`${i}=${e[i]}`),t[r]=o}}}function Z(e){let t={};Ct(e,t);let r=[];for(let n in t)r.push(`[${n}] ${t[n].join(" ")}`);return r.join(`
36
- `)}var $=class e{constructor(t,r,n){this.name=t;r||(r={}),n||(n=sr),this.sink=n,this.obj={...r,name:t}}log(t,r,n){let s=n||{};t({ts:Date.now(),message:r,...this.obj,...s})}debug(t,r){this.log(this.sink.DEBUG,t,r)}info(t,r){this.log(this.sink.INFO,t,r)}warn(t,r){this.log(this.sink.WARN,t,r)}error(t,r){this.log(this.sink.ERROR,t,r)}sub(t,r){return r||(r={}),new e(this.name+"."+t,{...this.obj,...r},this.sink)}};var ir=2,yt=5e3;function St(e){return{candidate:e.candidate,sdpMid:e.sdpMid,sdpMLineIndex:e.sdpMLineIndex,usernameFragment:e.password}}function or(e){switch(e){case 1:return"offer";case 2:return"answer";case 3:return"pranswer";case 4:return"rollback";default:throw new Error(`unexpected kind: ${e}`)}}function Rt(e){switch(e){case"offer":return 1;case"answer":return 2;case"pranswer":return 3;case"rollback":return 4;default:throw new Error(`unexpected sdp type: ${e}`)}}var w=class{constructor(t,r){this.stream=t;this.ondatachannel=()=>{};this.onconnectionstatechange=()=>{};this.ontrack=()=>{};this.triggerIceRestart=()=>{if(!this.impolite)return;let t=performance.now()-this.lastIceRestart;if(t<yt){let r=yt-t,n=window.setTimeout(()=>{this.triggerIceRestart(),this.timers=this.timers.filter(s=>s===n)},r);return}this.pc.connectionState!=="connected"&&(this.iceRestartCount>=ir&&this.close(),this.logger.debug("triggered ICE restart"),this.pc.restartIce(),this.generationCounter++,this.iceRestartCount++,this.lastIceRestart=performance.now())};this.sendSignal=t=>{this.stream.send({payloadType:{oneofKind:"signal",signal:{...t,generationCounter:this.generationCounter}}},!0)};this.handleMessage=async t=>{if(this.abort.signal.aborted){this.logger.warn("session is closed, ignoring message");return}switch(t.payloadType.oneofKind){case"signal":await this.handleSignal(t.payloadType.signal);break;case"bye":this.close();break;case"join":break}};this.handleSignal=async t=>{if(t.generationCounter<this.generationCounter){this.logger.warn("detected staled generationCounter signals, ignoring");return}let r=t.data;if(t.generationCounter>this.generationCounter){if(this.logger.debug("detected new generationCounter",{otherGenerationCounter:t.generationCounter,generationCounter:this.generationCounter,msg:r}),r.oneofKind==="iceCandidate"){let o=St(r.iceCandidate);this.pendingCandidates.push(o),this.logger.warn("expecting an offer but got ice candidates during an ICE restart, adding to pending.",{ice:o,msg:r});return}this.generationCounter=t.generationCounter}if(r.oneofKind==="iceCandidate"){let o=St(r.iceCandidate);this.pendingCandidates.push(o),this.checkPendingCandidates();return}if(r.oneofKind!="sdp")return;let n=r.sdp;this.logger.debug("received a SDP signal",{sdpKind:n.kind});let s=n.kind===1&&(this.makingOffer||this.pc.signalingState!=="stable");if(this.impolite&&s){this.logger.debug("ignored offer");return}if(this.logger.debug("creating an answer"),await this.pc.setRemoteDescription({type:or(n.kind),sdp:n.sdp}),n.kind===1){if(await this.pc.setLocalDescription(),!this.pc.localDescription){this.logger.error("unexpected null local description");return}this.sendSignal({data:{oneofKind:"sdp",sdp:{kind:Rt(this.pc.localDescription.type),sdp:this.pc.localDescription.sdp}}})}this.checkPendingCandidates()};this.checkPendingCandidates=()=>{if(!["stable","have-local-offer","have-remote-offer"].includes(this.pc.signalingState)||!this.pc.remoteDescription){this.logger.debug("wait for adding pending candidates",{signalingState:this.pc.signalingState,iceConnectionState:this.pc.iceConnectionState,connectionState:this.pc.connectionState,remoteDescription:this.pc.remoteDescription,pendingCandidates:this.pendingCandidates.length});return}for(let r of this.pendingCandidates)!r.candidate||r.candidate===""||(this.pc.addIceCandidate(r).catch(n=>{this.logger.warn("failed to add candidate, skipping.",{candidate:r,e:n})}),this.logger.debug(`added ice: ${r.candidate}`));this.pendingCandidates=[]};this.pc=new RTCPeerConnection(r),this.makingOffer=!1,this.pendingCandidates=[],this.stream.connId===this.stream.otherConnId?this.impolite=this.stream.peerId>this.stream.otherPeerId:this.impolite=this.stream.connId>this.stream.otherConnId,this.abort=new AbortController,this.logger=t.logger.sub("session",{role:this.impolite?"impolite":"polite"}),this.generationCounter=0,this.iceRestartCount=0,this.lastIceRestart=0,this.timers=[],this._connectionState="new",t.onpayload=i=>this.handleMessage(i),t.onclosed=i=>this.close(i),this.pc.oniceconnectionstatechange=async()=>{let i=await this.pc.getStats(),o=[],a=[],d=[];i.forEach(c=>{c.type==="candidate-pair"?o.push(c):c.type==="local-candidate"?a.push(c):c.type==="remote-candidate"&&d.push(c)}),this.logger.debug("iceconnectionstate changed",{connectionstate:this.pc.connectionState,iceconnectionstate:this.pc.iceConnectionState,local:a,remote:d,pair:o,pending:this.pendingCandidates})};let n=performance.now();this.pc.onconnectionstatechange=i=>{switch(this.logger.debug("connectionstate changed",{connectionstate:this.pc.connectionState,iceconnectionstate:this.pc.iceConnectionState}),this.pc.connectionState){case"connecting":n=performance.now();break;case"connected":{let o=performance.now()-n;this.logger.debug(`it took ${o}ms to connect`),this.iceRestartCount=0;break}case"disconnected":this.triggerIceRestart();break;case"failed":this.triggerIceRestart();break;case"closed":break}this.setConnectionState(this.pc.connectionState,i)};let s=!0;this.pc.onnegotiationneeded=async()=>{if(s){if(!this.impolite){this.stream.send({payloadType:{oneofKind:"join",join:{}}},!0);return}s=!1}try{if(this.makingOffer=!0,this.logger.debug("creating an offer"),await this.pc.setLocalDescription(),!this.pc.localDescription)throw new Error("expect localDescription to be not empty");this.sendSignal({data:{oneofKind:"sdp",sdp:{kind:Rt(this.pc.localDescription.type),sdp:this.pc.localDescription.sdp}}})}catch(i){i instanceof Error&&this.logger.error("failed in negotiating",{err:i})}finally{this.makingOffer=!1}},this.pc.onicecandidate=({candidate:i})=>{this.logger.debug("onicecandidate",{candidate:i});let o={candidate:"",sdpMLineIndex:0,sdpMid:""};if(!i||i.candidate===""){this.logger.debug("ice gathering is finished");return}o.candidate=i.candidate,o.sdpMLineIndex=i.sdpMLineIndex??void 0,o.sdpMid=i.sdpMid??void 0,o.username=i.usernameFragment??void 0,this.sendSignal({data:{oneofKind:"iceCandidate",iceCandidate:o}})},this.pc.ondatachannel=(...i)=>{this.ondatachannel&&this.ondatachannel(...i)},this.pc.ontrack=(...i)=>{this.ontrack&&this.ontrack(...i)}}addTrack(...t){return this.pc.addTrack(...t)}removeTrack(...t){return this.pc.removeTrack(...t)}createDataChannel(...t){return this.pc.createDataChannel(...t)}get connectionState(){return this.pc.connectionState}get closeReason(){return this._closeReason}get otherPeerId(){return this.stream.otherPeerId}get otherConnId(){return this.stream.otherConnId}close(t){if(this.abort.signal.aborted)return;this.abort.abort(t);for(let n of this.timers)clearTimeout(n);this.timers=[],this.stream.close(),this._closeReason=t,this.pc.close();let r=new Event("connectionstatechange");this.setConnectionState("closed",r),this.logger.debug("session closed",{connectionState:this.connectionState})}setConnectionState(t,r){t!==this._connectionState&&this.onconnectionstatechange&&this.onconnectionstatechange(r)}};var Tt=require("@protobuf-ts/runtime-rpc"),C=require("@protobuf-ts/twirp-transport");var bt=require("jwt-decode"),ar="https://cloud.pulsebeam.dev/twirp";var ee=class{constructor(t,r,n,s){this.onsession=t=>{};this.onstatechange=()=>{};this.peerId=n.peerId,this.logger=t.sub("peer",{peerId:this.peerId}),this.sessions=[],this._state="new";let i={bundlePolicy:"balanced",iceTransportPolicy:n.forceRelay?"relay":"all",iceCandidatePoolSize:0,iceServers:n.iceServers};this.transport=new Q(r,{enableDiscovery:!1,groupId:n.groupId,peerId:n.peerId,logger:this.logger,isRecoverable:s}),this.transport.onstream=o=>{let a=new w(o,i);this.sessions.push(a),this.onsession(a)},this.transport.onclosed=()=>{this.close()}}start(){if(this._state==="closed")throw new Error("peer is already closed");this.transport.listen()}async close(){this.sessions=[],await this.transport.close(),this.setState("closed")}connect(t,r,n){return this.transport.connect(t,r,n)}get state(){return this._state}setState(t){t!==this._state&&(this._state=t,this.onstatechange())}},cr=[C.TwirpErrorCode[C.TwirpErrorCode.permission_denied],C.TwirpErrorCode[C.TwirpErrorCode.invalid_argument],C.TwirpErrorCode[C.TwirpErrorCode.aborted],C.TwirpErrorCode[C.TwirpErrorCode.bad_route],C.TwirpErrorCode[C.TwirpErrorCode.malformed],C.TwirpErrorCode[C.TwirpErrorCode.not_found],C.TwirpErrorCode[C.TwirpErrorCode.unauthenticated]];function vt(e){return e instanceof Error?e instanceof Tt.RpcError?!cr.includes(e.code):!0:!1}async function pr(e){let t=e.token,r=new C.TwirpFetchTransport({baseUrl:e.baseUrl||ar,sendJson:!1,jsonOptions:{emitDefaultValues:!0,enumAsInteger:!0,ignoreUnknownFields:!0},interceptors:[{interceptUnary(c,p,u,m){return m.meta||(m.meta={}),m.meta.Authorization=`Bearer ${t}`,c(p,u,m)}}]}),n=new H(r),s=await D(async()=>await n.prepare({}),{baseDelay:50,maxDelay:1e3,maxRetries:5,isRecoverable:vt});if(s===null)throw new Error("createPeer aborted");let i=[...e.iceServers||[]];for(let c of s.response.iceServers)i.push({urls:c.urls,username:c.username,credential:c.credential});let o=(0,bt.jwtDecode)(t),a={...e,iceServers:i,groupId:o.gid,peerId:o.pid};return new ee(new $("pulsebeam",void 0,gt),n,a,vt)}M.disableLog(!1);M.disableWarnings(!1);console.log("UA: ",navigator.userAgent);console.log("webrtc-adapter is enabled",JSON.stringify({shim:M.browserShim,version:M.browserDetails},null,2));0&&(module.exports={Peer,createPeer});
35
+ `);e.RTCSessionDescription&&s instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:s.type,sdp:i}):s.sdp=i}return r.apply(this,arguments)}}function _(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let r=e.RTCPeerConnection.prototype.addIceCandidate;!r||r.length===0||(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser==="chrome"&&t.version<78||t.browser==="firefox"&&t.version<68||t.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function E(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let r=e.RTCPeerConnection.prototype.setLocalDescription;!r||r.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return r.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?r.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>r.apply(this,[o]))})}var Dt=et(_e());function lt({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){let r=L,n=ot(e),s={browserDetails:n,commonShim:Ee,extractVersion:P,disableLog:st,disableWarnings:it,sdp:Dt};switch(n.browser){case"chrome":if(!U||!j||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),s;if(n.version===null)return r("Chrome shim can not determine version, not shimming."),s;r("adapter.js shimming chrome."),s.browserShim=U,_(e,n),E(e,n),A(e,n),se(e,n),j(e,n),ie(e,n),ce(e,n),oe(e,n),ae(e,n),pe(e,n),x(e,n),z(e,n),K(e,n),k(e,n),I(e,n),J(e,n);break;case"firefox":if(!q||!N||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),s;r("adapter.js shimming firefox."),s.browserShim=q,_(e,n),E(e,n),F(e,n),N(e,n),de(e,n),me(e,n),le(e,n),ue(e,n),he(e,n),fe(e,n),ge(e,n),Ce(e,n),ye(e,n),x(e,n),K(e,n),k(e,n),I(e,n);break;case"safari":if(!G||!t.shimSafari)return r("Safari shim is not included in this adapter release."),s;r("adapter.js shimming safari."),s.browserShim=G,_(e,n),E(e,n),be(e,n),xe(e,n),ve(e,n),Se(e,n),Re(e,n),Pe(e,n),Te(e,n),ke(e,n),x(e,n),z(e,n),k(e,n),I(e,n),J(e,n);break;default:r("Unsupported browser!");break}return s}var Ot=lt({window:typeof window>"u"?void 0:window}),M=Ot;var ut=require("@protobuf-ts/runtime-rpc"),f=require("@protobuf-ts/runtime"),Qe=(i=>(i[i.UNSPECIFIED=0]="UNSPECIFIED",i[i.OFFER=1]="OFFER",i[i.ANSWER=2]="ANSWER",i[i.PRANSWER=3]="PRANSWER",i[i.ROLLBACK=4]="ROLLBACK",i))(Qe||{}),Me=class extends f.MessageType{constructor(){super("pulsebeam.v1.PrepareReq",[])}},Lt=new Me,De=class extends f.MessageType{constructor(){super("pulsebeam.v1.PrepareResp",[{no:1,name:"ice_servers",kind:"message",repeat:1,T:()=>jt}])}},At=new De,Oe=class extends f.MessageType{constructor(){super("pulsebeam.v1.IceServer",[{no:1,name:"urls",kind:"scalar",repeat:2,T:9},{no:2,name:"username",kind:"scalar",opt:!0,T:9},{no:3,name:"credential",kind:"scalar",opt:!0,T:9}])}},jt=new Oe,Le=class extends f.MessageType{constructor(){super("pulsebeam.v1.SendReq",[{no:1,name:"msg",kind:"message",T:()=>mt}])}},Ut=new Le,Ae=class extends f.MessageType{constructor(){super("pulsebeam.v1.SendResp",[])}},Ft=new Ae,je=class extends f.MessageType{constructor(){super("pulsebeam.v1.RecvReq",[{no:1,name:"info",kind:"message",T:()=>Gt}])}},Nt=new je,Ue=class extends f.MessageType{constructor(){super("pulsebeam.v1.RecvResp",[{no:1,name:"msgs",kind:"message",repeat:1,T:()=>mt}])}},qt=new Ue,Fe=class extends f.MessageType{constructor(){super("pulsebeam.v1.PeerInfo",[{no:1,name:"conn_id",kind:"scalar",T:13},{no:2,name:"enable_discovery",kind:"scalar",T:8}])}},Gt=new Fe,Ne=class extends f.MessageType{constructor(){super("pulsebeam.v1.Message",[{no:1,name:"header",kind:"message",T:()=>Kt},{no:2,name:"payload",kind:"message",T:()=>zt}])}},mt=new Ne,qe=class extends f.MessageType{constructor(){super("pulsebeam.v1.MessagePayload",[{no:1,name:"signal",kind:"message",oneof:"payloadType",T:()=>Jt},{no:2,name:"join",kind:"message",oneof:"payloadType",T:()=>Ht},{no:3,name:"bye",kind:"message",oneof:"payloadType",T:()=>Yt},{no:4,name:"ack",kind:"message",oneof:"payloadType",T:()=>Wt}])}},zt=new qe,Ge=class extends f.MessageType{constructor(){super("pulsebeam.v1.MessageHeader",[{no:1,name:"group_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"conn_id",kind:"scalar",T:13},{no:4,name:"other_group_id",kind:"scalar",T:9},{no:5,name:"other_peer_id",kind:"scalar",T:9},{no:6,name:"other_conn_id",kind:"scalar",T:13},{no:7,name:"seqnum",kind:"scalar",T:13},{no:8,name:"reliable",kind:"scalar",T:8}])}},Kt=new Ge,ze=class extends f.MessageType{constructor(){super("pulsebeam.v1.Signal",[{no:1,name:"generation_counter",kind:"scalar",T:13},{no:9,name:"sdp",kind:"message",oneof:"data",T:()=>Bt},{no:10,name:"ice_candidate",kind:"message",oneof:"data",T:()=>Vt}])}},Jt=new ze,Ke=class extends f.MessageType{constructor(){super("pulsebeam.v1.Sdp",[{no:1,name:"kind",kind:"enum",T:()=>["pulsebeam.v1.SdpKind",Qe,"SDP_KIND_"]},{no:2,name:"sdp",kind:"scalar",T:9}])}},Bt=new Ke,Je=class extends f.MessageType{constructor(){super("pulsebeam.v1.ICECandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"sdp_m_line_index",kind:"scalar",opt:!0,T:13},{no:3,name:"sdp_mid",kind:"scalar",opt:!0,T:9},{no:4,name:"username",kind:"scalar",opt:!0,T:9},{no:5,name:"password",kind:"scalar",opt:!0,T:9}])}},Vt=new Je,Be=class extends f.MessageType{constructor(){super("pulsebeam.v1.Join",[])}},Ht=new Be,Ve=class extends f.MessageType{constructor(){super("pulsebeam.v1.Bye",[])}},Yt=new Ve,He=class extends f.MessageType{constructor(){super("pulsebeam.v1.Ack",[{no:1,name:"ack_ranges",kind:"message",repeat:1,T:()=>Xt}])}},Wt=new He,Ye=class extends f.MessageType{constructor(){super("pulsebeam.v1.AckRange",[{no:1,name:"seqnum_start",kind:"scalar",T:13},{no:2,name:"seqnum_end",kind:"scalar",T:13}])}},Xt=new Ye,We=class extends f.MessageType{constructor(){super("pulsebeam.v1.DataChannel",[{no:10,name:"heartbeat",kind:"message",oneof:"payload",T:()=>Qt}])}},Tr=new We,Xe=class extends f.MessageType{constructor(){super("pulsebeam.v1.DataChannelHeartbeat",[])}},Qt=new Xe,B=new ut.ServiceType("pulsebeam.v1.Tunnel",[{name:"Prepare",options:{},I:Lt,O:At},{name:"Send",options:{},I:Ut,O:Ft},{name:"Recv",options:{},I:Nt,O:qt}]);var V=require("@protobuf-ts/runtime-rpc"),H=class{constructor(t){this._transport=t;this.typeName=B.typeName;this.methods=B.methods;this.options=B.options}prepare(t,r){let n=this.methods[0],s=this._transport.mergeOptions(r);return(0,V.stackIntercept)("unary",this._transport,n,s,t)}send(t,r){let n=this.methods[1],s=this._transport.mergeOptions(r);return(0,V.stackIntercept)("unary",this._transport,n,s,t)}recv(t,r){let n=this.methods[2],s=this._transport.mergeOptions(r);return(0,V.stackIntercept)("unary",this._transport,n,s,t)}};function Y(e,t){return new Promise(r=>{let n=setTimeout(()=>r(!0),e);t&&t.addEventListener("abort",()=>{clearTimeout(n),r(!1)})})}function W(...e){let t=new AbortController,r=()=>{t.abort();for(let n of e)n.removeEventListener("abort",r)};for(let n of e)n.addEventListener("abort",r);return t.signal}async function D(e,t){let{maxRetries:r,baseDelay:n,maxDelay:s,jitterFactor:i=.3,isRecoverable:o=()=>!0,abortSignal:a}=t,d=0;for(;(d<=r||r<0)&&!a?.aborted;)try{return await e()}catch(c){if(!o(c)||(d++,r>=0&&d>r))throw c;let p=Zt(d,n,s,i);await Y(p,a).catch(()=>{})}if(a?.aborted)return null;throw new Error("Retry failed: max retries exceeded")}function Zt(e,t,r,n){let s=Math.min(t*2**(e-1),r),i=Math.random()*n*s;return s+i}var ht=9e5,ft=50,X=1e3,$t=5,wt=1e4,er=1e3;var tr=Y,rr=e=>Math.floor(Math.random()*(2**32-e))+e,nr=e=>!0,Ze=class{constructor(t){this.onmsg=async t=>{};this.logger=t.sub("queue"),this.map=new Map,this.emitted=new Map,this.unreliable=[],this.processing=!1}enqueue(t){if(!t.header?.reliable)this.unreliable.push(t);else{let r=t.header.seqnum;if(this.map.has(r)||this.emitted.has(r))return;this.map.set(r,[performance.now(),t])}this.processNext()}async processNext(){if(this.processing)return;let t=this.unreliable.pop();if(!t){let r=this.map.entries().next().value;if(!r)return;let[n,s]=r;this.map.delete(n),this.emitted.set(n,s);let[i,o]=s;if(!o.header)return;t=o}this.processing=!0;try{await this.onmsg(t)}catch(r){let n={msg:t};r instanceof Error&&(n.err=r),this.logger.error("error processing message",n)}this.processing=!1,this.processNext()}},Q=class{constructor(t,r){this.client=t;this.opts=r;this.onstream=t=>{};this.onclosed=t=>{};this.handleMessages=t=>{for(let r of t){if(this.logger.debug("received",{msg:r}),this.abort.signal.aborted)return;if(!r.header)continue;if(r.header.otherConnId>=16&&r.header.otherConnId!=this.connId){this.logger.warn("received messages from a stale connection, ignoring",{receivedConnID:r.header.otherConnId});continue}let n=null;for(let s of this.streams)if(r.header.groupId===s.otherGroupId&&r.header.peerId===s.otherPeerId&&r.header.connId===s.otherConnId){n=s;break}if(!n){if(this.logger.debug(`session not found, creating one for ${r.header.peerId}:${r.header.connId}`),r.header.peerId==this.peerId){this.logger.warn("loopback detected, ignoring messages");return}n=new $e(this,r.header.groupId,r.header.peerId,r.header.connId,this.logger),this.streams.push(n),this.onstream(n)}n.enqueue(r)}};this.asleep=r.asleep||tr,this.randUint32=r.randUint32||rr,this.isRecoverable=r.isRecoverable||nr,this.groupId=r.groupId,this.peerId=r.peerId,this.connId=this.randUint32(16),this.info={connId:this.connId,enableDiscovery:r.enableDiscovery},this.abort=new AbortController,this.logger=r.logger.sub("transport",{groupId:this.opts.groupId,peerId:this.opts.peerId,connId:this.connId}),this.streams=[]}async listen(){await Promise.all([this.pollLoop(),this.gcLoop()])}async gcLoop(){for(;!this.abort.signal.aborted;)this.streams=this.streams.filter(t=>!t.isClosed()),await Y(er,this.abort.signal);this.logger.debug("gc loop is closed")}async pollLoop(){let t={abort:this.abort.signal,timeout:ht},r={baseDelay:ft,maxDelay:X,maxRetries:-1,abortSignal:this.abort.signal,isRecoverable:this.isRecoverable};for(;!this.abort.signal.aborted;)try{let n=await D(async()=>await this.client.recv({info:this.info},t),r);if(n===null)break;new Promise(()=>this.handleMessages(n.response.msgs))}catch(n){this.logger.error("unrecoverable error, force closing",{err:n}),this.close();return}this.logger.debug("poll loop is closed")}async close(t){this.abort.signal.aborted||(t=t||"transport is closed",await Promise.all(this.streams.map(r=>r.close(t))),this.abort.abort(t),this.logger.debug("transport is now closed",{reason:t}),this.streams=[],this.onclosed(t))}async connect(t,r,n){let s={payloadType:{oneofKind:"join",join:{}}},i={groupId:this.groupId,peerId:this.peerId,connId:this.connId,otherGroupId:t,otherPeerId:r,otherConnId:0,seqnum:0,reliable:!1},o=!1,a=W(n,this.abort.signal);for(;!a.aborted&&!o;)await this.send(a,{header:i,payload:s}),await this.asleep(X,a).catch(()=>{}),o=!!this.streams.find(d=>d.otherGroupId===t&&d.otherPeerId===r)}async send(t,r){let n=W(t,this.abort.signal),s={abort:n,timeout:ht},i={baseDelay:ft,maxDelay:X,maxRetries:-1,abortSignal:n,isRecoverable:this.isRecoverable};try{if(await D(async()=>await this.client.send({msg:r},s),i)===null){this.logger.warn("aborted, message dropped from sending",{msg:r});return}return}catch(o){this.logger.error("unrecoverable error, force closing",{err:o}),this.close();return}}},$e=class{constructor(t,r,n,s,i){this.transport=t;this.otherGroupId=r;this.otherPeerId=n;this.otherConnId=s;this.onpayload=async t=>{};this.onclosed=t=>{};this.logger=i.sub("stream",{otherGroupId:r,otherPeerId:n,otherConnId:s}),this.groupId=t.groupId,this.peerId=t.peerId,this.connId=t.connId,this.abort=new AbortController,this.ackedbuf={},this.recvq=new Ze(this.logger),this.recvq.onmsg=o=>this.handleMessage(o),this.lastSeqnum=0,this.closedAt=0}createSignal(...t){return W(this.abort.signal,...t)}isClosed(){let t=this.abort.signal.aborted&&performance.now()-this.closedAt>wt;return t&&this.logger.debug("stream is ready for GC"),t}enqueue(t){if(this.abort.signal.aborted){this.logger.warn("received a message in closed state, ignoring new messages.");return}this.recvq.enqueue(t)}async send(t,r,n){n||(n=this.abort.signal);let s={header:{groupId:this.transport.groupId,peerId:this.transport.peerId,connId:this.transport.connId,otherGroupId:this.otherGroupId,otherPeerId:this.otherPeerId,otherConnId:this.otherConnId,seqnum:0,reliable:r},payload:{...t}};if(!r){await this.transport.send(n,s);return}this.lastSeqnum++,s.header.seqnum=this.lastSeqnum,this.ackedbuf[s.header.seqnum]=!1;let i=$t,o=i,a=s.header.seqnum;for(;!n.aborted&&(await this.transport.send(this.abort.signal,s),await this.transport.asleep(5*X,this.abort.signal).catch(()=>{}),!this.ackedbuf[a]);){if(o<=0){let d="reached the maximum resend limit, dropping message";throw this.logger.warn(d,{seqnum:a,resendLimit:i,reliable:r}),new Error(d)}o--,this.logger.debug("resending",{...s.header})}}async handleMessage(t){let r=t.payload.payloadType;switch(r.oneofKind){case"ack":this.handleAck(r.ack);break;case"bye":this.close("received bye from other peer");break;case void 0:break;default:{if(t.header.reliable){let s={payloadType:{oneofKind:"ack",ack:{ackRanges:[{seqnumStart:t.header.seqnum,seqnumEnd:t.header.seqnum+1}]}}};this.logger.debug("ack",{seqnum:t.header.seqnum}),this.send(s,!1)}if(!t.payload)return;await this.onpayload(t.payload);break}}}handleAck(t){for(let r of t.ackRanges)for(let n=r.seqnumStart;n<r.seqnumEnd;n++)this.logger.debug("received ack",{seqnum:n}),this.ackedbuf[n]=!0}async close(t){this.abort.signal.aborted||(t=t||"session is closed",await this.send({payloadType:{oneofKind:"bye",bye:{}}},!1).catch(r=>this.logger.warn("failed to send bye",{e:r})),this.abort.abort(t),this.closedAt=performance.now(),this.onclosed(t),this.logger.debug("sent bye to the other peer",{reason:t}))}};var sr={DEBUG:console.debug,INFO:console.info,WARN:console.warn,ERROR:console.error},gt={DEBUG:e=>console.debug(Z(e)),INFO:e=>console.info(Z(e)),WARN:e=>console.warn(Z(e)),ERROR:e=>console.error(Z(e))};function Ct(e,t,r="root",n=new Set){let s=".";if(!n.has(e)){n.add(e);for(let i in e)if(typeof e[i]=="object"&&e[i]!==null){let o=r+s+i;Ct(e[i],t,o,n)}else{let o=t[r]||[];o.push(`${i}=${e[i]}`),t[r]=o}}}function Z(e){let t={};Ct(e,t);let r=[];for(let n in t)r.push(`[${n}] ${t[n].join(" ")}`);return r.join(`
36
+ `)}var $=class e{constructor(t,r,n){this.name=t;r||(r={}),n||(n=sr),this.sink=n,this.obj={...r,name:t}}log(t,r,n){let s=n||{};t({ts:Date.now(),message:r,...this.obj,...s})}debug(t,r){this.log(this.sink.DEBUG,t,r)}info(t,r){this.log(this.sink.INFO,t,r)}warn(t,r){this.log(this.sink.WARN,t,r)}error(t,r){this.log(this.sink.ERROR,t,r)}sub(t,r){return r||(r={}),new e(this.name+"."+t,{...this.obj,...r},this.sink)}};var ir=2,yt=5e3;function St(e){return{candidate:e.candidate,sdpMid:e.sdpMid,sdpMLineIndex:e.sdpMLineIndex,usernameFragment:e.password}}function or(e){switch(e){case 1:return"offer";case 2:return"answer";case 3:return"pranswer";case 4:return"rollback";default:throw new Error(`unexpected kind: ${e}`)}}function Rt(e){switch(e){case"offer":return 1;case"answer":return 2;case"pranswer":return 3;case"rollback":return 4;default:throw new Error(`unexpected sdp type: ${e}`)}}var w=class{constructor(t,r){this.stream=t;this.ondatachannel=()=>{};this.onconnectionstatechange=()=>{};this.ontrack=()=>{};this.triggerIceRestart=()=>{if(!this.impolite)return;let t=performance.now()-this.lastIceRestart;if(t<yt){let r=yt-t,n=window.setTimeout(()=>{this.triggerIceRestart(),this.timers=this.timers.filter(s=>s===n)},r);return}this.pc.connectionState!=="connected"&&(this.iceRestartCount>=ir&&this.close(),this.logger.debug("triggered ICE restart"),this.pc.restartIce(),this.generationCounter++,this.iceRestartCount++,this.lastIceRestart=performance.now())};this.sendSignal=t=>{this.stream.send({payloadType:{oneofKind:"signal",signal:{...t,generationCounter:this.generationCounter}}},!0)};this.handleMessage=async t=>{if(this.abort.signal.aborted){this.logger.warn("session is closed, ignoring message");return}switch(t.payloadType.oneofKind){case"signal":await this.handleSignal(t.payloadType.signal);break;case"bye":this.close();break;case"join":break}};this.handleSignal=async t=>{if(t.generationCounter<this.generationCounter){this.logger.warn("detected staled generationCounter signals, ignoring");return}let r=t.data;if(t.generationCounter>this.generationCounter){if(this.logger.debug("detected new generationCounter",{otherGenerationCounter:t.generationCounter,generationCounter:this.generationCounter,msg:r}),r.oneofKind==="iceCandidate"){let o=St(r.iceCandidate);this.pendingCandidates.push(o),this.logger.warn("expecting an offer but got ice candidates during an ICE restart, adding to pending.",{ice:o,msg:r});return}this.generationCounter=t.generationCounter}if(r.oneofKind==="iceCandidate"){let o=St(r.iceCandidate);this.pendingCandidates.push(o),this.checkPendingCandidates();return}if(r.oneofKind!="sdp")return;let n=r.sdp;this.logger.debug("received a SDP signal",{sdpKind:n.kind});let s=n.kind===1&&(this.makingOffer||this.pc.signalingState!=="stable");if(this.impolite&&s){this.logger.debug("ignored offer");return}if(this.logger.debug("creating an answer"),await this.pc.setRemoteDescription({type:or(n.kind),sdp:n.sdp}),n.kind===1){if(await this.pc.setLocalDescription(),!this.pc.localDescription){this.logger.error("unexpected null local description");return}this.sendSignal({data:{oneofKind:"sdp",sdp:{kind:Rt(this.pc.localDescription.type),sdp:this.pc.localDescription.sdp}}})}this.checkPendingCandidates()};this.checkPendingCandidates=()=>{if(!["stable","have-local-offer","have-remote-offer"].includes(this.pc.signalingState)||!this.pc.remoteDescription){this.logger.debug("wait for adding pending candidates",{signalingState:this.pc.signalingState,iceConnectionState:this.pc.iceConnectionState,connectionState:this.pc.connectionState,remoteDescription:this.pc.remoteDescription,pendingCandidates:this.pendingCandidates.length});return}for(let r of this.pendingCandidates)!r.candidate||r.candidate===""||(this.pc.addIceCandidate(r).catch(n=>{this.logger.warn("failed to add candidate, skipping.",{candidate:r,e:n})}),this.logger.debug(`added ice: ${r.candidate}`));this.pendingCandidates=[]};this.pc=new RTCPeerConnection(r),this.makingOffer=!1,this.pendingCandidates=[],this.stream.connId===this.stream.otherConnId?this.impolite=this.stream.peerId>this.stream.otherPeerId:this.impolite=this.stream.connId>this.stream.otherConnId,this.abort=new AbortController,this.logger=t.logger.sub("session",{role:this.impolite?"impolite":"polite"}),this.generationCounter=0,this.iceRestartCount=0,this.lastIceRestart=0,this.timers=[],this._connectionState="new",t.onpayload=i=>this.handleMessage(i),t.onclosed=i=>this.close(i),this.pc.oniceconnectionstatechange=async()=>{let i=await this.pc.getStats(),o=[],a=[],d=[];i.forEach(c=>{c.type==="candidate-pair"?o.push(c):c.type==="local-candidate"?a.push(c):c.type==="remote-candidate"&&d.push(c)}),this.logger.debug("iceconnectionstate changed",{connectionstate:this.pc.connectionState,iceconnectionstate:this.pc.iceConnectionState,local:a,remote:d,pair:o,pending:this.pendingCandidates})};let n=performance.now();this.pc.onconnectionstatechange=i=>{switch(this.logger.debug("connectionstate changed",{connectionstate:this.pc.connectionState,iceconnectionstate:this.pc.iceConnectionState}),this.setConnectionState(this.pc.connectionState,i),this.pc.connectionState){case"connecting":n=performance.now();break;case"connected":{let o=performance.now()-n;this.logger.debug(`it took ${o}ms to connect`),this.iceRestartCount=0;break}case"disconnected":this.triggerIceRestart();break;case"failed":this.close("detected sustained network failure");break;case"closed":break}};let s=!0;this.pc.onnegotiationneeded=async()=>{if(s){if(!this.impolite){this.stream.send({payloadType:{oneofKind:"join",join:{}}},!0);return}s=!1}try{if(this.makingOffer=!0,this.logger.debug("creating an offer"),await this.pc.setLocalDescription(),!this.pc.localDescription)throw new Error("expect localDescription to be not empty");this.sendSignal({data:{oneofKind:"sdp",sdp:{kind:Rt(this.pc.localDescription.type),sdp:this.pc.localDescription.sdp}}})}catch(i){i instanceof Error&&this.logger.error("failed in negotiating",{err:i})}finally{this.makingOffer=!1}},this.pc.onicecandidate=({candidate:i})=>{this.logger.debug("onicecandidate",{candidate:i});let o={candidate:"",sdpMLineIndex:0,sdpMid:""};if(!i||i.candidate===""){this.logger.debug("ice gathering is finished");return}o.candidate=i.candidate,o.sdpMLineIndex=i.sdpMLineIndex??void 0,o.sdpMid=i.sdpMid??void 0,o.username=i.usernameFragment??void 0,this.sendSignal({data:{oneofKind:"iceCandidate",iceCandidate:o}})},this.pc.ondatachannel=(...i)=>{this.ondatachannel&&this.ondatachannel(...i)},this.pc.ontrack=(...i)=>{this.ontrack&&this.ontrack(...i)}}addTrack(...t){return this.pc.addTrack(...t)}removeTrack(...t){return this.pc.removeTrack(...t)}createDataChannel(...t){return this.pc.createDataChannel(...t)}get connectionState(){return this.pc.connectionState}get closeReason(){return this._closeReason}get otherPeerId(){return this.stream.otherPeerId}get otherConnId(){return this.stream.otherConnId}close(t){if(this.abort.signal.aborted)return;this.abort.abort(t);for(let n of this.timers)clearTimeout(n);this.timers=[],this.stream.close(),this._closeReason=t,this.pc.close();let r=new Event("connectionstatechange");this.setConnectionState("closed",r),this.logger.debug("session closed",{connectionState:this.connectionState})}setConnectionState(t,r){t!==this._connectionState&&this.onconnectionstatechange&&this.onconnectionstatechange(r)}};var Tt=require("@protobuf-ts/runtime-rpc"),C=require("@protobuf-ts/twirp-transport");var bt=require("jwt-decode"),ar="https://cloud.pulsebeam.dev/twirp";var ee=class{constructor(t,r,n,s){this.onsession=t=>{};this.onstatechange=()=>{};this.peerId=n.peerId,this.logger=t.sub("peer",{peerId:this.peerId}),this.sessions=[],this._state="new";let i={bundlePolicy:"balanced",iceTransportPolicy:n.forceRelay?"relay":"all",iceCandidatePoolSize:0,iceServers:n.iceServers};this.transport=new Q(r,{enableDiscovery:!1,groupId:n.groupId,peerId:n.peerId,logger:this.logger,isRecoverable:s}),this.transport.onstream=o=>{let a=new w(o,i);this.sessions.push(a),this.onsession(a)},this.transport.onclosed=()=>{this.close()}}start(){if(this._state==="closed")throw new Error("peer is already closed");this.transport.listen()}async close(){this.sessions=[],await this.transport.close(),this.setState("closed")}connect(t,r,n){return this.transport.connect(t,r,n)}get state(){return this._state}setState(t){t!==this._state&&(this._state=t,this.onstatechange())}},cr=[C.TwirpErrorCode[C.TwirpErrorCode.permission_denied],C.TwirpErrorCode[C.TwirpErrorCode.invalid_argument],C.TwirpErrorCode[C.TwirpErrorCode.aborted],C.TwirpErrorCode[C.TwirpErrorCode.bad_route],C.TwirpErrorCode[C.TwirpErrorCode.malformed],C.TwirpErrorCode[C.TwirpErrorCode.not_found],C.TwirpErrorCode[C.TwirpErrorCode.unauthenticated]];function vt(e){return e instanceof Error?e instanceof Tt.RpcError?!cr.includes(e.code):!0:!1}async function pr(e){let t=e.token,r=new C.TwirpFetchTransport({baseUrl:e.baseUrl||ar,sendJson:!1,jsonOptions:{emitDefaultValues:!0,enumAsInteger:!0,ignoreUnknownFields:!0},interceptors:[{interceptUnary(c,p,u,m){return m.meta||(m.meta={}),m.meta.Authorization=`Bearer ${t}`,c(p,u,m)}}]}),n=new H(r),s=await D(async()=>await n.prepare({}),{baseDelay:50,maxDelay:1e3,maxRetries:5,isRecoverable:vt});if(s===null)throw new Error("createPeer aborted");let i=[...e.iceServers||[]];for(let c of s.response.iceServers)i.push({urls:c.urls,username:c.username,credential:c.credential});let o=(0,bt.jwtDecode)(t),a={...e,iceServers:i,groupId:o.gid,peerId:o.pid};return new ee(new $("pulsebeam",void 0,gt),n,a,vt)}M.disableLog(!1);M.disableWarnings(!1);console.log("UA: ",navigator.userAgent);console.log("webrtc-adapter is enabled",JSON.stringify({shim:M.browserShim,version:M.browserDetails},null,2));0&&(module.exports={Peer,createPeer});
37
37
  //# sourceMappingURL=index.cjs.map