@pulsebeam/peer 0.0.21 → 0.1.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +25 -26
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +728 -2
- package/dist/index.d.ts +728 -2
- package/dist/index.global.js +39 -0
- package/dist/index.js +25 -26
- package/dist/index.js.map +1 -1
- package/dist/peer.d.ts +1 -0
- package/dist/peer.js +5807 -0
- package/dist/peer.umd.cjs +39 -0
- package/package.json +13 -24
package/dist/index.cjs
CHANGED
@@ -1,37 +1,36 @@
|
|
1
|
-
"use strict";var
|
2
|
-
`).map(t=>t.trim())};
|
3
|
-
m=`).map((n
|
4
|
-
`)};
|
5
|
-
`};
|
6
|
-
`};
|
7
|
-
`}return t};
|
8
|
-
`}),t};
|
9
|
-
`;return e.fingerprints.forEach(
|
10
|
-
`}),
|
11
|
-
`};
|
1
|
+
"use strict";var zt=Object.create;var A=Object.defineProperty;var Jt=Object.getOwnPropertyDescriptor;var Ht=Object.getOwnPropertyNames;var Yt=Object.getPrototypeOf,$t=Object.prototype.hasOwnProperty;var Wt=(e,t,r)=>t in e?A(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Xt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),D=(e,t)=>{for(var r in t)A(e,r,{get:t[r],enumerable:!0})},Ct=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ht(t))!$t.call(e,s)&&s!==r&&A(e,s,{get:()=>t[s],enumerable:!(n=Jt(t,s))||n.enumerable});return e};var Rt=(e,t,r)=>(r=e!=null?zt(Yt(e)):{},Ct(t||!e||!e.__esModule?A(r,"default",{value:e,enumerable:!0}):r,e)),Qt=e=>Ct(A({},"__esModule",{value:!0}),e);var m=(e,t,r)=>Wt(e,typeof t!="symbol"?t+"":t,r);var Me=Xt((Hr,Ne)=>{"use strict";var u={};u.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};u.localCName=u.generateIdentifier();u.splitLines=function(e){return e.trim().split(`
|
2
|
+
`).map(t=>t.trim())};u.splitSections=function(e){return e.split(`
|
3
|
+
m=`).map((r,n)=>(n>0?"m="+r:r).trim()+`\r
|
4
|
+
`)};u.getDescription=function(e){let t=u.splitSections(e);return t&&t[0]};u.getMediaSections=function(e){let t=u.splitSections(e);return t.shift(),t};u.matchPrefix=function(e,t){return u.splitLines(e).filter(r=>r.indexOf(t)===0)};u.parseCandidate=function(e){let t;e.indexOf("a=candidate:")===0?t=e.substring(12).split(" "):t=e.substring(10).split(" ");let r={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let n=8;n<t.length;n+=2)switch(t[n]){case"raddr":r.relatedAddress=t[n+1];break;case"rport":r.relatedPort=parseInt(t[n+1],10);break;case"tcptype":r.tcpType=t[n+1];break;case"ufrag":r.ufrag=t[n+1],r.usernameFragment=t[n+1];break;default:r[t[n]]===void 0&&(r[t[n]]=t[n+1]);break}return r};u.writeCandidate=function(e){let t=[];t.push(e.foundation);let r=e.component;r==="rtp"?t.push(1):r==="rtcp"?t.push(2):t.push(r),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let n=e.type;return t.push("typ"),t.push(n),n!=="host"&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&e.protocol.toLowerCase()==="tcp"&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")};u.parseIceOptions=function(e){return e.substring(14).split(" ")};u.parseRtpMap=function(e){let t=e.substring(9).split(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=t.length===3?parseInt(t[2],10):1,r.numChannels=r.channels,r};u.writeRtpMap=function(e){let t=e.payloadType;e.preferredPayloadType!==void 0&&(t=e.preferredPayloadType);let r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(r!==1?"/"+r:"")+`\r
|
5
|
+
`};u.parseExtmap=function(e){let t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}};u.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&e.direction!=="sendrecv"?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+`\r
|
6
|
+
`};u.parseFmtp=function(e){let t={},r,n=e.substring(e.indexOf(" ")+1).split(";");for(let s=0;s<n.length;s++)r=n[s].trim().split("="),t[r[0].trim()]=r[1];return t};u.writeFmtp=function(e){let t="",r=e.payloadType;if(e.preferredPayloadType!==void 0&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){let n=[];Object.keys(e.parameters).forEach(s=>{e.parameters[s]!==void 0?n.push(s+"="+e.parameters[s]):n.push(s)}),t+="a=fmtp:"+r+" "+n.join(";")+`\r
|
7
|
+
`}return t};u.parseRtcpFb=function(e){let t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}};u.writeRtcpFb=function(e){let t="",r=e.payloadType;return e.preferredPayloadType!==void 0&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(n=>{t+="a=rtcp-fb:"+r+" "+n.type+(n.parameter&&n.parameter.length?" "+n.parameter:"")+`\r
|
8
|
+
`}),t};u.parseSsrcMedia=function(e){let t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(r.attribute=e.substring(t+1,n),r.value=e.substring(n+1)):r.attribute=e.substring(t+1),r};u.parseSsrcGroup=function(e){let t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(r=>parseInt(r,10))}};u.getMid=function(e){let t=u.matchPrefix(e,"a=mid:")[0];if(t)return t.substring(6)};u.parseFingerprint=function(e){let t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}};u.getDtlsParameters=function(e,t){return{role:"auto",fingerprints:u.matchPrefix(e+t,"a=fingerprint:").map(u.parseFingerprint)}};u.writeDtlsParameters=function(e,t){let r="a=setup:"+t+`\r
|
9
|
+
`;return e.fingerprints.forEach(n=>{r+="a=fingerprint:"+n.algorithm+" "+n.value+`\r
|
10
|
+
`}),r};u.parseCryptoLine=function(e){let t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}};u.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+(typeof e.keyParams=="object"?u.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+`\r
|
11
|
+
`};u.parseCryptoKeyParams=function(e){if(e.indexOf("inline:")!==0)return null;let t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}};u.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")};u.getCryptoParameters=function(e,t){return u.matchPrefix(e+t,"a=crypto:").map(u.parseCryptoLine)};u.getIceParameters=function(e,t){let r=u.matchPrefix(e+t,"a=ice-ufrag:")[0],n=u.matchPrefix(e+t,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substring(12),password:n.substring(10)}:null};u.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+`\r
|
12
12
|
a=ice-pwd:`+e.password+`\r
|
13
13
|
`;return e.iceLite&&(t+=`a=ice-lite\r
|
14
|
-
`),t};
|
15
|
-
`,
|
16
|
-
`,
|
17
|
-
`,t.codecs.forEach(
|
18
|
-
`),t.headerExtensions&&t.headerExtensions.forEach(
|
14
|
+
`),t};u.parseRtpParameters=function(e){let t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=u.splitLines(e)[0].split(" ");t.profile=n[2];for(let i=3;i<n.length;i++){let a=n[i],o=u.matchPrefix(e,"a=rtpmap:"+a+" ")[0];if(o){let d=u.parseRtpMap(o),c=u.matchPrefix(e,"a=fmtp:"+a+" ");switch(d.parameters=c.length?u.parseFmtp(c[0]):{},d.rtcpFeedback=u.matchPrefix(e,"a=rtcp-fb:"+a+" ").map(u.parseRtcpFb),t.codecs.push(d),d.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(d.name.toUpperCase());break;default:break}}}u.matchPrefix(e,"a=extmap:").forEach(i=>{t.headerExtensions.push(u.parseExtmap(i))});let s=u.matchPrefix(e,"a=rtcp-fb:* ").map(u.parseRtcpFb);return t.codecs.forEach(i=>{s.forEach(a=>{i.rtcpFeedback.find(d=>d.type===a.type&&d.parameter===a.parameter)||i.rtcpFeedback.push(a)})}),t};u.writeRtpDescription=function(e,t){let r="";r+="m="+e+" ",r+=t.codecs.length>0?"9":"0",r+=" "+(t.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=t.codecs.map(s=>s.preferredPayloadType!==void 0?s.preferredPayloadType:s.payloadType).join(" ")+`\r
|
15
|
+
`,r+=`c=IN IP4 0.0.0.0\r
|
16
|
+
`,r+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
17
|
+
`,t.codecs.forEach(s=>{r+=u.writeRtpMap(s),r+=u.writeFmtp(s),r+=u.writeRtcpFb(s)});let n=0;return t.codecs.forEach(s=>{s.maxptime>n&&(n=s.maxptime)}),n>0&&(r+="a=maxptime:"+n+`\r
|
18
|
+
`),t.headerExtensions&&t.headerExtensions.forEach(s=>{r+=u.writeExtmap(s)}),r};u.parseRtpEncodingParameters=function(e){let t=[],r=u.parseRtpParameters(e),n=r.fecMechanisms.indexOf("RED")!==-1,s=r.fecMechanisms.indexOf("ULPFEC")!==-1,i=u.matchPrefix(e,"a=ssrc:").map(p=>u.parseSsrcMedia(p)).filter(p=>p.attribute==="cname"),a=i.length>0&&i[0].ssrc,o,d=u.matchPrefix(e,"a=ssrc-group:FID").map(p=>p.substring(17).split(" ").map(f=>parseInt(f,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(o=d[0][1]),r.codecs.forEach(p=>{if(p.name.toUpperCase()==="RTX"&&p.parameters.apt){let h={ssrc:a,codecPayloadType:parseInt(p.parameters.apt,10)};a&&o&&(h.rtx={ssrc:o}),t.push(h),n&&(h=JSON.parse(JSON.stringify(h)),h.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},t.push(h))}}),t.length===0&&a&&t.push({ssrc:a});let c=u.matchPrefix(e,"b=");return c.length&&(c[0].indexOf("b=TIAS:")===0?c=parseInt(c[0].substring(7),10):c[0].indexOf("b=AS:")===0?c=parseInt(c[0].substring(5),10)*1e3*.95-50*40*8:c=void 0,t.forEach(p=>{p.maxBitrate=c})),t};u.parseRtcpParameters=function(e){let t={},r=u.matchPrefix(e,"a=ssrc:").map(i=>u.parseSsrcMedia(i)).filter(i=>i.attribute==="cname")[0];r&&(t.cname=r.value,t.ssrc=r.ssrc);let n=u.matchPrefix(e,"a=rtcp-rsize");t.reducedSize=n.length>0,t.compound=n.length===0;let s=u.matchPrefix(e,"a=rtcp-mux");return t.mux=s.length>0,t};u.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+=`a=rtcp-rsize\r
|
19
19
|
`),e.mux&&(t+=`a=rtcp-mux\r
|
20
20
|
`),e.ssrc!==void 0&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+`\r
|
21
|
-
`),t};
|
21
|
+
`),t};u.parseMsid=function(e){let t,r=u.matchPrefix(e,"a=msid:");if(r.length===1)return t=r[0].substring(7).split(" "),{stream:t[0],track:t[1]};let n=u.matchPrefix(e,"a=ssrc:").map(s=>u.parseSsrcMedia(s)).filter(s=>s.attribute==="msid");if(n.length>0)return t=n[0].value.split(" "),{stream:t[0],track:t[1]}};u.parseSctpDescription=function(e){let t=u.parseMLine(e),r=u.matchPrefix(e,"a=max-message-size:"),n;r.length>0&&(n=parseInt(r[0].substring(19),10)),isNaN(n)&&(n=65536);let s=u.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:t.fmt,maxMessageSize:n};let i=u.matchPrefix(e,"a=sctpmap:");if(i.length>0){let a=i[0].substring(10).split(" ");return{port:parseInt(a[0],10),protocol:a[1],maxMessageSize:n}}};u.writeSctpDescription=function(e,t){let r=[];return e.protocol!=="DTLS/SCTP"?r=["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+`\r
|
22
22
|
`,`c=IN IP4 0.0.0.0\r
|
23
23
|
`,"a=sctp-port:"+t.port+`\r
|
24
|
-
`]:
|
24
|
+
`]:r=["m="+e.kind+" 9 "+e.protocol+" "+t.port+`\r
|
25
25
|
`,`c=IN IP4 0.0.0.0\r
|
26
26
|
`,"a=sctpmap:"+t.port+" "+t.protocol+` 65535\r
|
27
|
-
`],t.maxMessageSize!==void 0&&
|
28
|
-
`),
|
29
|
-
o=`+(
|
27
|
+
`],t.maxMessageSize!==void 0&&r.push("a=max-message-size:"+t.maxMessageSize+`\r
|
28
|
+
`),r.join("")};u.generateSessionId=function(){return Math.random().toString().substr(2,22)};u.writeSessionBoilerplate=function(e,t,r){let n,s=t!==void 0?t:2;return e?n=e:n=u.generateSessionId(),`v=0\r
|
29
|
+
o=`+(r||"thisisadapterortc")+" "+n+" "+s+` IN IP4 127.0.0.1\r
|
30
30
|
s=-\r
|
31
31
|
t=0 0\r
|
32
|
-
`};l.getDirection=function(e,t){let n=l.splitLines(e);for(let r=0;r<n.length;r++)switch(n[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[r].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 n=l.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}};l.parseOLine=function(e){let n=l.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}};l.isValidSDP=function(e){if(typeof e!="string"||e.length===0)return!1;let t=l.splitLines(e);for(let n=0;n<t.length;n++)if(t[n].length<2||t[n].charAt(1)!=="=")return!1;return!0};typeof xe=="object"&&(xe.exports=l)});var ur={};b(ur,{Peer:()=>$,createPeer:()=>lr});module.exports=At(ur);var ot=!0,at=!0;function P(e,t,n){let r=e.match(t);return r&&r.length>=n&&parseInt(r[n],10)}function S(e,t,n){if(!e.RTCPeerConnection)return;let r=e.RTCPeerConnection.prototype,i=r.addEventListener;r.addEventListener=function(a,o){if(a!==t)return i.apply(this,arguments);let d=c=>{let p=n(c);p&&(o.handleEvent?o.handleEvent(p):o(p))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(o,d),i.apply(this,[a,d])};let s=r.removeEventListener;r.removeEventListener=function(a,o){if(a!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(o))return s.apply(this,arguments);let d=this._eventMap[t].get(o);return this._eventMap[t].delete(o),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[a,d])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(a){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),a&&this.addEventListener(t,this["_on"+t]=a)},enumerable:!0,configurable:!0})}function ct(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(ot=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function pt(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(at=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function L(){if(typeof window=="object"){if(ot)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function v(e,t){at&&console.warn(e+" is deprecated, please use "+t+" instead.")}function dt(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:n}=e;if(n.userAgentData&&n.userAgentData.brands){let r=n.userAgentData.brands.find(i=>i.brand==="Chromium");if(r)return{browser:"chrome",version:parseInt(r.version,10)}}if(n.mozGetUserMedia)t.browser="firefox",t.version=P(n.userAgent,/Firefox\/(\d+)\./,1);else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=P(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser="safari",t.version=P(n.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 st(e){return Object.prototype.toString.call(e)==="[object Object]"}function ee(e){return st(e)?Object.keys(e).reduce(function(t,n){let r=st(e[n]),i=r?ee(e[n]):e[n],s=r&&!Object.keys(i).length;return i===void 0||s?t:Object.assign(t,{[n]:i})},{}):e}function w(e,t,n){!t||n.has(t.id)||(n.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith("Id")?w(e,e.get(t[r]),n):r.endsWith("Ids")&&t[r].forEach(i=>{w(e,e.get(i),n)})}))}function te(e,t,n){let r=n?"outbound-rtp":"inbound-rtp",i=new Map;if(t===null)return i;let s=[];return e.forEach(a=>{a.type==="track"&&a.trackIdentifier===t.id&&s.push(a)}),s.forEach(a=>{e.forEach(o=>{o.type===r&&o.trackId===a.id&&w(e,o,i)})}),i}var U={};b(U,{fixNegotiationNeeded:()=>ae,shimAddTrackRemoveTrack:()=>oe,shimAddTrackRemoveTrackWithNative:()=>ut,shimGetSendersWithDtmf:()=>ie,shimGetUserMedia:()=>A,shimMediaStream:()=>re,shimOnTrack:()=>ne,shimPeerConnection:()=>j,shimSenderReceiverGetStats:()=>se});var lt=L;function A(e,t){let n=e&&e.navigator;if(!n.mediaDevices)return;let r=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;let d={};return Object.keys(o).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;let p=typeof o[c]=="object"?o[c]:{ideal:o[c]};p.exact!==void 0&&typeof p.exact=="number"&&(p.min=p.max=p.exact);let u=function(m,f){return m?m+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};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])})}),o.advanced&&(d.optional=(d.optional||[]).concat(o.advanced)),d},i=function(o,d){if(t.version>=61)return d(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){let c=function(p,u,m){u in p&&!(m in p)&&(p[m]=p[u],delete p[u])};o=JSON.parse(JSON.stringify(o)),c(o.audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=r(o.audio)}if(o&&typeof o.video=="object"){let c=o.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")&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!p)){delete o.video.facingMode;let u;if(c.exact==="environment"||c.ideal==="environment"?u=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(u=["front"]),u)return n.mediaDevices.enumerateDevices().then(m=>{m=m.filter(g=>g.kind==="videoinput");let f=m.find(g=>u.some(C=>g.label.toLowerCase().includes(C)));return!f&&m.length&&u.includes("back")&&(f=m[m.length-1]),f&&(o.video.deviceId=c.exact?{exact:f.deviceId}:{ideal:f.deviceId}),o.video=r(o.video),lt("chrome: "+JSON.stringify(o)),d(o)})}o.video=r(o.video)}return lt("chrome: "+JSON.stringify(o)),d(o)},s=function(o){return t.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,d,c){i(o,p=>{n.webkitGetUserMedia(p,d,u=>{c&&c(s(u))})})};if(n.getUserMedia=a.bind(n),n.mediaDevices.getUserMedia){let o=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(d){return i(d,c=>o(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(s(p))))}}}function re(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function ne(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(n){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=n)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=r=>{r.stream.addEventListener("addtrack",i=>{let s;e.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===i.track.id):s={track:i.track};let a=new Event("track");a.track=i.track,a.receiver=s,a.transceiver={receiver:s},a.streams=[r.stream],this.dispatchEvent(a)}),r.stream.getTracks().forEach(i=>{let s;e.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===i.id):s={track:i};let a=new Event("track");a.track=i,a.receiver=s,a.transceiver={receiver:s},a.streams=[r.stream],this.dispatchEvent(a)})},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 ie(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){let t=function(i,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=i.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:i}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(o,d){let c=i.apply(this,arguments);return c||(c=t(this,o),this._senders.push(c)),c};let s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);let d=this._senders.indexOf(o);d!==-1&&this._senders.splice(d,1)}}let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],n.apply(this,[s]),s.getTracks().forEach(a=>{this._senders.push(t(this,a))})};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],r.apply(this,[s]),s.getTracks().forEach(a=>{let o=this._senders.find(d=>d.track===a);o&&this._senders.splice(this._senders.indexOf(o),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 r=t.apply(this,[]);return r.forEach(i=>i._pc=this),r},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 se(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){let n=e.RTCPeerConnection.prototype.getSenders;n&&(e.RTCPeerConnection.prototype.getSenders=function(){let s=n.apply(this,[]);return s.forEach(a=>a._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(){let s=this;return this._pc.getStats().then(a=>te(a,s.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){let n=e.RTCPeerConnection.prototype.getReceivers;n&&(e.RTCPeerConnection.prototype.getReceivers=function(){let i=n.apply(this,[]);return i.forEach(s=>s._pc=this),i}),S(e,"track",r=>(r.receiver._pc=r.srcElement,r)),e.RTCRtpReceiver.prototype.getStats=function(){let i=this;return this._pc.getStats().then(s=>te(s,i.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 r=arguments[0],i,s,a;return this.getSenders().forEach(o=>{o.track===r&&(i?a=!0:i=o)}),this.getReceivers().forEach(o=>(o.track===r&&(s?a=!0:s=o),o.track===r)),a||i&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ut(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let d=t.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(d)===-1&&this._shimmedLocalStreams[o.id].push(d):this._shimmedLocalStreams[o.id]=[o,d],d};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(c=>{if(this.getSenders().find(u=>u.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});let o=this.getSenders();n.apply(this,arguments);let d=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(d)};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],r.apply(this,arguments)};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{let d=this._shimmedLocalStreams[o].indexOf(a);d!==-1&&this._shimmedLocalStreams[o].splice(d,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),i.apply(this,arguments)}}function oe(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ut(e);let n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let p=n.apply(this);return this._reverseStreams=this._reverseStreams||{},p.map(u=>this._reverseStreams[u.id])};let r=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(f=>f.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}r.apply(this,[p])};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(p){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.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(C=>C===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(C=>C.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 C=new e.MediaStream([p]);this._streams[u.id]=C,this._reverseStreams[C.id]=u,this.addStream(C)}return this.getSenders().find(C=>C.track===p)};function s(c,p){let u=p.sdp;return Object.keys(c._reverseStreams||[]).forEach(m=>{let f=c._reverseStreams[m],g=c._streams[f.id];u=u.replace(new RegExp(g.id,"g"),f.id)}),new RTCSessionDescription({type:p.type,sdp:u})}function a(c,p){let u=p.sdp;return Object.keys(c._reverseStreams||[]).forEach(m=>{let f=c._reverseStreams[m],g=c._streams[f.id];u=u.replace(new RegExp(f.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 C=s(this,g);m[0].apply(null,[C])},g=>{m[1]&&m[1].apply(null,g)},arguments[2]]):p.apply(this,arguments).then(g=>s(this,g))}};e.RTCPeerConnection.prototype[c]=u[c]});let o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.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:s(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(f=>{this._streams[f].getTracks().find(C=>p.track===C)&&(m=this._streams[f])}),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(n){let r=e.RTCPeerConnection.prototype[n],i={[n](){return arguments[0]=new(n==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[n]=i[n]})}function ae(e,t){S(e,"negotiationneeded",n=>{let r=n.target;if(!((t.version<72||r.getConfiguration&&r.getConfiguration().sdpSemantics==="plan-b")&&r.signalingState!=="stable"))return n})}var G={};b(G,{shimAddTransceiver:()=>me,shimCreateAnswer:()=>ge,shimCreateOffer:()=>he,shimGetDisplayMedia:()=>mt,shimGetParameters:()=>fe,shimGetUserMedia:()=>F,shimOnTrack:()=>ce,shimPeerConnection:()=>N,shimRTCDataChannel:()=>ue,shimReceiverGetStats:()=>de,shimRemoveStream:()=>le,shimSenderGetStats:()=>pe});function F(e,t){let n=e&&e.navigator,r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(i,s,a){v("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(i).then(s,a)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){let i=function(a,o,d){o in a&&!(d in a)&&(a[d]=a[o],delete a[o])},s=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),i(a.audio,"autoGainControl","mozAutoGainControl"),i(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},r&&r.prototype.getSettings){let a=r.prototype.getSettings;r.prototype.getSettings=function(){let o=a.apply(this,arguments);return i(o,"mozAutoGainControl","autoGainControl"),i(o,"mozNoiseSuppression","noiseSuppression"),o}}if(r&&r.prototype.applyConstraints){let a=r.prototype.applyConstraints;r.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),i(o,"autoGainControl","mozAutoGainControl"),i(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function mt(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!(r&&r.video)){let i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,Promise.reject(i)}return r.video===!0?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}function ce(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(i){let s=e.RTCPeerConnection.prototype[i],a={[i](){return arguments[0]=new(i==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};e.RTCPeerConnection.prototype[i]=a[i]});let n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[s,a,o]=arguments;return r.apply(this,[s||null]).then(d=>{if(t.version<53&&!a)try{d.forEach(c=>{c.type=n[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;d.forEach((p,u)=>{d.set(u,Object.assign({},p,{type:n[p.type]||p.type}))})}return d}).then(a,o)}}function pe(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 i=t.apply(this,[]);return i.forEach(s=>s._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(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function de(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 r=t.apply(this,[]);return r.forEach(i=>i._pc=this),r}),S(e,"track",n=>(n.receiver._pc=n.srcElement,n)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function le(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(n){v("removeStream","removeTrack"),this.getSenders().forEach(r=>{r.track&&n.getTracks().includes(r.track)&&this.removeTrack(r)})})}function ue(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function me(e){if(!(typeof e=="object"&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let r=arguments[1]&&arguments[1].sendEncodings;r===void 0&&(r=[]),r=[...r];let i=r.length>0;i&&r.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});let s=t.apply(this,arguments);if(i){let{sender:a}=s,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=r,a.sendEncodings=r,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function fe(e){if(!(typeof e=="object"&&e.RTCRtpSender))return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let r=t.apply(this,arguments);return"encodings"in r||(r.encodings=[].concat(this.sendEncodings||[{}])),r})}function he(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 ge(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 q={};b(q,{shimAudioContext:()=>Pe,shimCallbacksAPI:()=>Se,shimConstraints:()=>ft,shimCreateOfferLegacy:()=>be,shimGetUserMedia:()=>Re,shimLocalStreamsAPI:()=>Ce,shimRTCIceServerUrls:()=>ve,shimRemoteStreamsAPI:()=>ye,shimTrackEventTransceiver:()=>Te});function Ce(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(r){this._localStreams||(this._localStreams=[]),this._localStreams.includes(r)||this._localStreams.push(r),r.getAudioTracks().forEach(i=>t.call(this,i,r)),r.getVideoTracks().forEach(i=>t.call(this,i,r))},e.RTCPeerConnection.prototype.addTrack=function(r,...i){return i&&i.forEach(s=>{this._localStreams?this._localStreams.includes(s)||this._localStreams.push(s):this._localStreams=[s]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(n){this._localStreams||(this._localStreams=[]);let r=this._localStreams.indexOf(n);if(r===-1)return;this._localStreams.splice(r,1);let i=n.getTracks();this.getSenders().forEach(s=>{i.includes(s.track)&&this.removeTrack(s)})})}}function ye(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(n){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=n),this.addEventListener("track",this._onaddstreampoly=r=>{r.streams.forEach(i=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(i))return;this._remoteStreams.push(i);let s=new Event("addstream");s.stream=i,this.dispatchEvent(s)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let r=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(i){i.streams.forEach(s=>{if(r._remoteStreams||(r._remoteStreams=[]),r._remoteStreams.indexOf(s)>=0)return;r._remoteStreams.push(s);let a=new Event("addstream");a.stream=s,r.dispatchEvent(a)})}),t.apply(r,arguments)}}}function Se(e){if(typeof e!="object"||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,n=t.createOffer,r=t.createAnswer,i=t.setLocalDescription,s=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=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},t.createAnswer=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};let o=function(d,c,p){let u=i.apply(this,[d]);return p?(u.then(c,p),Promise.resolve()):u};t.setLocalDescription=o,o=function(d,c,p){let u=s.apply(this,[d]);return p?(u.then(c,p),Promise.resolve()):u},t.setRemoteDescription=o,o=function(d,c,p){let u=a.apply(this,[d]);return p?(u.then(c,p),Promise.resolve()):u},t.addIceCandidate=o}function Re(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let n=t.mediaDevices,r=n.getUserMedia.bind(n);t.mediaDevices.getUserMedia=i=>r(ft(i))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(r,i,s){t.mediaDevices.getUserMedia(r).then(i,s)}.bind(t))}function ft(e){return e&&e.video!==void 0?Object.assign({},e,{video:ee(e.video)}):e}function ve(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(r,i){if(r&&r.iceServers){let s=[];for(let a=0;a<r.iceServers.length;a++){let o=r.iceServers[a];o.urls===void 0&&o.url?(v("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(r.iceServers[a])}r.iceServers=s}return new t(r,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get(){return t.generateCertificate}})}function Te(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 be(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(r){if(r){typeof r.offerToReceiveAudio<"u"&&(r.offerToReceiveAudio=!!r.offerToReceiveAudio);let i=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");r.offerToReceiveAudio===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):r.offerToReceiveAudio===!0&&!i&&this.addTransceiver("audio",{direction:"recvonly"}),typeof r.offerToReceiveVideo<"u"&&(r.offerToReceiveVideo=!!r.offerToReceiveVideo);let s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");r.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):r.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Pe(e){typeof e!="object"||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Ie={};b(Ie,{removeExtmapAllowMixed:()=>K,shimAddIceCandidateNullOrEmpty:()=>E,shimConnectionState:()=>B,shimMaxMessageSize:()=>k,shimParameterlessSetLocalDescription:()=>_,shimRTCIceCandidate:()=>x,shimRTCIceCandidateRelayProtocol:()=>z,shimSendThrowTypeError:()=>I});var T=it(ke());function x(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(r){if(typeof r=="object"&&r.candidate&&r.candidate.indexOf("a=")===0&&(r=JSON.parse(JSON.stringify(r)),r.candidate=r.candidate.substring(2)),r.candidate&&r.candidate.length){let i=new t(r),s=T.default.parseCandidate(r.candidate);for(let a in s)a in i||Object.defineProperty(i,a,{value:s[a]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(r)},e.RTCIceCandidate.prototype=t.prototype,S(e,"icecandidate",n=>(n.candidate&&Object.defineProperty(n,"candidate",{value:new e.RTCIceCandidate(n.candidate),writable:"false"}),n))}function z(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||S(e,"icecandidate",t=>{if(t.candidate){let n=T.default.parseCandidate(t.candidate.candidate);n.type==="relay"&&(t.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[n.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 n=function(o){if(!o||!o.sdp)return!1;let d=T.default.splitSections(o.sdp);return d.shift(),d.some(c=>{let p=T.default.parseMLine(c);return p&&p.kind==="application"&&p.protocol.indexOf("SCTP")!==-1})},r=function(o){let d=o.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},i=function(o){let d=65536;return t.browser==="firefox"&&(t.version<57?o===-1?d=16384:d=2147483637:t.version<60?d=t.version===57?65535:65536:d=2147483637),d},s=function(o,d){let c=65536;t.browser==="firefox"&&t.version===57&&(c=65535);let p=T.default.matchPrefix(o.sdp,"a=max-message-size:");return p.length>0?c=parseInt(p[0].substring(19),10):t.browser==="firefox"&&d!==-1&&(c=2147483637),c},a=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(n(arguments[0])){let d=r(arguments[0]),c=i(d),p=s(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 a.apply(this,arguments)}}function I(e){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype))return;function t(r,i){let s=r.send;r.send=function(){let o=arguments[0],d=o.length||o.size||o.byteLength;if(r.readyState==="open"&&i.sctp&&d>i.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+i.sctp.maxMessageSize+" bytes)");return s.apply(r,arguments)}}let n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let i=n.apply(this,arguments);return t(i,this),i},S(e,"datachannel",r=>(t(r.channel,r.target),r))}function B(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(n){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),n&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=n)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(n=>{let r=t[n];t[n]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=i=>{let s=i.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;let a=new Event("connectionstatechange",i);s.dispatchEvent(a)}return i},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}function K(e,t){if(!e.RTCPeerConnection||t.browser==="chrome"&&t.version>=71||t.browser==="safari"&&t.version>=605)return;let n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(i){if(i&&i.sdp&&i.sdp.indexOf(`
|
33
|
-
a=extmap-allow-mixed`)!==-1){let s
|
32
|
+
`};u.getDirection=function(e,t){let r=u.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?u.getDirection(t):"sendrecv"};u.getKind=function(e){return u.splitLines(e)[0].split(" ")[0].substring(2)};u.isRejected=function(e){return e.split(" ",2)[1]==="0"};u.parseMLine=function(e){let r=u.splitLines(e)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}};u.parseOLine=function(e){let r=u.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]}};u.isValidSDP=function(e){if(typeof e!="string"||e.length===0)return!1;let t=u.splitLines(e);for(let r=0;r<t.length;r++)if(t[r].length<2||t[r].charAt(1)!=="=")return!1;return!0};typeof Ne=="object"&&(Ne.exports=u)});var jr={};D(jr,{Peer:()=>ie,PeerStore:()=>gt,createPeer:()=>Vr});module.exports=Qt(jr);var yt=!0,Tt=!0;function x(e,t,r){let n=e.match(t);return n&&n.length>=r&&parseInt(n[r],10)}function T(e,t,r){if(!e.RTCPeerConnection)return;let n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(a,o){if(a!==t)return s.apply(this,arguments);let d=c=>{let p=r(c);p&&(o.handleEvent?o.handleEvent(p):o(p))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(o,d),s.apply(this,[a,d])};let i=n.removeEventListener;n.removeEventListener=function(a,o){if(a!==t||!this._eventMap||!this._eventMap[t])return i.apply(this,arguments);if(!this._eventMap[t].has(o))return i.apply(this,arguments);let d=this._eventMap[t].get(o);return this._eventMap[t].delete(o),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,i.apply(this,[a,d])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(a){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),a&&this.addEventListener(t,this["_on"+t]=a)},enumerable:!0,configurable:!0})}function _t(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(yt=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Et(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(Tt=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function K(){if(typeof window=="object"){if(yt)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function v(e,t){Tt&&console.warn(e+" is deprecated, please use "+t+" instead.")}function vt(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=x(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=x(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(e.RTCPeerConnection&&r.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser="safari",t.version=x(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 St(e){return Object.prototype.toString.call(e)==="[object Object]"}function ce(e){return St(e)?Object.keys(e).reduce(function(t,r){let n=St(e[r]),s=n?ce(e[r]):e[r],i=n&&!Object.keys(s).length;return s===void 0||i?t:Object.assign(t,{[r]:s})},{}):e}function ae(e,t,r){!t||r.has(t.id)||(r.set(t.id,t),Object.keys(t).forEach(n=>{n.endsWith("Id")?ae(e,e.get(t[n]),r):n.endsWith("Ids")&&t[n].forEach(s=>{ae(e,e.get(s),r)})}))}function pe(e,t,r){let n=r?"outbound-rtp":"inbound-rtp",s=new Map;if(t===null)return s;let i=[];return e.forEach(a=>{a.type==="track"&&a.trackIdentifier===t.id&&i.push(a)}),i.forEach(a=>{e.forEach(o=>{o.type===n&&o.trackId===a.id&&ae(e,o,s)})}),s}var z={};D(z,{fixNegotiationNeeded:()=>fe,shimAddTrackRemoveTrack:()=>he,shimAddTrackRemoveTrackWithNative:()=>Pt,shimGetSendersWithDtmf:()=>ue,shimGetUserMedia:()=>q,shimMediaStream:()=>de,shimOnTrack:()=>le,shimPeerConnection:()=>B,shimSenderReceiverGetStats:()=>me});var bt=K;function q(e,t){let r=e&&e.navigator;if(!r.mediaDevices)return;let n=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;let d={};return Object.keys(o).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;let p=typeof o[c]=="object"?o[c]:{ideal:o[c]};p.exact!==void 0&&typeof p.exact=="number"&&(p.min=p.max=p.exact);let h=function(f,g){return f?f+g.charAt(0).toUpperCase()+g.slice(1):g==="deviceId"?"sourceId":g};if(p.ideal!==void 0){d.optional=d.optional||[];let f={};typeof p.ideal=="number"?(f[h("min",c)]=p.ideal,d.optional.push(f),f={},f[h("max",c)]=p.ideal,d.optional.push(f)):(f[h("",c)]=p.ideal,d.optional.push(f))}p.exact!==void 0&&typeof p.exact!="number"?(d.mandatory=d.mandatory||{},d.mandatory[h("",c)]=p.exact):["min","max"].forEach(f=>{p[f]!==void 0&&(d.mandatory=d.mandatory||{},d.mandatory[h(f,c)]=p[f])})}),o.advanced&&(d.optional=(d.optional||[]).concat(o.advanced)),d},s=function(o,d){if(t.version>=61)return d(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){let c=function(p,h,f){h in p&&!(f in p)&&(p[f]=p[h],delete p[h])};o=JSON.parse(JSON.stringify(o)),c(o.audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=n(o.audio)}if(o&&typeof o.video=="object"){let c=o.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 o.video.facingMode;let h;if(c.exact==="environment"||c.ideal==="environment"?h=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(h=["front"]),h)return r.mediaDevices.enumerateDevices().then(f=>{f=f.filter(R=>R.kind==="videoinput");let g=f.find(R=>h.some(S=>R.label.toLowerCase().includes(S)));return!g&&f.length&&h.includes("back")&&(g=f[f.length-1]),g&&(o.video.deviceId=c.exact?{exact:g.deviceId}:{ideal:g.deviceId}),o.video=n(o.video),bt("chrome: "+JSON.stringify(o)),d(o)})}o.video=n(o.video)}return bt("chrome: "+JSON.stringify(o)),d(o)},i=function(o){return t.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,d,c){s(o,p=>{r.webkitGetUserMedia(p,d,h=>{c&&c(i(h))})})};if(r.getUserMedia=a.bind(r),r.mediaDevices.getUserMedia){let o=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(d){return s(d,c=>o(c).then(p=>{if(c.audio&&!p.getAudioTracks().length||c.video&&!p.getVideoTracks().length)throw p.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return p},p=>Promise.reject(i(p))))}}}function de(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function le(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(o=>o.track&&o.track.id===s.track.id):i={track:s.track};let a=new Event("track");a.track=s.track,a.receiver=i,a.transceiver={receiver:i},a.streams=[n.stream],this.dispatchEvent(a)}),n.stream.getTracks().forEach(s=>{let i;e.RTCPeerConnection.prototype.getReceivers?i=this.getReceivers().find(o=>o.track&&o.track.id===s.id):i={track:s};let a=new Event("track");a.track=s,a.receiver=i,a.transceiver={receiver:i},a.streams=[n.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else T(e,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function ue(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(o,d){let c=s.apply(this,arguments);return c||(c=t(this,o),this._senders.push(c)),c};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(o){i.apply(this,arguments);let d=this._senders.indexOf(o);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(a=>{this._senders.push(t(this,a))})};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(i){this._senders=this._senders||[],n.apply(this,[i]),i.getTracks().forEach(a=>{let o=this._senders.find(d=>d.track===a);o&&this._senders.splice(this._senders.indexOf(o),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 me(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(a=>a._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(a=>pe(a,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}),T(e,"track",n=>(n.receiver._pc=n.srcElement,n)),e.RTCRtpReceiver.prototype.getStats=function(){let s=this;return this._pc.getStats().then(i=>pe(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,a;return this.getSenders().forEach(o=>{o.track===n&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===n&&(i?a=!0:i=o),o.track===n)),a||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 Pt(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let d=t.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(d)===-1&&this._shimmedLocalStreams[o.id].push(d):this._shimmedLocalStreams[o.id]=[o,d],d};let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(c=>{if(this.getSenders().find(h=>h.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});let o=this.getSenders();r.apply(this,arguments);let d=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(d)};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],n.apply(this,arguments)};let s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{let d=this._shimmedLocalStreams[o].indexOf(a);d!==-1&&this._shimmedLocalStreams[o].splice(d,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function he(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Pt(e);let r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let p=r.apply(this);return this._reverseStreams=this._reverseStreams||{},p.map(h=>this._reverseStreams[h.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(h=>{if(this.getSenders().find(g=>g.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[p.id]){let h=new e.MediaStream(p.getTracks());this._streams[p.id]=h,this._reverseStreams[h.id]=p,p=h}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,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let f=[].slice.call(arguments,1);if(f.length!==1||!f[0].getTracks().find(S=>S===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(S=>S.track===p))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let R=this._streams[h.id];if(R)R.addTrack(p),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let S=new e.MediaStream([p]);this._streams[h.id]=S,this._reverseStreams[S.id]=h,this.addStream(S)}return this.getSenders().find(S=>S.track===p)};function i(c,p){let h=p.sdp;return Object.keys(c._reverseStreams||[]).forEach(f=>{let g=c._reverseStreams[f],R=c._streams[g.id];h=h.replace(new RegExp(R.id,"g"),g.id)}),new RTCSessionDescription({type:p.type,sdp:h})}function a(c,p){let h=p.sdp;return Object.keys(c._reverseStreams||[]).forEach(f=>{let g=c._reverseStreams[f],R=c._streams[g.id];h=h.replace(new RegExp(g.id,"g"),R.id)}),new RTCSessionDescription({type:p.type,sdp:h})}["createOffer","createAnswer"].forEach(function(c){let p=e.RTCPeerConnection.prototype[c],h={[c](){let f=arguments;return arguments.length&&typeof arguments[0]=="function"?p.apply(this,[R=>{let S=i(this,R);f[0].apply(null,[S])},R=>{f[1]&&f[1].apply(null,R)},arguments[2]]):p.apply(this,arguments).then(R=>i(this,R))}};e.RTCPeerConnection.prototype[c]=h[c]});let o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.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 f;Object.keys(this._streams).forEach(g=>{this._streams[g].getTracks().find(S=>p.track===S)&&(f=this._streams[g])}),f&&(f.getTracks().length===1?this.removeStream(this._reverseStreams[f.id]):f.removeTrack(p.track),this.dispatchEvent(new Event("negotiationneeded")))}}function B(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 fe(e,t){T(e,"negotiationneeded",r=>{let n=r.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return r})}var Y={};D(Y,{shimAddTransceiver:()=>Te,shimCreateAnswer:()=>ve,shimCreateOffer:()=>Ee,shimGetDisplayMedia:()=>It,shimGetParameters:()=>_e,shimGetUserMedia:()=>J,shimOnTrack:()=>ge,shimPeerConnection:()=>H,shimRTCDataChannel:()=>ye,shimReceiverGetStats:()=>Re,shimRemoveStream:()=>Se,shimSenderGetStats:()=>Ce});function J(e,t){let r=e&&e.navigator,n=e&&e.MediaStreamTrack;if(r.getUserMedia=function(s,i,a){v("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(s).then(i,a)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){let s=function(a,o,d){o in a&&!(d in a)&&(a[d]=a[o],delete a[o])},i=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),i(a)},n&&n.prototype.getSettings){let a=n.prototype.getSettings;n.prototype.getSettings=function(){let o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(n&&n.prototype.applyConstraints){let a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function It(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 ge(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 H(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],a={[s](){return arguments[0]=new(s==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[s]=a[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,a,o]=arguments;return n.apply(this,[i||null]).then(d=>{if(t.version<53&&!a)try{d.forEach(c=>{c.type=r[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;d.forEach((p,h)=>{d.set(h,Object.assign({},p,{type:r[p.type]||p.type}))})}return d}).then(a,o)}}function Ce(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 Re(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}),T(e,"track",r=>(r.receiver._pc=r.srcElement,r)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Se(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 ye(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Te(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(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});let i=t.apply(this,arguments);if(s){let{sender:a}=i,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return i})}function _e(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 Ee(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 ve(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 $={};D($,{shimAudioContext:()=>Oe,shimCallbacksAPI:()=>Ie,shimConstraints:()=>At,shimCreateOfferLegacy:()=>ke,shimGetUserMedia:()=>Ae,shimLocalStreamsAPI:()=>be,shimRTCIceServerUrls:()=>De,shimRemoteStreamsAPI:()=>Pe,shimTrackEventTransceiver:()=>xe});function be(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 Pe(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 a=new Event("addstream");a.stream=i,n.dispatchEvent(a)})}),t.apply(n,arguments)}}}function Ie(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,a=t.addIceCandidate;t.createOffer=function(c,p){let h=arguments.length>=2?arguments[2]:arguments[0],f=r.apply(this,[h]);return p?(f.then(c,p),Promise.resolve()):f},t.createAnswer=function(c,p){let h=arguments.length>=2?arguments[2]:arguments[0],f=n.apply(this,[h]);return p?(f.then(c,p),Promise.resolve()):f};let o=function(d,c,p){let h=s.apply(this,[d]);return p?(h.then(c,p),Promise.resolve()):h};t.setLocalDescription=o,o=function(d,c,p){let h=i.apply(this,[d]);return p?(h.then(c,p),Promise.resolve()):h},t.setRemoteDescription=o,o=function(d,c,p){let h=a.apply(this,[d]);return p?(h.then(c,p),Promise.resolve()):h},t.addIceCandidate=o}function Ae(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(At(s))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(n,s,i){t.mediaDevices.getUserMedia(n).then(s,i)}.bind(t))}function At(e){return e&&e.video!==void 0?Object.assign({},e,{video:ce(e.video)}):e}function De(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(n,s){if(n&&n.iceServers){let i=[];for(let a=0;a<n.iceServers.length;a++){let o=n.iceServers[a];o.urls===void 0&&o.url?(v("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,i.push(o)):i.push(n.iceServers[a])}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 xe(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 ke(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(a=>a.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(a=>a.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 Oe(e){typeof e!="object"||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Le={};D(Le,{removeExtmapAllowMixed:()=>Q,shimAddIceCandidateNullOrEmpty:()=>M,shimConnectionState:()=>X,shimMaxMessageSize:()=>O,shimParameterlessSetLocalDescription:()=>L,shimRTCIceCandidate:()=>k,shimRTCIceCandidateRelayProtocol:()=>W,shimSendThrowTypeError:()=>N});var b=Rt(Me());function k(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=b.default.parseCandidate(n.candidate);for(let a in i)a in s||Object.defineProperty(s,a,{value:i[a]});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,T(e,"icecandidate",r=>(r.candidate&&Object.defineProperty(r,"candidate",{value:new e.RTCIceCandidate(r.candidate),writable:"false"}),r))}function W(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||T(e,"icecandidate",t=>{if(t.candidate){let r=b.default.parseCandidate(t.candidate.candidate);r.type==="relay"&&(t.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[r.priority>>24])}return t})}function O(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(o){if(!o||!o.sdp)return!1;let d=b.default.splitSections(o.sdp);return d.shift(),d.some(c=>{let p=b.default.parseMLine(c);return p&&p.kind==="application"&&p.protocol.indexOf("SCTP")!==-1})},n=function(o){let d=o.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(o){let d=65536;return t.browser==="firefox"&&(t.version<57?o===-1?d=16384:d=2147483637:t.version<60?d=t.version===57?65535:65536:d=2147483637),d},i=function(o,d){let c=65536;t.browser==="firefox"&&t.version===57&&(c=65535);let p=b.default.matchPrefix(o.sdp,"a=max-message-size:");return p.length>0?c=parseInt(p[0].substring(19),10):t.browser==="firefox"&&d!==-1&&(c=2147483637),c},a=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),h;c===0&&p===0?h=Number.POSITIVE_INFINITY:c===0||p===0?h=Math.max(c,p):h=Math.min(c,p);let f={};Object.defineProperty(f,"maxMessageSize",{get(){return h}}),this._sctp=f}return a.apply(this,arguments)}}function N(e){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype))return;function t(n,s){let i=n.send;n.send=function(){let o=arguments[0],d=o.length||o.size||o.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},T(e,"datachannel",n=>(t(n.channel,n.target),n))}function X(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 a=new Event("connectionstatechange",s);i.dispatchEvent(a)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function Q(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
|
+
a=extmap-allow-mixed`)!==-1){let i=s.sdp.split(`
|
34
34
|
`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
|
35
|
-
`);e.RTCSessionDescription&&i instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:i.type,sdp:s}):i.sdp=s}return n.apply(this,arguments)}}function E(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.addIceCandidate;!n||n.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():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function _(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return n.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?n.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>n.apply(this,[a]))})}var jt=it(ke());function ht({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){let n=L,r=dt(e),i={browserDetails:r,commonShim:Ie,extractVersion:P,disableLog:ct,disableWarnings:pt,sdp:jt};switch(r.browser){case"chrome":if(!U||!j||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),i;if(r.version===null)return n("Chrome shim can not determine version, not shimming."),i;n("adapter.js shimming chrome."),i.browserShim=U,E(e,r),_(e,r),A(e,r),re(e,r),j(e,r),ne(e,r),oe(e,r),ie(e,r),se(e,r),ae(e,r),x(e,r),z(e,r),B(e,r),k(e,r),I(e,r),K(e,r);break;case"firefox":if(!G||!N||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),i;n("adapter.js shimming firefox."),i.browserShim=G,E(e,r),_(e,r),F(e,r),N(e,r),ce(e,r),le(e,r),pe(e,r),de(e,r),ue(e,r),me(e,r),fe(e,r),he(e,r),ge(e,r),x(e,r),B(e,r),k(e,r),I(e,r);break;case"safari":if(!q||!t.shimSafari)return n("Safari shim is not included in this adapter release."),i;n("adapter.js shimming safari."),i.browserShim=q,E(e,r),_(e,r),ve(e,r),be(e,r),Se(e,r),Ce(e,r),ye(e,r),Te(e,r),Re(e,r),Pe(e,r),x(e,r),z(e,r),k(e,r),I(e,r),K(e,r);break;default:n("Unsupported browser!");break}return i}var Ut=ht({window:typeof window>"u"?void 0:window}),M=Ut;var gt=require("@protobuf-ts/runtime-rpc"),h=require("@protobuf-ts/runtime"),Ze=(s=>(s[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.OFFER=1]="OFFER",s[s.ANSWER=2]="ANSWER",s[s.PRANSWER=3]="PRANSWER",s[s.ROLLBACK=4]="ROLLBACK",s))(Ze||{}),Ee=class extends h.MessageType{constructor(){super("pulsebeam.v1.PrepareReq",[])}},Ft=new Ee,_e=class extends h.MessageType{constructor(){super("pulsebeam.v1.PrepareResp",[{no:1,name:"ice_servers",kind:"message",repeat:1,T:()=>Gt}])}},Nt=new _e,Me=class extends h.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}])}},Gt=new Me,De=class extends h.MessageType{constructor(){super("pulsebeam.v1.SendReq",[{no:1,name:"msg",kind:"message",T:()=>Ct}])}},qt=new De,Oe=class extends h.MessageType{constructor(){super("pulsebeam.v1.SendResp",[])}},zt=new Oe,Le=class extends h.MessageType{constructor(){super("pulsebeam.v1.RecvReq",[{no:1,name:"src",kind:"message",T:()=>Ue}])}},Bt=new Le,Ae=class extends h.MessageType{constructor(){super("pulsebeam.v1.RecvResp",[{no:1,name:"msg",kind:"message",T:()=>Ct}])}},Kt=new Ae,je=class extends h.MessageType{constructor(){super("pulsebeam.v1.PeerInfo",[{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}])}},Ue=new je,Fe=class extends h.MessageType{constructor(){super("pulsebeam.v1.Message",[{no:1,name:"header",kind:"message",T:()=>Vt},{no:2,name:"payload",kind:"message",T:()=>Jt}])}},Ct=new Fe,Ne=class extends h.MessageType{constructor(){super("pulsebeam.v1.MessagePayload",[{no:1,name:"signal",kind:"message",oneof:"payloadType",T:()=>Ht},{no:2,name:"join",kind:"message",oneof:"payloadType",T:()=>Xt},{no:3,name:"bye",kind:"message",oneof:"payloadType",T:()=>Qt},{no:4,name:"ack",kind:"message",oneof:"payloadType",T:()=>Zt},{no:5,name:"ping",kind:"message",oneof:"payloadType",T:()=>$t}])}},Jt=new Ne,Ge=class extends h.MessageType{constructor(){super("pulsebeam.v1.MessageHeader",[{no:1,name:"src",kind:"message",T:()=>Ue},{no:2,name:"dst",kind:"message",T:()=>Ue},{no:7,name:"seqnum",kind:"scalar",T:13},{no:8,name:"reliable",kind:"scalar",T:8}])}},Vt=new Ge,qe=class extends h.MessageType{constructor(){super("pulsebeam.v1.Signal",[{no:1,name:"generation_counter",kind:"scalar",T:13},{no:9,name:"sdp",kind:"message",oneof:"data",T:()=>Yt},{no:10,name:"ice_candidate",kind:"message",oneof:"data",T:()=>yt},{no:11,name:"ice_candidate_batch",kind:"message",oneof:"data",T:()=>Wt}])}},Ht=new qe,ze=class extends h.MessageType{constructor(){super("pulsebeam.v1.Sdp",[{no:1,name:"kind",kind:"enum",T:()=>["pulsebeam.v1.SdpKind",Ze,"SDP_KIND_"]},{no:2,name:"sdp",kind:"scalar",T:9}])}},Yt=new ze,Be=class extends h.MessageType{constructor(){super("pulsebeam.v1.ICECandidateBatch",[{no:1,name:"candidates",kind:"message",repeat:1,T:()=>yt}])}},Wt=new Be,Ke=class extends h.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}])}},yt=new Ke,Je=class extends h.MessageType{constructor(){super("pulsebeam.v1.Join",[])}},Xt=new Je,Ve=class extends h.MessageType{constructor(){super("pulsebeam.v1.Bye",[])}},Qt=new Ve,He=class extends h.MessageType{constructor(){super("pulsebeam.v1.Ack",[{no:1,name:"ack_ranges",kind:"message",repeat:1,T:()=>wt}])}},Zt=new He,Ye=class extends h.MessageType{constructor(){super("pulsebeam.v1.Ping",[])}},$t=new Ye,We=class extends h.MessageType{constructor(){super("pulsebeam.v1.AckRange",[{no:1,name:"seqnum_start",kind:"scalar",T:13},{no:2,name:"seqnum_end",kind:"scalar",T:13}])}},wt=new We,Xe=class extends h.MessageType{constructor(){super("pulsebeam.v1.DataChannel",[{no:10,name:"heartbeat",kind:"message",oneof:"payload",T:()=>er}])}},Pr=new Xe,Qe=class extends h.MessageType{constructor(){super("pulsebeam.v1.DataChannelHeartbeat",[])}},er=new Qe,J=new gt.ServiceType("pulsebeam.v1.Signaling",[{name:"Prepare",options:{},I:Ft,O:Nt},{name:"Send",options:{},I:qt,O:zt},{name:"Recv",serverStreaming:!0,options:{},I:Bt,O:Kt}]);var V=require("@protobuf-ts/runtime-rpc"),H=class{constructor(t){this._transport=t;this.typeName=J.typeName;this.methods=J.methods;this.options=J.options}prepare(t,n){let r=this.methods[0],i=this._transport.mergeOptions(n);return(0,V.stackIntercept)("unary",this._transport,r,i,t)}send(t,n){let r=this.methods[1],i=this._transport.mergeOptions(n);return(0,V.stackIntercept)("unary",this._transport,r,i,t)}recv(t,n){let r=this.methods[2],i=this._transport.mergeOptions(n);return(0,V.stackIntercept)("serverStreaming",this._transport,r,i,t)}};function $e(e,t){return new Promise(n=>{let r=setTimeout(()=>n(!0),e);t&&t.addEventListener("abort",()=>{clearTimeout(r),n(!1)})})}function Y(...e){let t=new AbortController,n=()=>{t.abort();for(let r of e)r.removeEventListener("abort",n)};for(let r of e)r.addEventListener("abort",n);return t.signal}async function D(e,t){let{maxRetries:n,baseDelay:r,maxDelay:i,jitterFactor:s=.3,isRecoverable:a=()=>!0,abortSignal:o}=t,d=0;for(;(d<=n||n<0)&&!o?.aborted;)try{return await e()}catch(c){if(!a(c)||(d++,n>=0&&d>n))throw c;let p=tr(d,r,i,s);await $e(p,o).catch(()=>{})}if(o?.aborted)return null;throw new Error("Retry failed: max retries exceeded")}function tr(e,t,n,r){let i=Math.min(t*2**(e-1),n),s=Math.random()*r*i;return i+s}var St=9e5,Rt=50,we=1e3;var rr=$e,nr=e=>{let t;do{let n=new Uint32Array(1);crypto.getRandomValues(n),t=n[0]}while(t>=0&&t<e);return t},ir=e=>!0,et=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 n=t.header.seqnum;if(this.map.has(n)||this.emitted.has(n))return;this.map.set(n,[performance.now(),t])}this.processNext()}async processNext(){if(this.processing)return;let t=this.unreliable.pop();if(!t){let n=this.map.entries().next().value;if(!n)return;let[r,i]=n;this.map.delete(r),this.emitted.set(r,i);let[s,a]=i;if(!a.header)return;t=a}this.processing=!0;try{await this.onmsg(t)}catch(n){let r={msg:t};n instanceof Error&&(r.err=n),this.logger.error("error processing message",r)}this.processing=!1,this.processNext()}},W=class{constructor(t,n){this.client=t;this.opts=n;this.onstream=t=>{};this.onclosed=t=>{};this.handleControlMessage=t=>{switch(t.payloadType.oneofKind){case"ping":this.logger.debug("received ping");break;default:this.logger.warn("received unknown control message",{payload:t});break}};this.handleMessages=t=>{if(this.logger.debug("received",{msg:t}),this.abort.signal.aborted)return;if(!t.header)return t.payload?this.handleControlMessage(t.payload):void 0;let n=t.header.src,r=t.header.dst;if(!n||!r)return;if(r.connId>=16&&r.connId!=this.info.connId){this.logger.warn("received messages from a stale connection, ignoring",{receivedConnID:r.connId});return}let i=null;for(let s of this.streams)if(n.groupId===s.other.groupId&&n.peerId===s.other.peerId&&n.connId===s.other.connId){i=s;break}if(!i){if(n.peerId==this.info.peerId){this.logger.warn("loopback detected, ignoring messages");return}this.logger.debug(`session not found, creating one for ${n.peerId}:${n.connId}`),i=new tt(this,this.info,n,this.logger),this.streams.push(i),this.onstream(i)}i.enqueue(t)};this.asleep=n.asleep||rr,this.randUint32=n.randUint32||nr,this.isRecoverable=n.isRecoverable||ir,this.info={groupId:n.groupId,peerId:n.peerId,connId:this.randUint32(16)},this.abort=new AbortController,this.logger=n.logger.sub("transport",{info:this.info}),this.streams=[]}async listen(){let t={abort:this.abort.signal,timeout:St},n={baseDelay:Rt,maxDelay:we,maxRetries:-1,abortSignal:this.abort.signal,isRecoverable:this.isRecoverable};for(;!this.abort.signal.aborted;)try{await D(async()=>{let r=this.client.recv({src:this.info},t);r.responses.onMessage(i=>!!i.msg&&this.handleMessages(i.msg)),await r},n)}catch(r){this.logger.error("unrecoverable error, force closing",{err:r}),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(n=>n.close(t))),this.abort.abort(t),this.logger.debug("transport is now closed",{reason:t}),this.streams=[],this.onclosed(t))}removeStream(t){this.streams=this.streams.filter(n=>n!==t)}async connect(t,n,r){let i={payloadType:{oneofKind:"join",join:{}}},s={src:this.info,dst:{groupId:t,peerId:n,connId:0},seqnum:0,reliable:!1},a=!1,o=Y(r,this.abort.signal);for(;!o.aborted&&!a;)await this.send(o,{header:s,payload:i}),await this.asleep(we,o).catch(()=>{}),a=!!this.streams.find(d=>d.other.groupId===t&&d.other.peerId===n)}async send(t,n){let r=Y(t,this.abort.signal),i={abort:r,timeout:St},s={baseDelay:Rt,maxDelay:we,maxRetries:-1,abortSignal:r,isRecoverable:this.isRecoverable};try{if(await D(async()=>await this.client.send({msg:n},i),s)===null){this.logger.warn("aborted, message dropped from sending",{msg:n});return}return}catch(a){this.logger.error("unrecoverable error, force closing",{err:a}),this.close();return}}},tt=class{constructor(t,n,r,i){this.transport=t;this.info=n;this.other=r;this.onsignal=async t=>{};this.onclosed=t=>{};this.logger=i.sub("stream",{other:r}),this.abort=new AbortController,this.recvq=new et(this.logger),this.recvq.onmsg=s=>this.handleMessage(s),this.lastSeqnum=0}createSignal(...t){return Y(this.abort.signal,...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,n,r){r||(r=this.abort.signal);let i={header:{src:this.transport.info,dst:this.other,seqnum:this.lastSeqnum,reliable:n},payload:{...t}};this.lastSeqnum++,await this.transport.send(r,i)}async handleMessage(t){if(!t.payload){this.logger.warn("payload is missing from the stream message",{msg:t});return}switch(t.payload.payloadType.oneofKind){case"bye":this.close("received bye",!0);return;case"signal":this.onsignal(t.payload.payloadType.signal);return;case"join":return;default:this.logger.warn("unhandled payload type",{msg:t});return}}async close(t,n){this.abort.signal.aborted||(t=t||"session is closed",n||await this.send({payloadType:{oneofKind:"bye",bye:{}}},!1).catch(r=>this.logger.warn("failed to send bye",{e:r})),this.abort.abort(t),this.transport.removeStream(this),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},vt={DEBUG:e=>console.debug(X(e)),INFO:e=>console.info(X(e)),WARN:e=>console.warn(X(e)),ERROR:e=>console.error(X(e))};function Tt(e,t,n="root",r=new Set){let i=".";if(!r.has(e)){r.add(e);for(let s in e)if(typeof e[s]=="object"&&e[s]!==null){let a=n+i+s;Tt(e[s],t,a,r)}else{let a=t[n]||[];a.push(`${s}=${e[s]}`),t[n]=a}}}function X(e){let t={};Tt(e,t);let n=[];for(let r in t)n.push(`[${r}] ${t[r].join(" ")}`);return n.join(`
|
36
|
-
`)}var Q=class e{constructor(t,n,r){this.name=t;n||(n={}),r||(r=sr),this.sink=r,this.obj={...n,name:t}}log(t,n,r){let i=r||{};t({ts:Date.now(),message:n,...this.obj,...i})}debug(t,n){this.log(this.sink.DEBUG,t,n)}info(t,n){this.log(this.sink.INFO,t,n)}warn(t,n){this.log(this.sink.WARN,t,n)}error(t,n){this.log(this.sink.ERROR,t,n)}sub(t,n){return n||(n={}),new e(this.name+"."+t,{...this.obj,...n},this.sink)}};var or=2,bt=5e3;function ar(e){return{candidate:e.candidate,sdpMid:e.sdpMid,sdpMLineIndex:e.sdpMLineIndex,usernameFragment:e.password}}function cr(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 Pt(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 Z=class{constructor(t,n){this.stream=t;this.ondatachannel=()=>{};this.onconnectionstatechange=()=>{};this.ontrack=()=>{};this.triggerIceRestart=()=>{if(!this.impolite)return;let t=performance.now()-this.lastIceRestart;if(t<bt){let n=bt-t,r=window.setTimeout(()=>{this.triggerIceRestart(),this.timers=this.timers.filter(i=>i===r)},n);return}if(this.pc.connectionState!=="connected"){if(this.iceRestartCount>=or){this.close("detected sustained network failure");return}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.handleSignal=async t=>{if(t.generationCounter<this.generationCounter){this.logger.warn("detected staled generationCounter signals, ignoring");return}this.addCandidates(t);let n=t.data;if(t.generationCounter>this.generationCounter){if(this.logger.debug("detected new generationCounter",{otherGenerationCounter:t.generationCounter,generationCounter:this.generationCounter,msg:n}),n.oneofKind==="iceCandidate"){this.logger.warn("expecting an offer but got ice candidates during an ICE restart, adding to pending.",{msg:n});return}this.generationCounter=t.generationCounter}if(n.oneofKind!="sdp")return;let r=n.sdp;this.logger.debug("received a SDP signal",{sdpKind:r.kind});let i=r.kind===1&&(this.makingOffer||this.pc.signalingState!=="stable");if(this.impolite&&i){this.logger.debug("ignored offer");return}if(this.logger.debug("creating an answer"),await this.pc.setRemoteDescription({type:cr(r.kind),sdp:r.sdp}),r.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:Pt(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 n of this.pendingCandidates)!n.candidate||n.candidate===""||(this.pc.addIceCandidate(n).catch(r=>{this.logger.warn("failed to add candidate, skipping.",{candidate:n,e:r})}),this.logger.debug(`added ice: ${n.candidate}`));this.pendingCandidates=[]};this.pc=new RTCPeerConnection(n),this.makingOffer=!1,this.pendingCandidates=[],this.stream.info.connId===this.stream.other.connId?this.impolite=this.stream.info.peerId>this.stream.other.peerId:this.impolite=this.stream.info.connId>this.stream.other.connId,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",this.iceBatcher=new rt(this.logger,100,s=>this.sendLocalIceCandidates(s)),t.onsignal=s=>this.handleSignal(s),t.onclosed=s=>this.close(s),this.pc.oniceconnectionstatechange=async()=>{let s=await this.pc.getStats(),a=[],o=[],d=[];s.forEach(c=>{c.type==="candidate-pair"?a.push(c):c.type==="local-candidate"?o.push(c):c.type==="remote-candidate"&&d.push(c)}),this.logger.debug("iceconnectionstate changed",{connectionstate:this.pc.connectionState,iceconnectionstate:this.pc.iceConnectionState,local:o,remote:d,pair:a,pending:this.pendingCandidates})};let r=performance.now();this.pc.onconnectionstatechange=s=>{switch(this.logger.debug("connectionstate changed",{connectionstate:this.pc.connectionState,iceconnectionstate:this.pc.iceConnectionState}),this.setConnectionState(this.pc.connectionState,s),this.pc.connectionState){case"connecting":r=performance.now();break;case"connected":{let a=performance.now()-r;this.logger.debug(`it took ${a}ms to connect`),this.iceRestartCount=0;break}case"disconnected":this.triggerIceRestart();break;case"failed":this.triggerIceRestart();break;case"closed":break}};let i=!0;this.pc.onnegotiationneeded=async()=>{if(i){if(!this.impolite){this.stream.send({payloadType:{oneofKind:"join",join:{}}},!0);return}i=!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:Pt(this.pc.localDescription.type),sdp:this.pc.localDescription.sdp}}})}catch(s){s instanceof Error&&this.logger.error("failed in negotiating",{err:s})}finally{this.makingOffer=!1}},this.pc.onicecandidate=({candidate:s})=>{this.iceBatcher.addCandidate(s)},this.pc.ondatachannel=(...s)=>{this.ondatachannel&&this.ondatachannel(...s)},this.pc.ontrack=(...s)=>{this.ontrack&&this.ontrack(...s)}}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 other(){return{groupId:this.stream.other.groupId,peerId:this.stream.other.peerId,connId:this.stream.other.connId}}close(t){if(this.abort.signal.aborted)return;this.abort.abort(t);for(let r of this.timers)clearTimeout(r);this.timers=[],this.iceBatcher.close(),this.stream.close(),this._closeReason=t,this.pc.close();let n=new Event("connectionstatechange");this.setConnectionState("closed",n),this.logger.debug("session closed",{connectionState:this.connectionState})}sendLocalIceCandidates(t){let n=[];for(let r of t){let i={candidate:"",sdpMLineIndex:0,sdpMid:""};i.candidate=r.candidate,i.sdpMLineIndex=r.sdpMLineIndex??void 0,i.sdpMid=r.sdpMid??void 0,i.username=r.usernameFragment??void 0,n.push(i)}this.sendSignal({data:{oneofKind:"iceCandidateBatch",iceCandidateBatch:{candidates:n}}})}setConnectionState(t,n){t!==this._connectionState&&this.onconnectionstatechange&&this.onconnectionstatechange(n)}addCandidates(t){let n=[];if(t.data.oneofKind==="iceCandidate")n.push(t.data.iceCandidate);else if(t.data.oneofKind==="iceCandidateBatch")n.push(...t.data.iceCandidateBatch.candidates);else return;this.pendingCandidates.push(...n.map(r=>ar(r))),this.checkPendingCandidates()}},rt=class{constructor(t,n,r){this.candidates=[];this.timeoutId=null;this.addCandidate=t=>{if(!t||t.candidate===""){this.logger.debug("ice gathering is finished, force flush local candidates"),this.flushCandidates();return}this.logger.debug("onicecandidate",{candidate:t}),this.candidates.push(t),this.timeoutId?(clearTimeout(this.timeoutId),this.timeoutId=setTimeout(this.flushCandidates,this.delayMs)):this.timeoutId=setTimeout(this.flushCandidates,this.delayMs)};this.flushCandidates=()=>{this.candidates.length>0&&(this.onIceCandidates(this.candidates),this.candidates=[]),this.timeoutId=null};this.flush=()=>{this.timeoutId&&clearTimeout(this.timeoutId),this.flushCandidates()};this.close=()=>{this.timeoutId&&clearTimeout(this.timeoutId)};this.logger=t.sub("icebatcher"),this.delayMs=n,this.onIceCandidates=r}};var kt=require("@protobuf-ts/runtime-rpc"),y=require("@protobuf-ts/grpcweb-transport");var It=require("jwt-decode"),pr="https://cloud.pulsebeam.dev/grpc";var $=class{constructor(t,n,r,i){this.onsession=t=>{};this.onstatechange=()=>{};this.peerId=r.peerId,this.logger=t.sub("peer",{peerId:this.peerId}),this.sessions=[],this._state="new";let s={bundlePolicy:"balanced",iceTransportPolicy:r.forceRelay?"relay":"all",iceCandidatePoolSize:0,iceServers:r.iceServers};this.transport=new W(n,{enableDiscovery:!1,groupId:r.groupId,peerId:r.peerId,logger:this.logger,isRecoverable:i}),this.transport.onstream=a=>{let o=new Z(a,s);this.sessions.push(o),this.onsession(o)},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,n,r){return this.transport.connect(t,n,r)}get state(){return this._state}setState(t){t!==this._state&&(this._state=t,this.onstatechange())}},dr=[y.GrpcStatusCode[y.GrpcStatusCode.PERMISSION_DENIED],y.GrpcStatusCode[y.GrpcStatusCode.INVALID_ARGUMENT],y.GrpcStatusCode[y.GrpcStatusCode.ABORTED],y.GrpcStatusCode[y.GrpcStatusCode.NOT_FOUND],y.GrpcStatusCode[y.GrpcStatusCode.UNAUTHENTICATED]];function xt(e){return e instanceof Error?e instanceof kt.RpcError?!dr.includes(e.code):!0:!1}async function lr(e){let t=e.token,n=new y.GrpcWebFetchTransport({baseUrl:e.baseUrl||pr,sendJson:!1,format:"binary",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)}}]}),r=new H(n),i=await D(async()=>await r.prepare({}),{baseDelay:50,maxDelay:1e3,maxRetries:5,isRecoverable:xt});if(i===null)throw new Error("createPeer aborted");let s=[...e.iceServers||[]];for(let c of i.response.iceServers)s.push({urls:c.urls,username:c.username,credential:c.credential});let a=(0,It.jwtDecode)(t),o={...e,iceServers:s,groupId:a.gid,peerId:a.pid};return new $(new Q("pulsebeam",void 0,vt),r,o,xt)}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
|
-
//# sourceMappingURL=index.cjs.map
|
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 M(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 L(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(a=>r.apply(this,[a]))})}var Zt=Rt(Me());function Dt({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){let r=K,n=vt(e),s={browserDetails:n,commonShim:Le,extractVersion:x,disableLog:_t,disableWarnings:Et,sdp:Zt};switch(n.browser){case"chrome":if(!z||!B||!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=z,M(e,n),L(e,n),q(e,n),de(e,n),B(e,n),le(e,n),he(e,n),ue(e,n),me(e,n),fe(e,n),k(e,n),W(e,n),X(e,n),O(e,n),N(e,n),Q(e,n);break;case"firefox":if(!Y||!H||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),s;r("adapter.js shimming firefox."),s.browserShim=Y,M(e,n),L(e,n),J(e,n),H(e,n),ge(e,n),Se(e,n),Ce(e,n),Re(e,n),ye(e,n),Te(e,n),_e(e,n),Ee(e,n),ve(e,n),k(e,n),X(e,n),O(e,n),N(e,n);break;case"safari":if(!$||!t.shimSafari)return r("Safari shim is not included in this adapter release."),s;r("adapter.js shimming safari."),s.browserShim=$,M(e,n),L(e,n),De(e,n),ke(e,n),Ie(e,n),be(e,n),Pe(e,n),xe(e,n),Ae(e,n),Oe(e,n),k(e,n),W(e,n),O(e,n),N(e,n),Q(e,n);break;default:r("Unsupported browser!");break}return s}var wt=Dt({window:typeof window>"u"?void 0:window}),U=wt;var xt=require("@protobuf-ts/runtime-rpc"),C=require("@protobuf-ts/runtime"),pt=(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))(pt||{}),dt=(l=>(l[l.UNKNOWN_EVENT=0]="UNKNOWN_EVENT",l[l.EVENT_ERROR_REPORTING_BASE=1e3]="EVENT_ERROR_REPORTING_BASE",l[l.EVENT_ERROR_SIGNALING_CONNECTION_FAILED=1001]="EVENT_ERROR_SIGNALING_CONNECTION_FAILED",l[l.EVENT_ERROR_ICE_CONNECTION_FAILED=1002]="EVENT_ERROR_ICE_CONNECTION_FAILED",l[l.EVENT_ERROR_MEDIA_CAPTURE_AUDIO_FAILED=1003]="EVENT_ERROR_MEDIA_CAPTURE_AUDIO_FAILED",l[l.EVENT_ERROR_MEDIA_CAPTURE_VIDEO_FAILED=1004]="EVENT_ERROR_MEDIA_CAPTURE_VIDEO_FAILED",l[l.EVENT_ERROR_MEDIA_CAPTURE_SCREEN_FAILED=1005]="EVENT_ERROR_MEDIA_CAPTURE_SCREEN_FAILED",l[l.EVENT_ERROR_SDP_NEGOTIATION_FAILED=1006]="EVENT_ERROR_SDP_NEGOTIATION_FAILED",l[l.EVENT_ERROR_OTHER=1099]="EVENT_ERROR_OTHER",l[l.EVENT_ICE_CANDIDATE_BASE=2e3]="EVENT_ICE_CANDIDATE_BASE",l[l.EVENT_ICE_CANDIDATE_GATHERING_STARTED=2001]="EVENT_ICE_CANDIDATE_GATHERING_STARTED",l[l.EVENT_ICE_CANDIDATE_LOCAL_REFLEXIVE_FOUND=2002]="EVENT_ICE_CANDIDATE_LOCAL_REFLEXIVE_FOUND",l[l.EVENT_ICE_CANDIDATE_LOCAL_HOST_FOUND=2003]="EVENT_ICE_CANDIDATE_LOCAL_HOST_FOUND",l[l.EVENT_ICE_CANDIDATE_LOCAL_SRFLX_FOUND=2004]="EVENT_ICE_CANDIDATE_LOCAL_SRFLX_FOUND",l[l.EVENT_ICE_CANDIDATE_LOCAL_PRFLX_FOUND=2005]="EVENT_ICE_CANDIDATE_LOCAL_PRFLX_FOUND",l[l.EVENT_ICE_CANDIDATE_REMOTE_RECEIVED=2006]="EVENT_ICE_CANDIDATE_REMOTE_RECEIVED",l[l.EVENT_ICE_CANDIDATE_REMOTE_REFLEXIVE_FOUND=2007]="EVENT_ICE_CANDIDATE_REMOTE_REFLEXIVE_FOUND",l[l.EVENT_ICE_CANDIDATE_REMOTE_HOST_FOUND=2008]="EVENT_ICE_CANDIDATE_REMOTE_HOST_FOUND",l[l.EVENT_ICE_CANDIDATE_REMOTE_SRFLX_FOUND=2009]="EVENT_ICE_CANDIDATE_REMOTE_SRFLX_FOUND",l[l.EVENT_ICE_CANDIDATE_REMOTE_PRFLX_FOUND=2010]="EVENT_ICE_CANDIDATE_REMOTE_PRFLX_FOUND",l[l.EVENT_ICE_CANDIDATE_PAIRING_SUCCESS=2011]="EVENT_ICE_CANDIDATE_PAIRING_SUCCESS",l[l.EVENT_ICE_CANDIDATE_PAIRING_FAILED=2012]="EVENT_ICE_CANDIDATE_PAIRING_FAILED",l[l.EVENT_ICE_CANDIDATE_CONNECTION_STATE_CHANGED=2013]="EVENT_ICE_CANDIDATE_CONNECTION_STATE_CHANGED",l[l.EVENT_ICE_CANDIDATE_GATHERING_COMPLETED=2014]="EVENT_ICE_CANDIDATE_GATHERING_COMPLETED",l[l.EVENT_ICE_CANDIDATE_SELECTED_PAIR=2015]="EVENT_ICE_CANDIDATE_SELECTED_PAIR",l[l.EVENT_SIGNALING_BASE=3e3]="EVENT_SIGNALING_BASE",l[l.EVENT_SIGNALING_OFFER_CREATED=3001]="EVENT_SIGNALING_OFFER_CREATED",l[l.EVENT_SIGNALING_OFFER_SENT=3002]="EVENT_SIGNALING_OFFER_SENT",l[l.EVENT_SIGNALING_OFFER_RECEIVED=3003]="EVENT_SIGNALING_OFFER_RECEIVED",l[l.EVENT_SIGNALING_ANSWER_CREATED=3004]="EVENT_SIGNALING_ANSWER_CREATED",l[l.EVENT_SIGNALING_ANSWER_SENT=3005]="EVENT_SIGNALING_ANSWER_SENT",l[l.EVENT_SIGNALING_ANSWER_RECEIVED=3006]="EVENT_SIGNALING_ANSWER_RECEIVED",l[l.EVENT_SIGNALING_NEGOTIATION_NEEDED=3007]="EVENT_SIGNALING_NEGOTIATION_NEEDED",l[l.EVENT_SIGNALING_ICE_RESTART_TRIGGERED=3008]="EVENT_SIGNALING_ICE_RESTART_TRIGGERED",l[l.EVENT_SIGNALING_CONNECTED=3009]="EVENT_SIGNALING_CONNECTED",l[l.EVENT_SIGNALING_DISCONNECTED=3010]="EVENT_SIGNALING_DISCONNECTED",l[l.EVENT_USER_INTERACTION_BASE=4e3]="EVENT_USER_INTERACTION_BASE",l[l.EVENT_USER_JOINED_SESSION=4001]="EVENT_USER_JOINED_SESSION",l[l.EVENT_USER_LEFT_SESSION=4002]="EVENT_USER_LEFT_SESSION",l[l.EVENT_USER_MUTED_AUDIO=4003]="EVENT_USER_MUTED_AUDIO",l[l.EVENT_USER_UNMUTED_AUDIO=4004]="EVENT_USER_UNMUTED_AUDIO",l[l.EVENT_USER_MUTED_VIDEO=4005]="EVENT_USER_MUTED_VIDEO",l[l.EVENT_USER_UNMUTED_VIDEO=4006]="EVENT_USER_UNMUTED_VIDEO",l[l.EVENT_USER_SCREEN_SHARE_STARTED=4007]="EVENT_USER_SCREEN_SHARE_STARTED",l[l.EVENT_USER_SCREEN_SHARE_STOPPED=4008]="EVENT_USER_SCREEN_SHARE_STOPPED",l[l.EVENT_USER_INPUT_TEXT_MESSAGE_SENT=4009]="EVENT_USER_INPUT_TEXT_MESSAGE_SENT",l[l.EVENT_USER_INPUT_TEXT_MESSAGE_RECEIVED=4010]="EVENT_USER_INPUT_TEXT_MESSAGE_RECEIVED",l[l.EVENT_MEDIA_HANDLING_BASE=5e3]="EVENT_MEDIA_HANDLING_BASE",l[l.EVENT_MEDIA_LOCAL_AUDIO_TRACK_ADDED=5001]="EVENT_MEDIA_LOCAL_AUDIO_TRACK_ADDED",l[l.EVENT_MEDIA_LOCAL_VIDEO_TRACK_ADDED=5002]="EVENT_MEDIA_LOCAL_VIDEO_TRACK_ADDED",l[l.EVENT_MEDIA_REMOTE_AUDIO_TRACK_ADDED=5003]="EVENT_MEDIA_REMOTE_AUDIO_TRACK_ADDED",l[l.EVENT_MEDIA_REMOTE_VIDEO_TRACK_ADDED=5004]="EVENT_MEDIA_REMOTE_VIDEO_TRACK_ADDED",l[l.EVENT_MEDIA_LOCAL_AUDIO_TRACK_REMOVED=5005]="EVENT_MEDIA_LOCAL_AUDIO_TRACK_REMOVED",l[l.EVENT_MEDIA_LOCAL_VIDEO_TRACK_REMOVED=5006]="EVENT_MEDIA_LOCAL_VIDEO_TRACK_REMOVED",l[l.EVENT_MEDIA_REMOTE_AUDIO_TRACK_REMOVED=5007]="EVENT_MEDIA_REMOTE_AUDIO_TRACK_REMOVED",l[l.EVENT_MEDIA_REMOTE_VIDEO_TRACK_REMOVED=5008]="EVENT_MEDIA_REMOTE_VIDEO_TRACK_REMOVED",l[l.EVENT_MEDIA_AUDIO_PLAYBACK_STARTED=5009]="EVENT_MEDIA_AUDIO_PLAYBACK_STARTED",l[l.EVENT_MEDIA_VIDEO_PLAYBACK_STARTED=5010]="EVENT_MEDIA_VIDEO_PLAYBACK_STARTED",l[l.EVENT_MEDIA_AUDIO_PLAYBACK_STOPPED=5011]="EVENT_MEDIA_AUDIO_PLAYBACK_STOPPED",l[l.EVENT_MEDIA_VIDEO_PLAYBACK_STOPPED=5012]="EVENT_MEDIA_VIDEO_PLAYBACK_STOPPED",l[l.CONNECTION_TYPE_UNKNOWN=6e3]="CONNECTION_TYPE_UNKNOWN",l[l.CONNECTION_TYPE_DIRECT=6001]="CONNECTION_TYPE_DIRECT",l[l.CONNECTION_TYPE_RELAY=6002]="CONNECTION_TYPE_RELAY",l[l.CONNECTION_TYPE_SRFLX=6003]="CONNECTION_TYPE_SRFLX",l[l.CONNECTION_TYPE_PRFLX=6004]="CONNECTION_TYPE_PRFLX",l))(dt||{}),Ue=class extends C.MessageType{constructor(){super("pulsebeam.v1.PrepareReq",[])}},er=new Ue,Ve=class extends C.MessageType{constructor(){super("pulsebeam.v1.PrepareResp",[{no:1,name:"ice_servers",kind:"message",repeat:1,T:()=>rr}])}},tr=new Ve,je=class extends C.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}])}},rr=new je,Fe=class extends C.MessageType{constructor(){super("pulsebeam.v1.SendReq",[{no:1,name:"msg",kind:"message",T:()=>kt}])}},nr=new Fe,Ge=class extends C.MessageType{constructor(){super("pulsebeam.v1.SendResp",[])}},sr=new Ge,Ke=class extends C.MessageType{constructor(){super("pulsebeam.v1.RecvReq",[{no:1,name:"src",kind:"message",T:()=>V}])}},ir=new Ke,qe=class extends C.MessageType{constructor(){super("pulsebeam.v1.RecvResp",[{no:1,name:"msg",kind:"message",T:()=>kt}])}},or=new qe,Be=class extends C.MessageType{constructor(){super("pulsebeam.v1.PeerInfo",[{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}])}},V=new Be,ze=class extends C.MessageType{constructor(){super("pulsebeam.v1.Message",[{no:1,name:"header",kind:"message",T:()=>cr},{no:2,name:"payload",kind:"message",T:()=>ar}])}},kt=new ze,Je=class extends C.MessageType{constructor(){super("pulsebeam.v1.MessagePayload",[{no:1,name:"signal",kind:"message",oneof:"payloadType",T:()=>pr},{no:2,name:"join",kind:"message",oneof:"payloadType",T:()=>ur},{no:3,name:"bye",kind:"message",oneof:"payloadType",T:()=>mr},{no:4,name:"ack",kind:"message",oneof:"payloadType",T:()=>hr},{no:5,name:"ping",kind:"message",oneof:"payloadType",T:()=>fr}])}},ar=new Je,He=class extends C.MessageType{constructor(){super("pulsebeam.v1.MessageHeader",[{no:1,name:"src",kind:"message",T:()=>V},{no:2,name:"dst",kind:"message",T:()=>V},{no:7,name:"seqnum",kind:"scalar",T:13},{no:8,name:"reliable",kind:"scalar",T:8}])}},cr=new He,Ye=class extends C.MessageType{constructor(){super("pulsebeam.v1.Signal",[{no:1,name:"generation_counter",kind:"scalar",T:13},{no:9,name:"sdp",kind:"message",oneof:"data",T:()=>dr},{no:10,name:"ice_candidate",kind:"message",oneof:"data",T:()=>Ot},{no:11,name:"ice_candidate_batch",kind:"message",oneof:"data",T:()=>lr}])}},pr=new Ye,$e=class extends C.MessageType{constructor(){super("pulsebeam.v1.Sdp",[{no:1,name:"kind",kind:"enum",T:()=>["pulsebeam.v1.SdpKind",pt,"SDP_KIND_"]},{no:2,name:"sdp",kind:"scalar",T:9}])}},dr=new $e,We=class extends C.MessageType{constructor(){super("pulsebeam.v1.ICECandidateBatch",[{no:1,name:"candidates",kind:"message",repeat:1,T:()=>Ot}])}},lr=new We,Xe=class extends C.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}])}},Ot=new Xe,Qe=class extends C.MessageType{constructor(){super("pulsebeam.v1.Join",[])}},ur=new Qe,Ze=class extends C.MessageType{constructor(){super("pulsebeam.v1.Bye",[])}},mr=new Ze,we=class extends C.MessageType{constructor(){super("pulsebeam.v1.Ack",[{no:1,name:"ack_ranges",kind:"message",repeat:1,T:()=>gr}])}},hr=new we,et=class extends C.MessageType{constructor(){super("pulsebeam.v1.Ping",[])}},fr=new et,tt=class extends C.MessageType{constructor(){super("pulsebeam.v1.AckRange",[{no:1,name:"seqnum_start",kind:"scalar",T:13},{no:2,name:"seqnum_end",kind:"scalar",T:13}])}},gr=new tt,rt=class extends C.MessageType{constructor(){super("pulsebeam.v1.DataChannel",[{no:10,name:"heartbeat",kind:"message",oneof:"payload",T:()=>Cr}])}},Xr=new rt,nt=class extends C.MessageType{constructor(){super("pulsebeam.v1.DataChannelHeartbeat",[])}},Cr=new nt,st=class extends C.MessageType{constructor(){super("pulsebeam.v1.AnalyticsReportReq",[{no:1,name:"events",kind:"message",repeat:1,T:()=>Sr}])}},Rr=new st,it=class extends C.MessageType{constructor(){super("pulsebeam.v1.AnalyticsEvent",[{no:1,name:"tags",kind:"message",T:()=>yr},{no:2,name:"metrics",kind:"message",repeat:1,T:()=>Tr}])}},Sr=new it,ot=class extends C.MessageType{constructor(){super("pulsebeam.v1.AnalyticsTags",[{no:1,name:"src",kind:"message",T:()=>V},{no:2,name:"dst",kind:"message",T:()=>V}])}},yr=new ot,at=class extends C.MessageType{constructor(){super("pulsebeam.v1.AnalyticsMetrics",[{no:1,name:"timestamp_us",kind:"scalar",T:18,L:0},{no:2,name:"event_type",kind:"enum",opt:!0,T:()=>["pulsebeam.v1.EventType",dt]},{no:3,name:"quality_score",kind:"scalar",opt:!0,T:18,L:0},{no:4,name:"rtt_us",kind:"scalar",opt:!0,T:18,L:0}])}},Tr=new at,ct=class extends C.MessageType{constructor(){super("pulsebeam.v1.AnalyticsReportResp",[])}},_r=new ct,Z=new xt.ServiceType("pulsebeam.v1.Signaling",[{name:"Prepare",options:{},I:er,O:tr},{name:"Send",options:{},I:nr,O:sr},{name:"Recv",serverStreaming:!0,options:{},I:ir,O:or},{name:"AnalyticsReport",options:{},I:Rr,O:_r}]);var j=require("@protobuf-ts/runtime-rpc");var w=class{constructor(t){this._transport=t;m(this,"typeName",Z.typeName);m(this,"methods",Z.methods);m(this,"options",Z.options)}prepare(t,r){let n=this.methods[0],s=this._transport.mergeOptions(r);return(0,j.stackIntercept)("unary",this._transport,n,s,t)}send(t,r){let n=this.methods[1],s=this._transport.mergeOptions(r);return(0,j.stackIntercept)("unary",this._transport,n,s,t)}recv(t,r){let n=this.methods[2],s=this._transport.mergeOptions(r);return(0,j.stackIntercept)("serverStreaming",this._transport,n,s,t)}analyticsReport(t,r){let n=this.methods[3],s=this._transport.mergeOptions(r);return(0,j.stackIntercept)("unary",this._transport,n,s,t)}};function F(e,t){return new Promise(r=>{let n=setTimeout(()=>r(!0),e);t&&t.addEventListener("abort",()=>{clearTimeout(n),r(!1)})})}function ee(...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 P(e,t){let{maxRetries:r,baseDelay:n,maxDelay:s,jitterFactor:i=.3,isRecoverable:a=()=>!0,abortSignal:o}=t,d=0;for(;(d<=r||r<0)&&!o?.aborted;)try{return await e()}catch(c){if(!a(c)||(d++,r>=0&&d>r))throw c;let p=Er(d,n,s,i);await F(p,o).catch(()=>{})}if(o?.aborted)return null;throw new Error("Retry failed: max retries exceeded")}function Er(e,t,r,n){let s=Math.min(t*2**(e-1),r),i=Math.random()*n*s;return s+i}var lt=9e5,Nt=250,ut=1e3,vr=1e3,br=4e3;var Pr=F,Ir=e=>{let t;do{let r=new Uint32Array(1);crypto.getRandomValues(r),t=r[0]}while(t>=0&&t<e);return t},Ar=e=>!0,mt=class{constructor(t){m(this,"map");m(this,"emitted");m(this,"unreliable");m(this,"processing");m(this,"logger");m(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,a]=s;if(!a.header)return;t=a}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()}},te=class{constructor(t,r){this.client=t;this.opts=r;m(this,"info");m(this,"streams");m(this,"abort");m(this,"logger");m(this,"asleep");m(this,"randUint32");m(this,"isRecoverable");m(this,"onstream",t=>{});m(this,"onclosed",t=>{});m(this,"handleControlMessage",t=>{switch(t.payloadType.oneofKind){case"ping":this.logger.debug("received ping");break;default:this.logger.warn("received unknown control message",{payload:t});break}});m(this,"handleMessages",t=>{if(this.logger.debug("received",{msg:t}),this.abort.signal.aborted)return;if(!t.header)return t.payload?this.handleControlMessage(t.payload):void 0;let r=t.header.src,n=t.header.dst;if(!r||!n)return;if(n.connId>=16&&n.connId!=this.info.connId){this.logger.warn("received messages from a stale connection, ignoring",{receivedConnID:n.connId});return}let s=null;for(let i of this.streams)if(r.groupId===i.other.groupId&&r.peerId===i.other.peerId&&r.connId===i.other.connId){s=i;break}if(!s){if(r.peerId==this.info.peerId){this.logger.warn("loopback detected, ignoring messages");return}this.logger.debug(`session not found, creating one for ${r.peerId}:${r.connId}`),s=new ht(this,this.info,r,this.logger),this.streams.push(s),this.onstream(s)}s.enqueue(t)});this.asleep=r.asleep||Pr,this.randUint32=r.randUint32||Ir,this.isRecoverable=r.isRecoverable||Ar,this.info={groupId:r.groupId,peerId:r.peerId,connId:this.randUint32(16)},this.abort=new AbortController,this.logger=r.logger.sub("transport",{info:this.info}),this.streams=[]}async listen(){let t={abort:this.abort.signal,timeout:lt},r={baseDelay:Nt,maxDelay:ut,maxRetries:-1,abortSignal:this.abort.signal,isRecoverable:this.isRecoverable};for(;!this.abort.signal.aborted;)try{await P(async()=>{let n=this.client.recv({src:this.info},t);n.responses.onMessage(s=>!!s.msg&&this.handleMessages(s.msg)),await n},r)}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))}removeStream(t){this.streams=this.streams.filter(r=>r!==t)}async connect(t,r,n){let s={payloadType:{oneofKind:"join",join:{}}},i={src:this.info,dst:{groupId:t,peerId:r,connId:0},seqnum:0,reliable:!1},a=!1,o=ee(n,this.abort.signal);for(;!o.aborted&&!a;)await this.send(o,{header:i,payload:s}),await this.asleep(ut,o).catch(()=>{}),a=!!this.streams.find(d=>d.other.groupId===t&&d.other.peerId===r)}async send(t,r){let n=ee(t,this.abort.signal),s={abort:n,timeout:lt},i={baseDelay:Nt,maxDelay:ut,maxRetries:5,abortSignal:n,isRecoverable:this.isRecoverable};try{if(await P(async()=>await this.client.send({msg:r},s),i)===null){this.logger.warn("aborted, message dropped from sending",{msg:r});return}return}catch(a){this.logger.error("unrecoverable error, force closing",{err:a}),this.close();return}}async reportAnalytics(t){let r={abort:this.abort.signal,timeout:lt},n={baseDelay:vr,maxDelay:br,maxRetries:3,abortSignal:this.abort.signal,isRecoverable:this.isRecoverable};try{await P(async()=>await this.client.analyticsReport(t,r),n)===null&&this.logger.warn("aborted, message dropped from sending analytics",{msg:t})}catch(s){this.logger.error("analytics backend is in unrecoverable state, dropping analytics event",{err:s})}}},ht=class{constructor(t,r,n,s){this.transport=t;this.info=r;this.other=n;m(this,"logger");m(this,"abort");m(this,"recvq");m(this,"lastSeqnum");m(this,"onsignal",async t=>{});m(this,"onclosed",t=>{});this.logger=s.sub("stream",{other:n}),this.abort=new AbortController,this.recvq=new mt(this.logger),this.recvq.onmsg=i=>this.handleMessage(i),this.lastSeqnum=0}createSignal(...t){return ee(this.abort.signal,...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:{src:this.transport.info,dst:this.other,seqnum:this.lastSeqnum,reliable:r},payload:{...t}};this.lastSeqnum++,await this.transport.send(n,s)}async handleMessage(t){if(!t.payload){this.logger.warn("payload is missing from the stream message",{msg:t});return}switch(t.payload.payloadType.oneofKind){case"bye":this.close("received bye",!0);return;case"signal":this.onsignal(t.payload.payloadType.signal);return;case"join":return;default:this.logger.warn("unhandled payload type",{msg:t});return}}async close(t,r){this.abort.signal.aborted||(t=t||"session is closed",r||await this.send({payloadType:{oneofKind:"bye",bye:{}}},!1).catch(n=>this.logger.warn("failed to send bye",{e:n})),this.abort.abort(t),this.transport.removeStream(this),this.onclosed(t),this.logger.debug("sent bye to the other peer",{reason:t}))}};var Dr={DEBUG:console.debug,INFO:console.info,WARN:console.warn,ERROR:console.error},Mt={DEBUG:e=>console.debug(re(e)),INFO:e=>console.info(re(e)),WARN:e=>console.warn(re(e)),ERROR:e=>console.error(re(e))};function Lt(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 a=r+s+i;Lt(e[i],t,a,n)}else{let a=t[r]||[];a.push(`${i}=${e[i]}`),t[r]=a}}}function re(e){let t={};Lt(e,t);let r=[];for(let n in t)r.push(`[${n}] ${t[n].join(" ")}`);return r.join(`
|
36
|
+
`)}var ne=class e{constructor(t,r,n){this.name=t;m(this,"obj");m(this,"sink");r||(r={}),n||(n=Dr),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)}};function Ut(e){let t=e.values(),r,n,s,i;for(let f of t)if(f.type==="inbound-rtp"||f.type==="rtp-receiver"){let g=f;g.kind==="audio"?r=g:n=g}else if(f.type==="candidate-pair"){let g=f;g.state==="succeeded"&&!s&&(s=g.currentRoundTripTime)}else f.type==="peer-connection"?i=f:f.type==="remote-inbound-rtp"&&(s=f.roundTripTime);if(i&&i.iceConnectionState&&!["connected","completed"].includes(i.iceConnectionState))return null;let a={},o=100;if(r){let f=r.packetsLost??0,g=r.packetsReceived??0,R=g>0?f/g:0,S=Math.max(0,100-R*100),I=r.jitter??0,oe=I<.02?100:I<.1?70:30;o=(S+oe)/2}let d=100;if(n){let f=n.packetsLost??0,g=n.packetsReceived??0,R=g>0?f/g:0,S=Math.max(0,100-R*100),I=n.jitter??0,oe=I<.02?100:I<.1?70:30;d=(S+oe)/2}let c=80;s&&(a.rttUs=BigInt(Math.trunc(s*1e6)),c=s<.1?100:s<.3?80:s<.5?60:40);let p=Math.round(d*.5+o*.3+c*.2),h=Math.max(0,Math.min(100,p));return a.qualityScore=BigInt(h),a}function Vt(){return BigInt(Date.now()*1e3)}var kr=1,jt=5e3,Ft="__internal";function Or(e){return{candidate:e.candidate,sdpMid:e.sdpMid,sdpMLineIndex:e.sdpMLineIndex,usernameFragment:e.password}}function Nr(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 Gt(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 se=class{constructor(t,r){this.stream=t;m(this,"pc");m(this,"makingOffer");m(this,"impolite");m(this,"pendingCandidates");m(this,"iceBatcher");m(this,"logger");m(this,"abort");m(this,"generationCounter");m(this,"iceRestartCount");m(this,"lastIceRestart");m(this,"timers");m(this,"_closeReason");m(this,"_connectionState");m(this,"internalDataChannel");m(this,"_metrics");m(this,"ondatachannel",()=>{});m(this,"onconnectionstatechange",()=>{});m(this,"ontrack",()=>{});m(this,"triggerIceRestart",()=>{let t=performance.now()-this.lastIceRestart;if(t<jt){let r=jt-t,n=window.setTimeout(()=>{this.triggerIceRestart(),this.timers=this.timers.filter(s=>s===n)},r);return}if(this.pc.connectionState!=="connected"){if(this.iceRestartCount>=kr){this.close("detected sustained network failure");return}this.logger.debug("triggered ICE restart"),this.pc.restartIce(),this.recordEvent({eventType:3008}),this.generationCounter++,this.iceRestartCount++,this.lastIceRestart=performance.now()}});m(this,"sendSignal",t=>{if(t.data.oneofKind==="sdp"){let r=t.data.sdp.kind;r===1?this.recordEvent({eventType:3002}):r===2&&this.recordEvent({eventType:3005})}this.stream.send({payloadType:{oneofKind:"signal",signal:{...t,generationCounter:this.generationCounter}}},!0)});m(this,"handleSignal",async t=>{if(t.generationCounter<this.generationCounter){this.logger.warn("detected staled generationCounter signals, ignoring");return}this.addCandidates(t);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"){this.logger.warn("expecting an offer but got ice candidates during an ICE restart, adding to pending.",{msg:r});return}this.generationCounter=t.generationCounter}if(r.oneofKind!="sdp")return;let n=r.sdp;this.logger.debug("received a SDP signal",{sdpKind:n.kind}),n.kind===1?this.recordEvent({eventType:3003}):n.kind===2&&this.recordEvent({eventType:3006});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:Nr(n.kind),sdp:n.sdp}),n.kind===1){if(await this.setLocalDescription(),!this.pc.localDescription){this.logger.error("unexpected null local description");return}this.sendSignal({data:{oneofKind:"sdp",sdp:{kind:Gt(this.pc.localDescription.type),sdp:this.pc.localDescription.sdp}}})}this.checkPendingCandidates()});m(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.info.connId===this.stream.other.connId?this.impolite=this.stream.info.peerId>this.stream.other.peerId:this.impolite=this.stream.info.connId>this.stream.other.connId,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",this._metrics=[],this.iceBatcher=new ft(this.logger,100,s=>this.sendLocalIceCandidates(s)),t.onsignal=s=>this.handleSignal(s),t.onclosed=s=>this.close(s),this.pc.oniceconnectionstatechange=async()=>{let s=await this.pc.getStats(),i=[],a=[],o=[];s.forEach(d=>{d.type==="candidate-pair"?i.push(d):d.type==="local-candidate"?a.push(d):d.type==="remote-candidate"&&o.push(d)}),this.logger.debug("iceconnectionstate changed",{connectionstate:this.pc.connectionState,iceconnectionstate:this.pc.iceConnectionState,local:a,remote:o,pair:i,pending:this.pendingCandidates})},this.pc.onsignalingstatechange=()=>{this.checkPendingCandidates()};let n=performance.now();this.pc.onconnectionstatechange=s=>{switch(this.logger.debug("connectionstate changed",{connectionstate:this.pc.connectionState,iceconnectionstate:this.pc.iceConnectionState}),this.setConnectionState(this.pc.connectionState,s),this.pc.connectionState){case"new":break;case"connecting":n=performance.now();break;case"connected":{let i=performance.now()-n;this.logger.debug(`it took ${i}ms to connect`),this.recordEvent({eventType:2011}),this.iceRestartCount=0;break}case"disconnected":break;case"failed":this.recordEvent({eventType:1002}),this.triggerIceRestart();break;case"closed":break}},this.pc.onnegotiationneeded=this.onnegotiationneeded.bind(this),this.pc.onicecandidate=({candidate:s})=>{this.iceBatcher.addCandidate(s)},this.pc.ondatachannel=s=>{s.channel.label!==Ft&&this.ondatachannel&&this.ondatachannel(s)},this.pc.ontrack=s=>{s.track.kind==="audio"?this.recordEvent({eventType:5003}):s.track.kind==="video"&&this.recordEvent({eventType:5004}),this.ontrack&&this.ontrack(s)},this.internalDataChannel=this.pc.createDataChannel(Ft),this.internalDataChannel}addTrack(t,...r){return t.kind==="audio"?this.recordEvent({eventType:5001}):t.kind==="video"&&this.recordEvent({eventType:5002}),this.pc.addTrack(t,...r)}getSenders(){return this.pc.getSenders()}removeTrack(t){return t.track?.kind==="audio"?this.recordEvent({eventType:5005}):t.track?.kind==="video"&&this.recordEvent({eventType:5006}),this.pc.removeTrack(t)}createDataChannel(...t){return this.pc.createDataChannel(...t)}getStats(...t){return this.pc.getStats(...t)}get connectionState(){return this.pc.connectionState}get closeReason(){return this._closeReason}get other(){return{groupId:this.stream.other.groupId,peerId:this.stream.other.peerId,connId:this.stream.other.connId}}close(t){if(this.abort.signal.aborted)return;this.abort.abort(t);for(let n of this.timers)clearTimeout(n);this.timers=[],this.iceBatcher.close(),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,reason:t})}recordEvent(t){let r=Vt();this._metrics.push({...t,timestampUs:r})}async collectMetrics(){let t=await this.getStats(),r=Ut(t);r&&this.recordEvent({qualityScore:r.qualityScore,rttUs:r.rttUs});let n=this._metrics;return this._metrics=[],{tags:{src:this.stream.info,dst:this.other},metrics:n}}async onnegotiationneeded(){try{if(this.recordEvent({eventType:3007}),this.makingOffer=!0,this.logger.debug("creating an offer"),await this.setLocalDescription(),!this.pc.localDescription)throw new Error("expect localDescription to be not empty");this.sendSignal({data:{oneofKind:"sdp",sdp:{kind:Gt(this.pc.localDescription.type),sdp:this.pc.localDescription.sdp}}})}catch(t){t instanceof Error&&this.logger.error("failed in negotiating",{err:t})}finally{this.makingOffer=!1}}sendLocalIceCandidates(t){let r=[];for(let n of t){let s={candidate:"",sdpMLineIndex:0,sdpMid:""};s.candidate=n.candidate,s.sdpMLineIndex=n.sdpMLineIndex??void 0,s.sdpMid=n.sdpMid??void 0,s.username=n.usernameFragment??void 0,r.push(s)}this.sendSignal({data:{oneofKind:"iceCandidateBatch",iceCandidateBatch:{candidates:r}}})}setConnectionState(t,r){t!==this._connectionState&&this.onconnectionstatechange&&this.onconnectionstatechange(r)}async setLocalDescription(){let t=this.pc.getTransceivers();for(let r of t){if(r.receiver.track.kind!=="video")continue;let n=["video/AV1","video/VP9","video/VP8","video/H264"],i=(RTCRtpReceiver.getCapabilities("video")?.codecs||[]).sort((a,o)=>{let d=n.indexOf(a.mimeType),c=n.indexOf(o.mimeType),p=d>=0?d:Number.MAX_VALUE,h=c>=0?c:Number.MAX_VALUE;return p-h});r.setCodecPreferences(i)}for(let r of this.pc.getSenders()){if(r.track?.kind!=="video")continue;let n=r.getParameters();(!n.encodings||n.encodings.length===0)&&(n.encodings=[{}]),n.encodings[0].maxBitrate=400*1e3;try{await r.setParameters(n)}catch(s){this.logger.warn("failed to change max bitrate",{error:s})}}try{await this.pc.setLocalDescription()}catch(r){throw this.recordEvent({eventType:1006}),r}}addCandidates(t){let r=[];if(t.data.oneofKind==="iceCandidate")r.push(t.data.iceCandidate);else if(t.data.oneofKind==="iceCandidateBatch")r.push(...t.data.iceCandidateBatch.candidates);else return;this.pendingCandidates.push(...r.map(n=>Or(n))),this.checkPendingCandidates()}},ft=class{constructor(t,r,n){m(this,"candidates",[]);m(this,"timeoutId",null);m(this,"delayMs");m(this,"logger");m(this,"onIceCandidates");m(this,"addCandidate",t=>{if(!t||t.candidate===""){this.logger.debug("ice gathering is finished, force flush local candidates"),this.flushCandidates();return}this.logger.debug("onicecandidate",{candidate:t}),this.candidates.push(t),this.timeoutId?(clearTimeout(this.timeoutId),this.timeoutId=setTimeout(this.flushCandidates,this.delayMs)):this.timeoutId=setTimeout(this.flushCandidates,this.delayMs)});m(this,"flushCandidates",()=>{this.candidates.length>0&&(this.onIceCandidates(this.candidates),this.candidates=[]),this.timeoutId=null});m(this,"flush",()=>{this.timeoutId&&clearTimeout(this.timeoutId),this.flushCandidates()});m(this,"close",()=>{this.timeoutId&&clearTimeout(this.timeoutId)});this.logger=t.sub("icebatcher"),this.delayMs=r,this.onIceCandidates=n}};var qt=require("@protobuf-ts/runtime-rpc"),y=require("@protobuf-ts/grpcweb-transport");var Bt=require("jwt-decode");var Mr=6e4,Lr="https://cloud.pulsebeam.dev/grpc",ie=class{constructor(t,r,n,s){this.opts=n;m(this,"transport");m(this,"logger");m(this,"_sessions");m(this,"_state");m(this,"onsession",t=>{});m(this,"onstatechange",()=>{});m(this,"peerId");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 te(r,{enableDiscovery:!1,groupId:n.groupId,peerId:n.peerId,logger:this.logger,isRecoverable:s}),this.transport.onstream=a=>{let o=new se(a,i);this._sessions.push(o),this.onsession(o)},this.transport.onclosed=()=>{this.close()}}get sessions(){return this._sessions=this._sessions.filter(t=>t.connectionState!="closed"),[...this._sessions]}start(){if(this._state==="closed")throw new Error("peer is already closed");this.transport.listen()}async analyticsLoop(){for(;this.state!="closed";){let t=[];for(let s of this.sessions){let i=await s.collectMetrics();t.push(i)}let r={events:t};(this.opts.disableAnalytics==null||this.opts.disableAnalytics===!1)&&this.transport.reportAnalytics(r),await F(Mr)}}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())}},Ur=[y.GrpcStatusCode[y.GrpcStatusCode.PERMISSION_DENIED],y.GrpcStatusCode[y.GrpcStatusCode.INVALID_ARGUMENT],y.GrpcStatusCode[y.GrpcStatusCode.ABORTED],y.GrpcStatusCode[y.GrpcStatusCode.NOT_FOUND],y.GrpcStatusCode[y.GrpcStatusCode.UNAUTHENTICATED]];function Kt(e){return e instanceof Error?e instanceof qt.RpcError?!Ur.includes(e.code):!0:!1}async function Vr(e){let t=e.token,r=new y.GrpcWebFetchTransport({baseUrl:e.baseUrl||Lr,sendJson:!1,format:"binary",jsonOptions:{emitDefaultValues:!0,enumAsInteger:!0,ignoreUnknownFields:!0},interceptors:[{interceptUnary(c,p,h,f){return f.meta||(f.meta={}),f.meta.Authorization=`Bearer ${t}`,c(p,h,f)}}]}),n=new w(r),s=await P(async()=>await n.prepare({}),{baseDelay:50,maxDelay:1e3,maxRetries:5,isRecoverable:Kt});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 a=(0,Bt.jwtDecode)(t),o={...e,iceServers:i,groupId:a.gid,peerId:a.pid};return new ie(new ne("pulsebeam",void 0,Mt),n,o,Kt)}var _=require("nanostores");var G=class G{constructor(t){this.peer=t;m(this,"$kv");m(this,"$streams");m(this,"$remotePeers");m(this,"$state");m(this,"$_remotePeers");m(this,"$_state");m(this,"crdtStore");m(this,"replicaId");m(this,"sendChannels");this.crdtStore={},this.$kv=(0,_.map)({}),this.$streams=(0,_.map)({}),this.$_remotePeers=(0,_.map)({}),this.$remotePeers=(0,_.computed)(this.$_remotePeers,r=>r),this.$_state=(0,_.atom)("new"),this.$state=(0,_.computed)(this.$_state,r=>r),this.sendChannels={},this.replicaId=t.peerId,t.onstatechange=()=>{this.$_state.set(t.state)},t.onsession=r=>{let n=`${r.other.groupId}:${r.other.peerId}:${r.other.connId}`;this.sendChannels[n]=r.createDataChannel(G.KV_NAMESPACE,{ordered:!0}),r.ondatachannel=i=>{console.log("debug:ondatachannel",i.channel.label),i.channel.label===G.KV_NAMESPACE&&(i.channel.onmessage=a=>{let o=JSON.parse(a.data);console.log("debug:onmessage",{update:o}),this.receiveUpdate(o.key,o.entry)},i.channel.onopen=a=>{console.log("debug:sync",{crdt:this.crdtStore});for(let[o,d]of Object.entries(this.crdtStore))console.log("debug:notifying",{key:o,entry:d}),this.notifyPeer(this.sendChannels[n],{key:o,entry:d})})},r.ontrack=i=>{let a=this.$_remotePeers.get()[n];for(let o of i.streams){let d=a.streams.findIndex(c=>c.id===o.id);if(o.onremovetrack=c=>{console.log("debug:onremovetrack",c.track);for(let p of a.streams)p.removeTrack(c.track);a.streams=a.streams.filter(p=>p.active),this.$_remotePeers.setKey(n,{...a})},!o.active){d!==-1&&a.streams.splice(d,1);continue}d===-1?a.streams.push(o):a.streams[d]=o}this.$_remotePeers.setKey(n,{...a}),console.log("debug:ontrack",{id:n,streams:a.streams})},r.onconnectionstatechange=i=>{if(r.connectionState==="closed"){let o=this.$_remotePeers.get();delete o[n],delete this.sendChannels[n],console.log(`connection failed, removed ${n}`),this.$_remotePeers.set({...o});return}let a=this.$_remotePeers.get()[n];this.$_remotePeers.setKey(n,{...a,state:r.connectionState})};let s=Object.entries(this.$streams.get());for(let[i,a]of s)if(a){for(let o of a.getTracks())r.addTrack(o,a);console.log("debug:onsession",{_id:i,stream:a})}this.$_remotePeers.setKey(n,{info:r.other,streams:[],state:r.connectionState})},this.$kv.listen((r,n,s)=>{let i=r[s];this.set(s,i)}),this.$streams.listen((r,n,s)=>{console.log("debug:sync_streams",{newStreams:r});for(let i of this.peer.sessions){let a=i.getSenders(),o={},d={};for(let c of a){if(!c.track)continue;let p=o[c.track.id]||[];o[c.track.id]=[...p,c],d[c.track.id]=!0}for(let c of Object.values(r))if(c)for(let p of c.getTracks()){if(p.id in o){d[p.id]=!1;continue}i.addTrack(p,c)}for(let[c,p]of Object.entries(d)){if(!p)continue;let h=o[c];for(let f of h)f.track?.stop(),i.removeTrack(f),console.log("debug:removeTrack",{sender:f})}}}),this.peer.start()}close(){this.peer.close()}mute(t){let r=Object.values(this.$streams.get());for(let n of r)if(n)for(let s of n.getAudioTracks())s.enabled=!t}set(t,r){let n=this.crdtStore[t];if(n&&n.value===r)return;let s=n?{version:n.version+1,replicaId:this.replicaId,value:r}:{version:0,replicaId:this.replicaId,value:r};this.notifyPeers(t,s)}notifyPeer(t,r){t.send(JSON.stringify(r))}notifyPeers(t,r){let n={key:t,entry:r};for(let s of Object.values(this.sendChannels))this.notifyPeer(s,n)}receiveUpdate(t,r){let n=this.crdtStore[t];if(console.log("debug:received_update",{key:t,remoteEntry:r,currentEntry:n}),!n)this.crdtStore[t]=r,this.$kv.setKey(t,r.value),console.log("debug:received_update accepted (resolution=empty)",r);else if(r.version>n.version)this.crdtStore[t]=r,this.$kv.setKey(t,r.value),console.log("debug:received_update accepted (resolution=older)",r);else if(r.version===n.version&&r.replicaId>this.replicaId)this.crdtStore[t]=r,this.$kv.setKey(t,r.value),console.log("debug:received_update accepted (resolution=replicaId)",r);else{console.log("debug:received_update ignored remote update",{remoteEntry:r,currentEntry:n});return}}};m(G,"KV_NAMESPACE","__crdt_kv");var gt=G;U.disableLog(!1);U.disableWarnings(!1);console.log("UA: ",navigator.userAgent);console.log("webrtc-adapter is enabled",JSON.stringify({shim:U.browserShim,version:U.browserDetails},null,2));0&&(module.exports={Peer,PeerStore,createPeer});
|