@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.
@@ -0,0 +1,39 @@
1
+ (function(O,D){typeof exports=="object"&&typeof module<"u"?D(exports):typeof define=="function"&&define.amd?define(["exports"],D):(O=typeof globalThis<"u"?globalThis:O||self,D(O.peer={}))})(this,function(O){"use strict";var hs=Object.defineProperty;var ds=(O,D,G)=>D in O?hs(O,D,{enumerable:!0,configurable:!0,writable:!0,value:G}):O[D]=G;var m=(O,D,G)=>ds(O,typeof D!="symbol"?D+"":D,G);function D(r,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const s in n)if(s!=="default"&&!(s in r)){const i=Object.getOwnPropertyDescriptor(n,s);i&&Object.defineProperty(r,s,i.get?i:{enumerable:!0,get:()=>n[s]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}let G=!0,Ve=!0;function H(r,e,t){const n=r.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function J(r,e,t){if(!r.RTCPeerConnection)return;const n=r.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(o,a){if(o!==e)return s.apply(this,arguments);const c=l=>{const u=t(l);u&&(a.handleEvent?a.handleEvent(u):a(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),s.apply(this,[o,c])};const i=n.removeEventListener;n.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return i.apply(this,arguments);if(!this._eventMap[e].has(a))return i.apply(this,arguments);const c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,i.apply(this,[o,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function sn(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(G=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function on(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ve=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function $e(){if(typeof window=="object"){if(G)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function ge(r,e){Ve&&console.warn(r+" is deprecated, please use "+e+" instead.")}function an(r){const e={browser:null,version:null};if(typeof r>"u"||!r.navigator||!r.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=r;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=H(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=H(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=H(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=r.RTCRtpTransceiver&&"currentDirection"in r.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function we(r){return Object.prototype.toString.call(r)==="[object Object]"}function Ke(r){return we(r)?Object.keys(r).reduce(function(e,t){const n=we(r[t]),s=n?Ke(r[t]):r[t],i=n&&!Object.keys(s).length;return s===void 0||i?e:Object.assign(e,{[t]:s})},{}):r}function ye(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?ye(r,r.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{ye(r,r.get(s),t)})}))}function qe(r,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const i=[];return r.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&i.push(o)}),i.forEach(o=>{r.forEach(a=>{a.type===n&&a.trackId===o.id&&ye(r,a,s)})}),s}const Ge=$e;function Je(r,e){const t=r&&r.navigator;if(!t.mediaDevices)return;const n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const u=typeof a[l]=="object"?a[l]:{ideal:a[l]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const f=function(h,g){return h?h+g.charAt(0).toUpperCase()+g.slice(1):g==="deviceId"?"sourceId":g};if(u.ideal!==void 0){c.optional=c.optional||[];let h={};typeof u.ideal=="number"?(h[f("min",l)]=u.ideal,c.optional.push(h),h={},h[f("max",l)]=u.ideal,c.optional.push(h)):(h[f("",l)]=u.ideal,c.optional.push(h))}u.exact!==void 0&&typeof u.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[f("",l)]=u.exact):["min","max"].forEach(h=>{u[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[f(h,l)]=u[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},s=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const l=function(u,f,h){f in u&&!(h in u)&&(u[h]=u[f],delete u[f])};a=JSON.parse(JSON.stringify(a)),l(a.audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const u=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete a.video.facingMode;let f;if(l.exact==="environment"||l.ideal==="environment"?f=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(f=["front"]),f)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(y=>y.kind==="videoinput");let g=h.find(y=>f.some(v=>y.label.toLowerCase().includes(v)));return!g&&h.length&&f.includes("back")&&(g=h[h.length-1]),g&&(a.video.deviceId=l.exact?{exact:g.deviceId}:{ideal:g.deviceId}),a.video=n(a.video),Ge("chrome: "+JSON.stringify(a)),c(a)})}a.video=n(a.video)}return Ge("chrome: "+JSON.stringify(a)),c(a)},i=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,l){s(a,u=>{t.webkitGetUserMedia(u,c,f=>{l&&l(i(f))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,l=>a(l).then(u=>{if(l.audio&&!u.getAudioTracks().length||l.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(f=>{f.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(i(u))))}}}function Xe(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function ze(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("ontrack"in r.RTCPeerConnection.prototype)){Object.defineProperty(r.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",s=>{let i;r.RTCPeerConnection.prototype.getReceivers?i=this.getReceivers().find(a=>a.track&&a.track.id===s.track.id):i={track:s.track};const o=new Event("track");o.track=s.track,o.receiver=i,o.transceiver={receiver:i},o.streams=[n.stream],this.dispatchEvent(o)}),n.stream.getTracks().forEach(s=>{let i;r.RTCPeerConnection.prototype.getReceivers?i=this.getReceivers().find(a=>a.track&&a.track.id===s.id):i={track:s};const o=new Event("track");o.track=s,o.receiver=i,o.transceiver={receiver:i},o.streams=[n.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else J(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function We(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){const e=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(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(a,c){let l=s.apply(this,arguments);return l||(l=e(this,a),this._senders.push(l)),l};const i=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(a){i.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(i){this._senders=this._senders||[],t.apply(this,[i]),i.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(i){this._senders=this._senders||[],n.apply(this,[i]),i.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof r=="object"&&r.RTCPeerConnection&&"getSenders"in r.RTCPeerConnection.prototype&&"createDTMFSender"in r.RTCPeerConnection.prototype&&r.RTCRtpSender&&!("dtmf"in r.RTCRtpSender.prototype)){const e=r.RTCPeerConnection.prototype.getSenders;r.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n},Object.defineProperty(r.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 Ye(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender&&r.RTCRtpReceiver))return;if(!("getStats"in r.RTCRtpSender.prototype)){const t=r.RTCPeerConnection.prototype.getSenders;t&&(r.RTCPeerConnection.prototype.getSenders=function(){const i=t.apply(this,[]);return i.forEach(o=>o._pc=this),i});const n=r.RTCPeerConnection.prototype.addTrack;n&&(r.RTCPeerConnection.prototype.addTrack=function(){const i=n.apply(this,arguments);return i._pc=this,i}),r.RTCRtpSender.prototype.getStats=function(){const i=this;return this._pc.getStats().then(o=>qe(o,i.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const t=r.RTCPeerConnection.prototype.getReceivers;t&&(r.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(i=>i._pc=this),s}),J(r,"track",n=>(n.receiver._pc=n.srcElement,n)),r.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(i=>qe(i,s.track,!1))}}if(!("getStats"in r.RTCRtpSender.prototype&&"getStats"in r.RTCRtpReceiver.prototype))return;const e=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof r.MediaStreamTrack){const n=arguments[0];let s,i,o;return this.getSenders().forEach(a=>{a.track===n&&(s?o=!0:s=a)}),this.getReceivers().forEach(a=>(a.track===n&&(i?o=!0:i=a),a.track===n)),o||s&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Ze(r){r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(f=>f.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};const s=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),s.apply(this,arguments)}}function He(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Ze(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(f=>this._reverseStreams[f.id])};const n=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(f=>{if(this.getSenders().find(g=>g.track===f))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const f=new r.MediaStream(u.getTracks());this._streams[u.id]=f,this._reverseStreams[f.id]=u,u=f}n.apply(this,[u])};const s=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},r.RTCPeerConnection.prototype.addTrack=function(u,f){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(v=>v===u))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(v=>v.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const y=this._streams[f.id];if(y)y.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new r.MediaStream([u]);this._streams[f.id]=v,this._reverseStreams[v.id]=f,this.addStream(v)}return this.getSenders().find(v=>v.track===u)};function i(l,u){let f=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const g=l._reverseStreams[h],y=l._streams[g.id];f=f.replace(new RegExp(y.id,"g"),g.id)}),new RTCSessionDescription({type:u.type,sdp:f})}function o(l,u){let f=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const g=l._reverseStreams[h],y=l._streams[g.id];f=f.replace(new RegExp(g.id,"g"),y.id)}),new RTCSessionDescription({type:u.type,sdp:f})}["createOffer","createAnswer"].forEach(function(l){const u=r.RTCPeerConnection.prototype[l],f={[l](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[y=>{const v=i(this,y);h[0].apply(null,[v])},y=>{h[1]&&h[1].apply(null,y)},arguments[2]]):u.apply(this,arguments).then(y=>i(this,y))}};r.RTCPeerConnection.prototype[l]=f[l]});const a=r.RTCPeerConnection.prototype.setLocalDescription;r.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:i(this,l)}}),r.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(g=>{this._streams[g].getTracks().find(v=>u.track===v)&&(h=this._streams[g])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function be(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=r.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=s[t]})}function Qe(r,e){J(r,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}const et=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:Qe,shimAddTrackRemoveTrack:He,shimAddTrackRemoveTrackWithNative:Ze,shimGetSendersWithDtmf:We,shimGetUserMedia:Je,shimMediaStream:Xe,shimOnTrack:ze,shimPeerConnection:be,shimSenderReceiverGetStats:Ye},Symbol.toStringTag,{value:"Module"}));function tt(r,e){const t=r&&r.navigator,n=r&&r.MediaStreamTrack;if(t.getUserMedia=function(s,i,o){ge("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(i,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},i=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),i(o)},n&&n.prototype.getSettings){const o=n.prototype.getSettings;n.prototype.getSettings=function(){const a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){const o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function cn(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const 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:e}:n.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(n)})}function nt(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Te(r,e){if(typeof r!="object"||!(r.RTCPeerConnection||r.mozRTCPeerConnection))return;!r.RTCPeerConnection&&r.mozRTCPeerConnection&&(r.RTCPeerConnection=r.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const i=r.RTCPeerConnection.prototype[s],o={[s](){return arguments[0]=new(s==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};r.RTCPeerConnection.prototype[s]=o[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){const[i,o,a]=arguments;return n.apply(this,[i||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(l=>{l.type=t[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((u,f)=>{c.set(f,Object.assign({},u,{type:t[u.type]||u.type}))})}return c}).then(o,a)}}function rt(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpSender.prototype)return;const e=r.RTCPeerConnection.prototype.getSenders;e&&(r.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(i=>i._pc=this),s});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function st(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpReceiver.prototype)return;const e=r.RTCPeerConnection.prototype.getReceivers;e&&(r.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n}),J(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function it(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){ge("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function ot(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function at(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.addTransceiver;e&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const s=n.length>0;s&&n.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const i=e.apply(this,arguments);if(s){const{sender:o}=i,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=n,o.sendEncodings=n,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return i})}function ct(r){if(!(typeof r=="object"&&r.RTCRtpSender))return;const e=r.RTCRtpSender.prototype.getParameters;e&&(r.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function lt(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function ut(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.createAnswer;r.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}const ft=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:at,shimCreateAnswer:ut,shimCreateOffer:lt,shimGetDisplayMedia:cn,shimGetParameters:ct,shimGetUserMedia:tt,shimOnTrack:nt,shimPeerConnection:Te,shimRTCDataChannel:ot,shimReceiverGetStats:st,shimRemoveStream:it,shimSenderGetStats:rt},Symbol.toStringTag,{value:"Module"}));function ht(r){if(!(typeof r!="object"||!r.RTCPeerConnection)){if("getLocalStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in r.RTCPeerConnection.prototype)){const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(s=>e.call(this,s,n)),n.getVideoTracks().forEach(s=>e.call(this,s,n))},r.RTCPeerConnection.prototype.addTrack=function(n,...s){return s&&s.forEach(i=>{this._localStreams?this._localStreams.includes(i)||this._localStreams.push(i):this._localStreams=[i]}),e.apply(this,arguments)}}"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const s=t.getTracks();this.getSenders().forEach(i=>{s.includes(i.track)&&this.removeTrack(i)})})}}function dt(r){if(!(typeof r!="object"||!r.RTCPeerConnection)&&("getRemoteStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in r.RTCPeerConnection.prototype))){Object.defineProperty(r.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const i=new Event("addstream");i.stream=s,this.dispatchEvent(i)})})}});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const 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);const o=new Event("addstream");o.stream=i,n.dispatchEvent(o)})}),e.apply(n,arguments)}}}function pt(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,s=e.setLocalDescription,i=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(l,u){const f=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[f]);return u?(h.then(l,u),Promise.resolve()):h},e.createAnswer=function(l,u){const f=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[f]);return u?(h.then(l,u),Promise.resolve()):h};let a=function(c,l,u){const f=s.apply(this,[c]);return u?(f.then(l,u),Promise.resolve()):f};e.setLocalDescription=a,a=function(c,l,u){const f=i.apply(this,[c]);return u?(f.then(l,u),Promise.resolve()):f},e.setRemoteDescription=a,a=function(c,l,u){const f=o.apply(this,[c]);return u?(f.then(l,u),Promise.resolve()):f},e.addIceCandidate=a}function mt(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>n(gt(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,i){e.mediaDevices.getUserMedia(n).then(s,i)}).bind(e))}function gt(r){return r&&r.video!==void 0?Object.assign({},r,{video:Ke(r.video)}):r}function yt(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(n,s){if(n&&n.iceServers){const i=[];for(let o=0;o<n.iceServers.length;o++){let a=n.iceServers[o];a.urls===void 0&&a.url?(ge("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,i.push(a)):i.push(n.iceServers[o])}n.iceServers=i}return new e(n,s)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function bt(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Tt(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const i=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):n.offerToReceiveVideo===!0&&!i&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Ct(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const St=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:Ct,shimCallbacksAPI:pt,shimConstraints:gt,shimCreateOfferLegacy:Tt,shimGetUserMedia:mt,shimLocalStreamsAPI:ht,shimRTCIceServerUrls:yt,shimRemoteStreamsAPI:dt,shimTrackEventTransceiver:bt},Symbol.toStringTag,{value:"Module"}));function ln(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ce={exports:{}},Rt;function un(){return Rt||(Rt=1,function(r){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
2
+ `).map(n=>n.trim())},e.splitSections=function(t){return t.split(`
3
+ m=`).map((s,i)=>(i>0?"m="+s:s).trim()+`\r
4
+ `)},e.getDescription=function(t){const n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){const n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(s=>s.indexOf(n)===0)},e.parseCandidate=function(t){let n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");const s={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let i=8;i<n.length;i+=2)switch(n[i]){case"raddr":s.relatedAddress=n[i+1];break;case"rport":s.relatedPort=parseInt(n[i+1],10);break;case"tcptype":s.tcpType=n[i+1];break;case"ufrag":s.ufrag=n[i+1],s.usernameFragment=n[i+1];break;default:s[n[i]]===void 0&&(s[n[i]]=n[i+1]);break}return s},e.writeCandidate=function(t){const n=[];n.push(t.foundation);const s=t.component;s==="rtp"?n.push(1):s==="rtcp"?n.push(2):n.push(s),n.push(t.protocol.toUpperCase()),n.push(t.priority),n.push(t.address||t.ip),n.push(t.port);const i=t.type;return n.push("typ"),n.push(i),i!=="host"&&t.relatedAddress&&t.relatedPort&&(n.push("raddr"),n.push(t.relatedAddress),n.push("rport"),n.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(n.push("tcptype"),n.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(n.push("ufrag"),n.push(t.usernameFragment||t.ufrag)),"candidate:"+n.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let n=t.substring(9).split(" ");const s={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),s.name=n[0],s.clockRate=parseInt(n[1],10),s.channels=n.length===3?parseInt(n[2],10):1,s.numChannels=s.channels,s},e.writeRtpMap=function(t){let n=t.payloadType;t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType);const s=t.channels||t.numChannels||1;return"a=rtpmap:"+n+" "+t.name+"/"+t.clockRate+(s!==1?"/"+s:"")+`\r
5
+ `},e.parseExtmap=function(t){const n=t.substring(9).split(" ");return{id:parseInt(n[0],10),direction:n[0].indexOf("/")>0?n[0].split("/")[1]:"sendrecv",uri:n[1],attributes:n.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
6
+ `},e.parseFmtp=function(t){const n={};let s;const i=t.substring(t.indexOf(" ")+1).split(";");for(let o=0;o<i.length;o++)s=i[o].trim().split("="),n[s[0].trim()]=s[1];return n},e.writeFmtp=function(t){let n="",s=t.payloadType;if(t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const i=[];Object.keys(t.parameters).forEach(o=>{t.parameters[o]!==void 0?i.push(o+"="+t.parameters[o]):i.push(o)}),n+="a=fmtp:"+s+" "+i.join(";")+`\r
7
+ `}return n},e.parseRtcpFb=function(t){const n=t.substring(t.indexOf(" ")+1).split(" ");return{type:n.shift(),parameter:n.join(" ")}},e.writeRtcpFb=function(t){let n="",s=t.payloadType;return t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(i=>{n+="a=rtcp-fb:"+s+" "+i.type+(i.parameter&&i.parameter.length?" "+i.parameter:"")+`\r
8
+ `}),n},e.parseSsrcMedia=function(t){const n=t.indexOf(" "),s={ssrc:parseInt(t.substring(7,n),10)},i=t.indexOf(":",n);return i>-1?(s.attribute=t.substring(n+1,i),s.value=t.substring(i+1)):s.attribute=t.substring(n+1),s},e.parseSsrcGroup=function(t){const n=t.substring(13).split(" ");return{semantics:n.shift(),ssrcs:n.map(s=>parseInt(s,10))}},e.getMid=function(t){const n=e.matchPrefix(t,"a=mid:")[0];if(n)return n.substring(6)},e.parseFingerprint=function(t){const n=t.substring(14).split(" ");return{algorithm:n[0].toLowerCase(),value:n[1].toUpperCase()}},e.getDtlsParameters=function(t,n){return{role:"auto",fingerprints:e.matchPrefix(t+n,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,n){let s="a=setup:"+n+`\r
9
+ `;return t.fingerprints.forEach(i=>{s+="a=fingerprint:"+i.algorithm+" "+i.value+`\r
10
+ `}),s},e.parseCryptoLine=function(t){const n=t.substring(9).split(" ");return{tag:parseInt(n[0],10),cryptoSuite:n[1],keyParams:n[2],sessionParams:n.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
11
+ `},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const n=t.substring(7).split("|");return{keyMethod:"inline",keySalt:n[0],lifeTime:n[1],mkiValue:n[2]?n[2].split(":")[0]:void 0,mkiLength:n[2]?n[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,n){return e.matchPrefix(t+n,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,n){const s=e.matchPrefix(t+n,"a=ice-ufrag:")[0],i=e.matchPrefix(t+n,"a=ice-pwd:")[0];return s&&i?{usernameFragment:s.substring(12),password:i.substring(10)}:null},e.writeIceParameters=function(t){let n="a=ice-ufrag:"+t.usernameFragment+`\r
12
+ a=ice-pwd:`+t.password+`\r
13
+ `;return t.iceLite&&(n+=`a=ice-lite\r
14
+ `),n},e.parseRtpParameters=function(t){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=e.splitLines(t)[0].split(" ");n.profile=i[2];for(let a=3;a<i.length;a++){const c=i[a],l=e.matchPrefix(t,"a=rtpmap:"+c+" ")[0];if(l){const u=e.parseRtpMap(l),f=e.matchPrefix(t,"a=fmtp:"+c+" ");switch(u.parameters=f.length?e.parseFmtp(f[0]):{},u.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+c+" ").map(e.parseRtcpFb),n.codecs.push(u),u.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(u.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(a=>{n.headerExtensions.push(e.parseExtmap(a))});const o=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return n.codecs.forEach(a=>{o.forEach(c=>{a.rtcpFeedback.find(u=>u.type===c.type&&u.parameter===c.parameter)||a.rtcpFeedback.push(c)})}),n},e.writeRtpDescription=function(t,n){let s="";s+="m="+t+" ",s+=n.codecs.length>0?"9":"0",s+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",s+=n.codecs.map(o=>o.preferredPayloadType!==void 0?o.preferredPayloadType:o.payloadType).join(" ")+`\r
15
+ `,s+=`c=IN IP4 0.0.0.0\r
16
+ `,s+=`a=rtcp:9 IN IP4 0.0.0.0\r
17
+ `,n.codecs.forEach(o=>{s+=e.writeRtpMap(o),s+=e.writeFmtp(o),s+=e.writeRtcpFb(o)});let i=0;return n.codecs.forEach(o=>{o.maxptime>i&&(i=o.maxptime)}),i>0&&(s+="a=maxptime:"+i+`\r
18
+ `),n.headerExtensions&&n.headerExtensions.forEach(o=>{s+=e.writeExtmap(o)}),s},e.parseRtpEncodingParameters=function(t){const n=[],s=e.parseRtpParameters(t),i=s.fecMechanisms.indexOf("RED")!==-1,o=s.fecMechanisms.indexOf("ULPFEC")!==-1,a=e.matchPrefix(t,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),c=a.length>0&&a[0].ssrc;let l;const u=e.matchPrefix(t,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(y=>parseInt(y,10)));u.length>0&&u[0].length>1&&u[0][0]===c&&(l=u[0][1]),s.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let g={ssrc:c,codecPayloadType:parseInt(h.parameters.apt,10)};c&&l&&(g.rtx={ssrc:l}),n.push(g),i&&(g=JSON.parse(JSON.stringify(g)),g.fec={ssrc:c,mechanism:o?"red+ulpfec":"red"},n.push(g))}}),n.length===0&&c&&n.push({ssrc:c});let f=e.matchPrefix(t,"b=");return f.length&&(f[0].indexOf("b=TIAS:")===0?f=parseInt(f[0].substring(7),10):f[0].indexOf("b=AS:")===0?f=parseInt(f[0].substring(5),10)*1e3*.95-50*40*8:f=void 0,n.forEach(h=>{h.maxBitrate=f})),n},e.parseRtcpParameters=function(t){const n={},s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="cname")[0];s&&(n.cname=s.value,n.ssrc=s.ssrc);const i=e.matchPrefix(t,"a=rtcp-rsize");n.reducedSize=i.length>0,n.compound=i.length===0;const o=e.matchPrefix(t,"a=rtcp-mux");return n.mux=o.length>0,n},e.writeRtcpParameters=function(t){let n="";return t.reducedSize&&(n+=`a=rtcp-rsize\r
19
+ `),t.mux&&(n+=`a=rtcp-mux\r
20
+ `),t.ssrc!==void 0&&t.cname&&(n+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
21
+ `),n},e.parseMsid=function(t){let n;const s=e.matchPrefix(t,"a=msid:");if(s.length===1)return n=s[0].substring(7).split(" "),{stream:n[0],track:n[1]};const i=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="msid");if(i.length>0)return n=i[0].value.split(" "),{stream:n[0],track:n[1]}},e.parseSctpDescription=function(t){const n=e.parseMLine(t),s=e.matchPrefix(t,"a=max-message-size:");let i;s.length>0&&(i=parseInt(s[0].substring(19),10)),isNaN(i)&&(i=65536);const o=e.matchPrefix(t,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:n.fmt,maxMessageSize:i};const a=e.matchPrefix(t,"a=sctpmap:");if(a.length>0){const c=a[0].substring(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:i}}},e.writeSctpDescription=function(t,n){let s=[];return t.protocol!=="DTLS/SCTP"?s=["m="+t.kind+" 9 "+t.protocol+" "+n.protocol+`\r
22
+ `,`c=IN IP4 0.0.0.0\r
23
+ `,"a=sctp-port:"+n.port+`\r
24
+ `]:s=["m="+t.kind+" 9 "+t.protocol+" "+n.port+`\r
25
+ `,`c=IN IP4 0.0.0.0\r
26
+ `,"a=sctpmap:"+n.port+" "+n.protocol+` 65535\r
27
+ `],n.maxMessageSize!==void 0&&s.push("a=max-message-size:"+n.maxMessageSize+`\r
28
+ `),s.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,n,s){let i;const o=n!==void 0?n:2;return t?i=t:i=e.generateSessionId(),`v=0\r
29
+ o=`+(s||"thisisadapterortc")+" "+i+" "+o+` IN IP4 127.0.0.1\r
30
+ s=-\r
31
+ t=0 0\r
32
+ `},e.getDirection=function(t,n){const s=e.splitLines(t);for(let i=0;i<s.length;i++)switch(s[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[i].substring(2)}return n?e.getDirection(n):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let s=0;s<n.length;s++)if(n[s].length<2||n[s].charAt(1)!=="=")return!1;return!0},r.exports=e}(Ce)),Ce.exports}var vt=un();const z=ln(vt),fn=D({__proto__:null,default:z},[vt]);function Q(r){if(!r.RTCIceCandidate||r.RTCIceCandidate&&"foundation"in r.RTCIceCandidate.prototype)return;const e=r.RTCIceCandidate;r.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){const s=new e(n),i=z.parseCandidate(n.candidate);for(const o in i)o in s||Object.defineProperty(s,o,{value:i[o]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(n)},r.RTCIceCandidate.prototype=e.prototype,J(r,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new r.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Se(r){!r.RTCIceCandidate||r.RTCIceCandidate&&"relayProtocol"in r.RTCIceCandidate.prototype||J(r,"icecandidate",e=>{if(e.candidate){const t=z.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function ee(r,e){if(!r.RTCPeerConnection)return;"sctp"in r.RTCPeerConnection.prototype||Object.defineProperty(r.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(a){if(!a||!a.sdp)return!1;const c=z.splitSections(a.sdp);return c.shift(),c.some(l=>{const u=z.parseMLine(l);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},n=function(a){const c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const l=parseInt(c[1],10);return l!==l?-1:l},s=function(a){let c=65536;return e.browser==="firefox"&&(e.version<57?a===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},i=function(a,c){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);const u=z.matchPrefix(a.sdp,"a=max-message-size:");return u.length>0?l=parseInt(u[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(l=2147483637),l},o=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const c=n(arguments[0]),l=s(c),u=i(arguments[0],c);let f;l===0&&u===0?f=Number.POSITIVE_INFINITY:l===0||u===0?f=Math.max(l,u):f=Math.min(l,u);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return f}}),this._sctp=h}return o.apply(this,arguments)}}function te(r){if(!(r.RTCPeerConnection&&"createDataChannel"in r.RTCPeerConnection.prototype))return;function e(n,s){const i=n.send;n.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(n.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return i.apply(n,arguments)}}const t=r.RTCPeerConnection.prototype.createDataChannel;r.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},J(r,"datachannel",n=>(e(n.channel,n.target),n))}function Re(r){if(!r.RTCPeerConnection||"connectionState"in r.RTCPeerConnection.prototype)return;const e=r.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const i=s.target;if(i._lastConnectionState!==i.connectionState){i._lastConnectionState=i.connectionState;const o=new Event("connectionstatechange",s);i.dispatchEvent(o)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function ve(r,e){if(!r.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
33
+ a=extmap-allow-mixed`)!==-1){const i=s.sdp.split(`
34
+ `).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
35
+ `);r.RTCSessionDescription&&s instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:s.type,sdp:i}):s.sdp=i}return t.apply(this,arguments)}}function ne(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(r.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function re(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(r.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.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"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}const hn=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:ve,shimAddIceCandidateNullOrEmpty:ne,shimConnectionState:Re,shimMaxMessageSize:ee,shimParameterlessSetLocalDescription:re,shimRTCIceCandidate:Q,shimRTCIceCandidateRelayProtocol:Se,shimSendThrowTypeError:te},Symbol.toStringTag,{value:"Module"}));function dn({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=$e,n=an(r),s={browserDetails:n,commonShim:hn,extractVersion:H,disableLog:sn,disableWarnings:on,sdp:fn};switch(n.browser){case"chrome":if(!et||!be||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=et,ne(r,n),re(r),Je(r,n),Xe(r),be(r,n),ze(r),He(r,n),We(r),Ye(r),Qe(r,n),Q(r),Se(r),Re(r),ee(r,n),te(r),ve(r,n);break;case"firefox":if(!ft||!Te||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=ft,ne(r,n),re(r),tt(r,n),Te(r,n),nt(r),it(r),rt(r),st(r),ot(r),at(r),ct(r),lt(r),ut(r),Q(r),Re(r),ee(r,n),te(r);break;case"safari":if(!St||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=St,ne(r,n),re(r),yt(r),Tt(r),pt(r),ht(r),dt(r),bt(r),mt(r),Ct(r),Q(r),Se(r),ee(r,n),te(r),ve(r,n);break;default:t("Unsupported browser!");break}return s}const se=dn({window:typeof window>"u"?void 0:window});function Et(r){let e=typeof r;if(e=="object"){if(Array.isArray(r))return"array";if(r===null)return"null"}return e}function pn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}let $="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ie=[];for(let r=0;r<$.length;r++)ie[$[r].charCodeAt(0)]=r;ie[45]=$.indexOf("+"),ie[95]=$.indexOf("/");function It(r){let e=r.length*3/4;r[r.length-2]=="="?e-=2:r[r.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,s=0,i,o=0;for(let a=0;a<r.length;a++){if(i=ie[r.charCodeAt(a)],i===void 0)switch(r[a]){case"=":s=0;case`
36
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=i,s=1;break;case 1:t[n++]=o<<2|(i&48)>>4,o=i,s=2;break;case 2:t[n++]=(o&15)<<4|(i&60)>>2,o=i,s=3;break;case 3:t[n++]=(o&3)<<6|i,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,n)}function kt(r){let e="",t=0,n,s=0;for(let i=0;i<r.length;i++)switch(n=r[i],t){case 0:e+=$[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=$[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=$[s|n>>6],e+=$[n&63],t=0;break}return t&&(e+=$[s],e+="=",t==1&&(e+="=")),e}var oe;(function(r){r.symbol=Symbol.for("protobuf-ts/unknown"),r.onRead=(t,n,s,i,o)=>{(e(n)?n[r.symbol]:n[r.symbol]=[]).push({no:s,wireType:i,data:o})},r.onWrite=(t,n,s)=>{for(let{no:i,wireType:o,data:a}of r.list(n))s.tag(i,o).raw(a)},r.list=(t,n)=>{if(e(t)){let s=t[r.symbol];return n?s.filter(i=>i.no==n):s}return[]},r.last=(t,n)=>r.list(t,n).slice(-1)[0];const e=t=>t&&Array.isArray(t[r.symbol])})(oe||(oe={}));function mn(r,e){return Object.assign(Object.assign({},r),e)}var k;(function(r){r[r.Varint=0]="Varint",r[r.Bit64=1]="Bit64",r[r.LengthDelimited=2]="LengthDelimited",r[r.StartGroup=3]="StartGroup",r[r.EndGroup=4]="EndGroup",r[r.Bit32=5]="Bit32"})(k||(k={}));function gn(){let r=0,e=0;for(let n=0;n<28;n+=7){let s=this.buf[this.pos++];if(r|=(s&127)<<n,(s&128)==0)return this.assertBounds(),[r,e]}let t=this.buf[this.pos++];if(r|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[r,e];for(let n=3;n<=31;n+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<n,(s&128)==0)return this.assertBounds(),[r,e]}throw new Error("invalid varint")}function Ee(r,e,t){for(let i=0;i<28;i=i+7){const o=r>>>i,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(t.push(c),!a)return}const n=r>>>28&15|(e&7)<<4,s=e>>3!=0;if(t.push((s?n|128:n)&255),!!s){for(let i=3;i<31;i=i+7){const o=e>>>i,a=!!(o>>>7),c=(a?o|128:o)&255;if(t.push(c),!a)return}t.push(e>>>31&1)}}const ae=65536*65536;function Nt(r){let e=r[0]=="-";e&&(r=r.slice(1));const t=1e6;let n=0,s=0;function i(o,a){const c=Number(r.slice(o,a));s*=t,n=n*t+c,n>=ae&&(s=s+(n/ae|0),n=n%ae)}return i(-24,-18),i(-18,-12),i(-12,-6),i(-6),[e,n,s]}function Ie(r,e){if(e>>>0<=2097151)return""+(ae*e+(r>>>0));let t=r&16777215,n=(r>>>24|e<<8)>>>0&16777215,s=e>>16&65535,i=t+n*6777216+s*6710656,o=n+s*8147497,a=s*2,c=1e7;i>=c&&(o+=Math.floor(i/c),i%=c),o>=c&&(a+=Math.floor(o/c),o%=c);function l(u,f){let h=u?String(u):"";return f?"0000000".slice(h.length)+h:h}return l(a,0)+l(o,a)+l(i,1)}function _t(r,e){if(r>=0){for(;r>127;)e.push(r&127|128),r=r>>>7;e.push(r)}else{for(let t=0;t<9;t++)e.push(r&127|128),r=r>>7;e.push(1)}}function yn(){let r=this.buf[this.pos++],e=r&127;if((r&128)==0)return this.assertBounds(),e;if(r=this.buf[this.pos++],e|=(r&127)<<7,(r&128)==0)return this.assertBounds(),e;if(r=this.buf[this.pos++],e|=(r&127)<<14,(r&128)==0)return this.assertBounds(),e;if(r=this.buf[this.pos++],e|=(r&127)<<21,(r&128)==0)return this.assertBounds(),e;r=this.buf[this.pos++],e|=(r&15)<<28;for(let t=5;(r&128)!==0&&t<10;t++)r=this.buf[this.pos++];if((r&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}let R;function bn(){const r=new DataView(new ArrayBuffer(8));R=globalThis.BigInt!==void 0&&typeof r.getBigInt64=="function"&&typeof r.getBigUint64=="function"&&typeof r.setBigInt64=="function"&&typeof r.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:r}:void 0}bn();function Pt(r){if(!r)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const Ot=/^-?[0-9]+$/,ce=4294967296,le=2147483648;class Dt{constructor(e,t){this.lo=e|0,this.hi=t|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*ce+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class P extends Dt{static from(e){if(R)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=R.C(e);case"number":if(e===0)return this.ZERO;e=R.C(e);case"bigint":if(!e)return this.ZERO;if(e<R.UMIN)throw new Error("signed value for ulong");if(e>R.UMAX)throw new Error("ulong too large");return R.V.setBigUint64(0,e,!0),new P(R.V.getInt32(0,!0),R.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!Ot.test(e))throw new Error("string is no integer");let[t,n,s]=Nt(e);if(t)throw new Error("signed value for ulong");return new P(n,s);case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");if(e<0)throw new Error("signed value for ulong");return new P(e,e/ce)}throw new Error("unknown value "+typeof e)}toString(){return R?this.toBigInt().toString():Ie(this.lo,this.hi)}toBigInt(){return Pt(R),R.V.setInt32(0,this.lo,!0),R.V.setInt32(4,this.hi,!0),R.V.getBigUint64(0,!0)}}P.ZERO=new P(0,0);class N extends Dt{static from(e){if(R)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=R.C(e);case"number":if(e===0)return this.ZERO;e=R.C(e);case"bigint":if(!e)return this.ZERO;if(e<R.MIN)throw new Error("signed long too small");if(e>R.MAX)throw new Error("signed long too large");return R.V.setBigInt64(0,e,!0),new N(R.V.getInt32(0,!0),R.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!Ot.test(e))throw new Error("string is no integer");let[t,n,s]=Nt(e);if(t){if(s>le||s==le&&n!=0)throw new Error("signed long too small")}else if(s>=le)throw new Error("signed long too large");let i=new N(n,s);return t?i.negate():i;case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new N(e,e/ce):new N(-e,-e/ce).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&le)!==0}negate(){let e=~this.hi,t=this.lo;return t?t=~t+1:e+=1,new N(t,e)}toString(){if(R)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+Ie(e.lo,e.hi)}return Ie(this.lo,this.hi)}toBigInt(){return Pt(R),R.V.setInt32(0,this.lo,!0),R.V.setInt32(4,this.hi,!0),R.V.getBigInt64(0,!0)}}N.ZERO=new N(0,0);const At={readUnknownField:!0,readerFactory:r=>new Cn(r)};function Tn(r){return r?Object.assign(Object.assign({},At),r):At}class Cn{constructor(e,t){this.varint64=gn,this.uint32=yn,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e){let t=this.pos;switch(e){case k.Varint:for(;this.buf[this.pos++]&128;);break;case k.Bit64:this.pos+=4;case k.Bit32:this.pos+=4;break;case k.LengthDelimited:let n=this.uint32();this.pos+=n;break;case k.StartGroup:let s;for(;(s=this.tag()[1])!==k.EndGroup;)this.skip(s);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return new N(...this.varint64())}uint64(){return new P(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,new N(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new P(this.sfixed32(),this.sfixed32())}sfixed64(){return new N(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function T(r,e){if(!r)throw new Error(e)}function Sn(r,e){throw new Error("Unexpected object: "+r)}const Rn=34028234663852886e22,vn=-34028234663852886e22,En=4294967295,In=2147483647,kn=-2147483648;function W(r){if(typeof r!="number")throw new Error("invalid int 32: "+typeof r);if(!Number.isInteger(r)||r>In||r<kn)throw new Error("invalid int 32: "+r)}function ue(r){if(typeof r!="number")throw new Error("invalid uint 32: "+typeof r);if(!Number.isInteger(r)||r>En||r<0)throw new Error("invalid uint 32: "+r)}function ke(r){if(typeof r!="number")throw new Error("invalid float 32: "+typeof r);if(Number.isFinite(r)&&(r>Rn||r<vn))throw new Error("invalid float 32: "+r)}const xt={writeUnknownFields:!0,writerFactory:()=>new _n};function Nn(r){return r?Object.assign(Object.assign({},xt),r):xt}class _n{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),n=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],n),n+=this.chunks[s].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(ue(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return W(e),_t(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){ke(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){ue(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){W(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return W(e),e=(e<<1^e>>31)>>>0,_t(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=N.from(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=P.from(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=N.from(e);return Ee(t.lo,t.hi,this.buf),this}sint64(e){let t=N.from(e),n=t.hi>>31,s=t.lo<<1^n,i=(t.hi<<1|t.lo>>>31)^n;return Ee(s,i,this.buf),this}uint64(e){let t=P.from(e);return Ee(t.lo,t.hi,this.buf),this}}const Lt={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Mt={ignoreUnknownFields:!1};function Pn(r){return r?Object.assign(Object.assign({},Mt),r):Mt}function On(r){return r?Object.assign(Object.assign({},Lt),r):Lt}function Dn(r,e){var t,n;let s=Object.assign(Object.assign({},r),e);return s.typeRegistry=[...(t=r==null?void 0:r.typeRegistry)!==null&&t!==void 0?t:[],...(n=e==null?void 0:e.typeRegistry)!==null&&n!==void 0?n:[]],s}const Ft=Symbol.for("protobuf-ts/message-type");function Ne(r){let e=!1;const t=[];for(let n=0;n<r.length;n++){let s=r.charAt(n);s=="_"?e=!0:/\d/.test(s)?(t.push(s),e=!0):e?(t.push(s.toUpperCase()),e=!1):n==0?t.push(s.toLowerCase()):t.push(s)}return t.join("")}var d;(function(r){r[r.DOUBLE=1]="DOUBLE",r[r.FLOAT=2]="FLOAT",r[r.INT64=3]="INT64",r[r.UINT64=4]="UINT64",r[r.INT32=5]="INT32",r[r.FIXED64=6]="FIXED64",r[r.FIXED32=7]="FIXED32",r[r.BOOL=8]="BOOL",r[r.STRING=9]="STRING",r[r.BYTES=12]="BYTES",r[r.UINT32=13]="UINT32",r[r.SFIXED32=15]="SFIXED32",r[r.SFIXED64=16]="SFIXED64",r[r.SINT32=17]="SINT32",r[r.SINT64=18]="SINT64"})(d||(d={}));var B;(function(r){r[r.BIGINT=0]="BIGINT",r[r.STRING=1]="STRING",r[r.NUMBER=2]="NUMBER"})(B||(B={}));var fe;(function(r){r[r.NO=0]="NO",r[r.PACKED=1]="PACKED",r[r.UNPACKED=2]="UNPACKED"})(fe||(fe={}));function An(r){var e,t,n,s;return r.localName=(e=r.localName)!==null&&e!==void 0?e:Ne(r.name),r.jsonName=(t=r.jsonName)!==null&&t!==void 0?t:Ne(r.name),r.repeat=(n=r.repeat)!==null&&n!==void 0?n:fe.NO,r.opt=(s=r.opt)!==null&&s!==void 0?s:r.repeat||r.oneof?!1:r.kind=="message",r}function xn(r){if(typeof r!="object"||r===null||!r.hasOwnProperty("oneofKind"))return!1;switch(typeof r.oneofKind){case"string":return r[r.oneofKind]===void 0?!1:Object.keys(r).length==2;case"undefined":return Object.keys(r).length==1;default:return!1}}class Ln{constructor(e){var t;this.fields=(t=e.fields)!==null&&t!==void 0?t:[]}prepare(){if(this.data)return;const e=[],t=[],n=[];for(let s of this.fields)if(s.oneof)n.includes(s.oneof)||(n.push(s.oneof),e.push(s.oneof),t.push(s.oneof));else switch(t.push(s.localName),s.kind){case"scalar":case"enum":(!s.opt||s.repeat)&&e.push(s.localName);break;case"message":s.repeat&&e.push(s.localName);break;case"map":e.push(s.localName);break}this.data={req:e,known:t,oneofs:Object.values(n)}}is(e,t,n=!1){if(t<0)return!0;if(e==null||typeof e!="object")return!1;this.prepare();let s=Object.keys(e),i=this.data;if(s.length<i.req.length||i.req.some(o=>!s.includes(o))||!n&&s.some(o=>!i.known.includes(o)))return!1;if(t<1)return!0;for(const o of i.oneofs){const a=e[o];if(!xn(a))return!1;if(a.oneofKind===void 0)continue;const c=this.fields.find(l=>l.localName===a.oneofKind);if(!c||!this.field(a[a.oneofKind],c,n,t))return!1}for(const o of this.fields)if(o.oneof===void 0&&!this.field(e[o.localName],o,n,t))return!1;return!0}field(e,t,n,s){let i=t.repeat;switch(t.kind){case"scalar":return e===void 0?t.opt:i?this.scalars(e,t.T,s,t.L):this.scalar(e,t.T,t.L);case"enum":return e===void 0?t.opt:i?this.scalars(e,d.INT32,s):this.scalar(e,d.INT32);case"message":return e===void 0?!0:i?this.messages(e,t.T(),n,s):this.message(e,t.T(),n,s);case"map":if(typeof e!="object"||e===null)return!1;if(s<2)return!0;if(!this.mapKeys(e,t.K,s))return!1;switch(t.V.kind){case"scalar":return this.scalars(Object.values(e),t.V.T,s,t.V.L);case"enum":return this.scalars(Object.values(e),d.INT32,s);case"message":return this.messages(Object.values(e),t.V.T(),n,s)}break}return!0}message(e,t,n,s){return n?t.isAssignable(e,s):t.is(e,s)}messages(e,t,n,s){if(!Array.isArray(e))return!1;if(s<2)return!0;if(n){for(let i=0;i<e.length&&i<s;i++)if(!t.isAssignable(e[i],s-1))return!1}else for(let i=0;i<e.length&&i<s;i++)if(!t.is(e[i],s-1))return!1;return!0}scalar(e,t,n){let s=typeof e;switch(t){case d.UINT64:case d.FIXED64:case d.INT64:case d.SFIXED64:case d.SINT64:switch(n){case B.BIGINT:return s=="bigint";case B.NUMBER:return s=="number"&&!isNaN(e);default:return s=="string"}case d.BOOL:return s=="boolean";case d.STRING:return s=="string";case d.BYTES:return e instanceof Uint8Array;case d.DOUBLE:case d.FLOAT:return s=="number"&&!isNaN(e);default:return s=="number"&&Number.isInteger(e)}}scalars(e,t,n,s){if(!Array.isArray(e))return!1;if(n<2)return!0;if(Array.isArray(e)){for(let i=0;i<e.length&&i<n;i++)if(!this.scalar(e[i],t,s))return!1}return!0}mapKeys(e,t,n){let s=Object.keys(e);switch(t){case d.INT32:case d.FIXED32:case d.SFIXED32:case d.SINT32:case d.UINT32:return this.scalars(s.slice(0,n).map(i=>parseInt(i)),t,n);case d.BOOL:return this.scalars(s.slice(0,n).map(i=>i=="true"?!0:i=="false"?!1:i),t,n);default:return this.scalars(s,t,n,B.STRING)}}}function M(r,e){switch(e){case B.BIGINT:return r.toBigInt();case B.NUMBER:return r.toNumber();default:return r.toString()}}class Mn{constructor(e){this.info=e}prepare(){var e;if(this.fMap===void 0){this.fMap={};const t=(e=this.info.fields)!==null&&e!==void 0?e:[];for(const n of t)this.fMap[n.name]=n,this.fMap[n.jsonName]=n,this.fMap[n.localName]=n}}assert(e,t,n){if(!e){let s=Et(n);throw(s=="number"||s=="boolean")&&(s=n.toString()),new Error(`Cannot parse JSON ${s} for ${this.info.typeName}#${t}`)}}read(e,t,n){this.prepare();const s=[];for(const[i,o]of Object.entries(e)){const a=this.fMap[i];if(!a){if(!n.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${i}`);continue}const c=a.localName;let l;if(a.oneof){if(o===null&&(a.kind!=="enum"||a.T()[0]!=="google.protobuf.NullValue"))continue;if(s.includes(a.oneof))throw new Error(`Multiple members of the oneof group "${a.oneof}" of ${this.info.typeName} are present in JSON.`);s.push(a.oneof),l=t[a.oneof]={oneofKind:c}}else l=t;if(a.kind=="map"){if(o===null)continue;this.assert(pn(o),a.name,o);const u=l[c];for(const[f,h]of Object.entries(o)){this.assert(h!==null,a.name+" map value",null);let g;switch(a.V.kind){case"message":g=a.V.T().internalJsonRead(h,n);break;case"enum":if(g=this.enum(a.V.T(),h,a.name,n.ignoreUnknownFields),g===!1)continue;break;case"scalar":g=this.scalar(h,a.V.T,a.V.L,a.name);break}this.assert(g!==void 0,a.name+" map value",h);let y=f;a.K==d.BOOL&&(y=y=="true"?!0:y=="false"?!1:y),y=this.scalar(y,a.K,B.STRING,a.name).toString(),u[y]=g}}else if(a.repeat){if(o===null)continue;this.assert(Array.isArray(o),a.name,o);const u=l[c];for(const f of o){this.assert(f!==null,a.name,null);let h;switch(a.kind){case"message":h=a.T().internalJsonRead(f,n);break;case"enum":if(h=this.enum(a.T(),f,a.name,n.ignoreUnknownFields),h===!1)continue;break;case"scalar":h=this.scalar(f,a.T,a.L,a.name);break}this.assert(h!==void 0,a.name,o),u.push(h)}}else switch(a.kind){case"message":if(o===null&&a.T().typeName!="google.protobuf.Value"){this.assert(a.oneof===void 0,a.name+" (oneof member)",null);continue}l[c]=a.T().internalJsonRead(o,n,l[c]);break;case"enum":if(o===null)continue;let u=this.enum(a.T(),o,a.name,n.ignoreUnknownFields);if(u===!1)continue;l[c]=u;break;case"scalar":if(o===null)continue;l[c]=this.scalar(o,a.T,a.L,a.name);break}}}enum(e,t,n,s){if(e[0]=="google.protobuf.NullValue"&&T(t===null||t==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} only accepts null.`),t===null)return 0;switch(typeof t){case"number":return T(Number.isInteger(t),`Unable to parse field ${this.info.typeName}#${n}, enum can only be integral number, got ${t}.`),t;case"string":let i=t;e[2]&&t.substring(0,e[2].length)===e[2]&&(i=t.substring(e[2].length));let o=e[1][i];return typeof o>"u"&&s?!1:(T(typeof o=="number",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${t}".`),o)}T(!1,`Unable to parse field ${this.info.typeName}#${n}, cannot parse enum value from ${typeof t}".`)}scalar(e,t,n,s){let i;try{switch(t){case d.DOUBLE:case d.FLOAT:if(e===null)return 0;if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""){i="empty string";break}if(typeof e=="string"&&e.trim().length!==e.length){i="extra whitespace";break}if(typeof e!="string"&&typeof e!="number")break;let o=Number(e);if(Number.isNaN(o)){i="not a number";break}if(!Number.isFinite(o)){i="too large or small";break}return t==d.FLOAT&&ke(o),o;case d.INT32:case d.FIXED32:case d.SFIXED32:case d.SINT32:case d.UINT32:if(e===null)return 0;let a;if(typeof e=="number"?a=e:e===""?i="empty string":typeof e=="string"&&(e.trim().length!==e.length?i="extra whitespace":a=Number(e)),a===void 0)break;return t==d.UINT32?ue(a):W(a),a;case d.INT64:case d.SFIXED64:case d.SINT64:if(e===null)return M(N.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return M(N.from(e),n);case d.FIXED64:case d.UINT64:if(e===null)return M(P.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return M(P.from(e),n);case d.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case d.STRING:if(e===null)return"";if(typeof e!="string"){i="extra whitespace";break}try{encodeURIComponent(e)}catch(c){c="invalid UTF8";break}return e;case d.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return It(e)}}catch(o){i=o.message}this.assert(!1,s+(i?" - "+i:""),e)}}class Fn{constructor(e){var t;this.fields=(t=e.fields)!==null&&t!==void 0?t:[]}write(e,t){const n={},s=e;for(const i of this.fields){if(!i.oneof){let l=this.field(i,s[i.localName],t);l!==void 0&&(n[t.useProtoFieldName?i.name:i.jsonName]=l);continue}const o=s[i.oneof];if(o.oneofKind!==i.localName)continue;const a=i.kind=="scalar"||i.kind=="enum"?Object.assign(Object.assign({},t),{emitDefaultValues:!0}):t;let c=this.field(i,o[i.localName],a);T(c!==void 0),n[t.useProtoFieldName?i.name:i.jsonName]=c}return n}field(e,t,n){let s;if(e.kind=="map"){T(typeof t=="object"&&t!==null);const i={};switch(e.V.kind){case"scalar":for(const[c,l]of Object.entries(t)){const u=this.scalar(e.V.T,l,e.name,!1,!0);T(u!==void 0),i[c.toString()]=u}break;case"message":const o=e.V.T();for(const[c,l]of Object.entries(t)){const u=this.message(o,l,e.name,n);T(u!==void 0),i[c.toString()]=u}break;case"enum":const a=e.V.T();for(const[c,l]of Object.entries(t)){T(l===void 0||typeof l=="number");const u=this.enum(a,l,e.name,!1,!0,n.enumAsInteger);T(u!==void 0),i[c.toString()]=u}break}(n.emitDefaultValues||Object.keys(i).length>0)&&(s=i)}else if(e.repeat){T(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let c=0;c<t.length;c++){const l=this.scalar(e.T,t[c],e.name,e.opt,!0);T(l!==void 0),i.push(l)}break;case"enum":const o=e.T();for(let c=0;c<t.length;c++){T(t[c]===void 0||typeof t[c]=="number");const l=this.enum(o,t[c],e.name,e.opt,!0,n.enumAsInteger);T(l!==void 0),i.push(l)}break;case"message":const a=e.T();for(let c=0;c<t.length;c++){const l=this.message(a,t[c],e.name,n);T(l!==void 0),i.push(l)}break}(n.emitDefaultValues||i.length>0||n.emitDefaultValues)&&(s=i)}else switch(e.kind){case"scalar":s=this.scalar(e.T,t,e.name,e.opt,n.emitDefaultValues);break;case"enum":s=this.enum(e.T(),t,e.name,e.opt,n.emitDefaultValues,n.enumAsInteger);break;case"message":s=this.message(e.T(),t,e.name,n);break}return s}enum(e,t,n,s,i,o){if(e[0]=="google.protobuf.NullValue")return!i&&!s?void 0:null;if(t===void 0){T(s);return}if(!(t===0&&!i&&!s))return T(typeof t=="number"),T(Number.isInteger(t)),o||!e[1].hasOwnProperty(t)?t:e[2]?e[2]+e[1][t]:e[1][t]}message(e,t,n,s){return t===void 0?s.emitDefaultValues?null:void 0:e.internalJsonWrite(t,s)}scalar(e,t,n,s,i){if(t===void 0){T(s);return}const o=i||s;switch(e){case d.INT32:case d.SFIXED32:case d.SINT32:return t===0?o?0:void 0:(W(t),t);case d.FIXED32:case d.UINT32:return t===0?o?0:void 0:(ue(t),t);case d.FLOAT:ke(t);case d.DOUBLE:return t===0?o?0:void 0:(T(typeof t=="number"),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t);case d.STRING:return t===""?o?"":void 0:(T(typeof t=="string"),t);case d.BOOL:return t===!1?o?!1:void 0:(T(typeof t=="boolean"),t);case d.UINT64:case d.FIXED64:T(typeof t=="number"||typeof t=="string"||typeof t=="bigint");let a=P.from(t);return a.isZero()&&!o?void 0:a.toString();case d.INT64:case d.SFIXED64:case d.SINT64:T(typeof t=="number"||typeof t=="string"||typeof t=="bigint");let c=N.from(t);return c.isZero()&&!o?void 0:c.toString();case d.BYTES:return T(t instanceof Uint8Array),t.byteLength?kt(t):o?"":void 0}}}function _e(r,e=B.STRING){switch(r){case d.BOOL:return!1;case d.UINT64:case d.FIXED64:return M(P.ZERO,e);case d.INT64:case d.SFIXED64:case d.SINT64:return M(N.ZERO,e);case d.DOUBLE:case d.FLOAT:return 0;case d.BYTES:return new Uint8Array(0);case d.STRING:return"";default:return 0}}class Un{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const t=(e=this.info.fields)!==null&&e!==void 0?e:[];this.fieldNoToField=new Map(t.map(n=>[n.no,n]))}}read(e,t,n,s){this.prepare();const i=s===void 0?e.len:e.pos+s;for(;e.pos<i;){const[o,a]=e.tag(),c=this.fieldNoToField.get(o);if(!c){let h=n.readUnknownField;if(h=="throw")throw new Error(`Unknown field ${o} (wire type ${a}) for ${this.info.typeName}`);let g=e.skip(a);h!==!1&&(h===!0?oe.onRead:h)(this.info.typeName,t,o,a,g);continue}let l=t,u=c.repeat,f=c.localName;switch(c.oneof&&(l=l[c.oneof],l.oneofKind!==f&&(l=t[c.oneof]={oneofKind:f})),c.kind){case"scalar":case"enum":let h=c.kind=="enum"?d.INT32:c.T,g=c.kind=="scalar"?c.L:void 0;if(u){let E=l[f];if(a==k.LengthDelimited&&h!=d.STRING&&h!=d.BYTES){let j=e.uint32()+e.pos;for(;e.pos<j;)E.push(this.scalar(e,h,g))}else E.push(this.scalar(e,h,g))}else l[f]=this.scalar(e,h,g);break;case"message":if(u){let E=l[f],j=c.T().internalBinaryRead(e,e.uint32(),n);E.push(j)}else l[f]=c.T().internalBinaryRead(e,e.uint32(),n,l[f]);break;case"map":let[y,v]=this.mapEntry(c,e,n);l[f][y]=v;break}}}mapEntry(e,t,n){let s=t.uint32(),i=t.pos+s,o,a;for(;t.pos<i;){let[c,l]=t.tag();switch(c){case 1:e.K==d.BOOL?o=t.bool().toString():o=this.scalar(t,e.K,B.STRING);break;case 2:switch(e.V.kind){case"scalar":a=this.scalar(t,e.V.T,e.V.L);break;case"enum":a=t.int32();break;case"message":a=e.V.T().internalBinaryRead(t,t.uint32(),n);break}break;default:throw new Error(`Unknown field ${c} (wire type ${l}) in map entry for ${this.info.typeName}#${e.name}`)}}if(o===void 0){let c=_e(e.K);o=e.K==d.BOOL?c.toString():c}if(a===void 0)switch(e.V.kind){case"scalar":a=_e(e.V.T,e.V.L);break;case"enum":a=0;break;case"message":a=e.V.T().create();break}return[o,a]}scalar(e,t,n){switch(t){case d.INT32:return e.int32();case d.STRING:return e.string();case d.BOOL:return e.bool();case d.DOUBLE:return e.double();case d.FLOAT:return e.float();case d.INT64:return M(e.int64(),n);case d.UINT64:return M(e.uint64(),n);case d.FIXED64:return M(e.fixed64(),n);case d.FIXED32:return e.fixed32();case d.BYTES:return e.bytes();case d.UINT32:return e.uint32();case d.SFIXED32:return e.sfixed32();case d.SFIXED64:return M(e.sfixed64(),n);case d.SINT32:return e.sint32();case d.SINT64:return M(e.sint64(),n)}}}class jn{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((t,n)=>t.no-n.no)}}write(e,t,n){this.prepare();for(const i of this.fields){let o,a,c=i.repeat,l=i.localName;if(i.oneof){const u=e[i.oneof];if(u.oneofKind!==l)continue;o=u[l],a=!0}else o=e[l],a=!1;switch(i.kind){case"scalar":case"enum":let u=i.kind=="enum"?d.INT32:i.T;if(c)if(T(Array.isArray(o)),c==fe.PACKED)this.packed(t,u,i.no,o);else for(const f of o)this.scalar(t,u,i.no,f,!0);else o===void 0?T(i.opt):this.scalar(t,u,i.no,o,a||i.opt);break;case"message":if(c){T(Array.isArray(o));for(const f of o)this.message(t,n,i.T(),i.no,f)}else this.message(t,n,i.T(),i.no,o);break;case"map":T(typeof o=="object"&&o!==null);for(const[f,h]of Object.entries(o))this.mapEntry(t,n,i,f,h);break}}let s=n.writeUnknownFields;s!==!1&&(s===!0?oe.onWrite:s)(this.info.typeName,e,t)}mapEntry(e,t,n,s,i){e.tag(n.no,k.LengthDelimited),e.fork();let o=s;switch(n.K){case d.INT32:case d.FIXED32:case d.UINT32:case d.SFIXED32:case d.SINT32:o=Number.parseInt(s);break;case d.BOOL:T(s=="true"||s=="false"),o=s=="true";break}switch(this.scalar(e,n.K,1,o,!0),n.V.kind){case"scalar":this.scalar(e,n.V.T,2,i,!0);break;case"enum":this.scalar(e,d.INT32,2,i,!0);break;case"message":this.message(e,t,n.V.T(),2,i);break}e.join()}message(e,t,n,s,i){i!==void 0&&(n.internalBinaryWrite(i,e.tag(s,k.LengthDelimited).fork(),t),e.join())}scalar(e,t,n,s,i){let[o,a,c]=this.scalarInfo(t,s);(!c||i)&&(e.tag(n,o),e[a](s))}packed(e,t,n,s){if(!s.length)return;T(t!==d.BYTES&&t!==d.STRING),e.tag(n,k.LengthDelimited),e.fork();let[,i]=this.scalarInfo(t);for(let o=0;o<s.length;o++)e[i](s[o]);e.join()}scalarInfo(e,t){let n=k.Varint,s,i=t===void 0,o=t===0;switch(e){case d.INT32:s="int32";break;case d.STRING:o=i||!t.length,n=k.LengthDelimited,s="string";break;case d.BOOL:o=t===!1,s="bool";break;case d.UINT32:s="uint32";break;case d.DOUBLE:n=k.Bit64,s="double";break;case d.FLOAT:n=k.Bit32,s="float";break;case d.INT64:o=i||N.from(t).isZero(),s="int64";break;case d.UINT64:o=i||P.from(t).isZero(),s="uint64";break;case d.FIXED64:o=i||P.from(t).isZero(),n=k.Bit64,s="fixed64";break;case d.BYTES:o=i||!t.byteLength,n=k.LengthDelimited,s="bytes";break;case d.FIXED32:n=k.Bit32,s="fixed32";break;case d.SFIXED32:n=k.Bit32,s="sfixed32";break;case d.SFIXED64:o=i||N.from(t).isZero(),n=k.Bit64,s="sfixed64";break;case d.SINT32:s="sint32";break;case d.SINT64:o=i||N.from(t).isZero(),s="sint64";break}return[n,s,i||o]}}function Bn(r){const e=r.messagePrototype?Object.create(r.messagePrototype):Object.defineProperty({},Ft,{value:r});for(let t of r.fields){let n=t.localName;if(!t.opt)if(t.oneof)e[t.oneof]={oneofKind:void 0};else if(t.repeat)e[n]=[];else switch(t.kind){case"scalar":e[n]=_e(t.T,t.L);break;case"enum":e[n]=0;break;case"map":e[n]={};break}}return e}function Pe(r,e,t){let n,s=t,i;for(let o of r.fields){let a=o.localName;if(o.oneof){const c=s[o.oneof];if((c==null?void 0:c.oneofKind)==null)continue;if(n=c[a],i=e[o.oneof],i.oneofKind=c.oneofKind,n==null){delete i[a];continue}}else if(n=s[a],i=e,n==null)continue;switch(o.repeat&&(i[a].length=n.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let l=0;l<n.length;l++)i[a][l]=n[l];else i[a]=n;break;case"message":let c=o.T();if(o.repeat)for(let l=0;l<n.length;l++)i[a][l]=c.create(n[l]);else i[a]===void 0?i[a]=c.create(n):c.mergePartial(i[a],n);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(i[a],n);break;case"message":let l=o.V.T();for(let u of Object.keys(n))i[a][u]=l.create(n[u]);break}break}}}function Vn(r,e,t){if(e===t)return!0;if(!e||!t)return!1;for(let n of r.fields){let s=n.localName,i=n.oneof?e[n.oneof][s]:e[s],o=n.oneof?t[n.oneof][s]:t[s];switch(n.kind){case"enum":case"scalar":let a=n.kind=="enum"?d.INT32:n.T;if(!(n.repeat?jt(a,i,o):Ut(a,i,o)))return!1;break;case"map":if(!(n.V.kind=="message"?Bt(n.V.T(),he(i),he(o)):jt(n.V.kind=="enum"?d.INT32:n.V.T,he(i),he(o))))return!1;break;case"message":let c=n.T();if(!(n.repeat?Bt(c,i,o):c.equals(i,o)))return!1;break}}return!0}const he=Object.values;function Ut(r,e,t){if(e===t)return!0;if(r!==d.BYTES)return!1;let n=e,s=t;if(n.length!==s.length)return!1;for(let i=0;i<n.length;i++)if(n[i]!=s[i])return!1;return!0}function jt(r,e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Ut(r,e[n],t[n]))return!1;return!0}function Bt(r,e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!r.equals(e[n],t[n]))return!1;return!0}const $n=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class I{constructor(e,t,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=t.map(An),this.options=n??{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},$n),{[Ft]:{value:this}})),this.refTypeCheck=new Ln(this),this.refJsonReader=new Mn(this),this.refJsonWriter=new Fn(this),this.refBinReader=new Un(this),this.refBinWriter=new jn(this)}create(e){let t=Bn(this);return e!==void 0&&Pe(this,t,e),t}clone(e){let t=this.create();return Pe(this,t,e),t}equals(e,t){return Vn(this,e,t)}is(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!1)}isAssignable(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!0)}mergePartial(e,t){Pe(this,e,t)}fromBinary(e,t){let n=Tn(t);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,t){return this.internalJsonRead(e,Pn(t))}fromJsonString(e,t){let n=JSON.parse(e);return this.fromJson(n,t)}toJson(e,t){return this.internalJsonWrite(e,On(t))}toJsonString(e,t){var n;let s=this.toJson(e,t);return JSON.stringify(s,null,(n=t==null?void 0:t.prettySpaces)!==null&&n!==void 0?n:0)}toBinary(e,t){let n=Nn(t);return this.internalBinaryWrite(e,n.writerFactory(),n).finish()}internalJsonRead(e,t,n){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let s=n??this.create();return this.refJsonReader.read(e,s,t),s}throw new Error(`Unable to parse message ${this.typeName} from JSON ${Et(e)}.`)}internalJsonWrite(e,t){return this.refJsonWriter.write(e,t)}internalBinaryWrite(e,t,n){return this.refBinWriter.write(e,t,n),t}internalBinaryRead(e,t,n,s){let i=s??this.create();return this.refBinReader.read(e,i,n,t),i}}function wn(r,e){var t,n,s;let i=r;return i.service=e,i.localName=(t=i.localName)!==null&&t!==void 0?t:Ne(i.name),i.serverStreaming=!!i.serverStreaming,i.clientStreaming=!!i.clientStreaming,i.options=(n=i.options)!==null&&n!==void 0?n:{},i.idempotency=(s=i.idempotency)!==null&&s!==void 0?s:void 0,i}class Kn{constructor(e,t,n){this.typeName=e,this.methods=t.map(s=>wn(s,this)),this.options=n??{}}}class S extends Error{constructor(e,t="UNKNOWN",n){super(e),this.name="RpcError",Object.setPrototypeOf(this,new.target.prototype),this.code=t,this.meta=n??{}}toString(){const e=[this.name+": "+this.message];this.code&&(e.push(""),e.push("Code: "+this.code)),this.serviceName&&this.methodName&&e.push("Method: "+this.serviceName+"/"+this.methodName);let t=Object.entries(this.meta);if(t.length){e.push(""),e.push("Meta:");for(let[n,s]of t)e.push(` ${n}: ${s}`)}return e.join(`
37
+ `)}}function qn(r,e){if(!e)return r;let t={};de(r,t),de(e,t);for(let n of Object.keys(e)){let s=e[n];switch(n){case"jsonOptions":t.jsonOptions=Dn(r.jsonOptions,t.jsonOptions);break;case"binaryOptions":t.binaryOptions=mn(r.binaryOptions,t.binaryOptions);break;case"meta":t.meta={},de(r.meta,t.meta),de(e.meta,t.meta);break;case"interceptors":t.interceptors=r.interceptors?r.interceptors.concat(s):s.concat();break}}return t}function de(r,e){if(!r)return;let t=e;for(let[n,s]of Object.entries(r))s instanceof Date?t[n]=new Date(s.getTime()):Array.isArray(s)?t[n]=s.concat():t[n]=s}var x;(function(r){r[r.PENDING=0]="PENDING",r[r.REJECTED=1]="REJECTED",r[r.RESOLVED=2]="RESOLVED"})(x||(x={}));class K{constructor(e=!0){this._state=x.PENDING,this._promise=new Promise((t,n)=>{this._resolve=t,this._reject=n}),e&&this._promise.catch(t=>{})}get state(){return this._state}get promise(){return this._promise}resolve(e){if(this.state!==x.PENDING)throw new Error(`cannot resolve ${x[this.state].toLowerCase()}`);this._resolve(e),this._state=x.RESOLVED}reject(e){if(this.state!==x.PENDING)throw new Error(`cannot reject ${x[this.state].toLowerCase()}`);this._reject(e),this._state=x.REJECTED}resolvePending(e){this._state===x.PENDING&&this.resolve(e)}rejectPending(e){this._state===x.PENDING&&this.reject(e)}}class Gn{constructor(){this._lis={nxt:[],msg:[],err:[],cmp:[]},this._closed=!1}onNext(e){return this.addLis(e,this._lis.nxt)}onMessage(e){return this.addLis(e,this._lis.msg)}onError(e){return this.addLis(e,this._lis.err)}onComplete(e){return this.addLis(e,this._lis.cmp)}addLis(e,t){return t.push(e),()=>{let n=t.indexOf(e);n>=0&&t.splice(n,1)}}clearLis(){for(let e of Object.values(this._lis))e.splice(0,e.length)}get closed(){return this._closed!==!1}notifyNext(e,t,n){T((e?1:0)+(t?1:0)+(n?1:0)<=1,"only one emission at a time"),e&&this.notifyMessage(e),t&&this.notifyError(t),n&&this.notifyComplete()}notifyMessage(e){T(!this.closed,"stream is closed"),this.pushIt({value:e,done:!1}),this._lis.msg.forEach(t=>t(e)),this._lis.nxt.forEach(t=>t(e,void 0,!1))}notifyError(e){T(!this.closed,"stream is closed"),this._closed=e,this.pushIt(e),this._lis.err.forEach(t=>t(e)),this._lis.nxt.forEach(t=>t(void 0,e,!1)),this.clearLis()}notifyComplete(){T(!this.closed,"stream is closed"),this._closed=!0,this.pushIt({value:null,done:!0}),this._lis.cmp.forEach(e=>e()),this._lis.nxt.forEach(e=>e(void 0,void 0,!0)),this.clearLis()}[Symbol.asyncIterator](){return this._itState||(this._itState={q:[]}),this._closed===!0?this.pushIt({value:null,done:!0}):this._closed!==!1&&this.pushIt(this._closed),{next:()=>{let e=this._itState;T(e,"bad state"),T(!e.p,"iterator contract broken");let t=e.q.shift();return t?"value"in t?Promise.resolve(t):Promise.reject(t):(e.p=new K,e.p.promise)}}}pushIt(e){let t=this._itState;if(t)if(t.p){const n=t.p;T(n.state==x.PENDING,"iterator contract broken"),"value"in e?n.resolve(e):n.reject(e),delete t.p}else t.q.push(e)}}var Jn=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(n.next(u))}catch(f){o(f)}}function c(u){try{l(n.throw(u))}catch(f){o(f)}}function l(u){u.done?i(u.value):s(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})};class Xn{constructor(e,t,n,s,i,o,a){this.method=e,this.requestHeaders=t,this.request=n,this.headers=s,this.response=i,this.status=o,this.trailers=a}then(e,t){return this.promiseFinished().then(n=>e?Promise.resolve(e(n)):n,n=>t?Promise.resolve(t(n)):Promise.reject(n))}promiseFinished(){return Jn(this,void 0,void 0,function*(){let[e,t,n,s]=yield Promise.all([this.headers,this.response,this.status,this.trailers]);return{method:this.method,requestHeaders:this.requestHeaders,request:this.request,headers:e,response:t,status:n,trailers:s}})}}var zn=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(n.next(u))}catch(f){o(f)}}function c(u){try{l(n.throw(u))}catch(f){o(f)}}function l(u){u.done?i(u.value):s(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})};class Wn{constructor(e,t,n,s,i,o,a){this.method=e,this.requestHeaders=t,this.request=n,this.headers=s,this.responses=i,this.status=o,this.trailers=a}then(e,t){return this.promiseFinished().then(n=>e?Promise.resolve(e(n)):n,n=>t?Promise.resolve(t(n)):Promise.reject(n))}promiseFinished(){return zn(this,void 0,void 0,function*(){let[e,t,n]=yield Promise.all([this.headers,this.status,this.trailers]);return{method:this.method,requestHeaders:this.requestHeaders,request:this.request,headers:e,status:t,trailers:n}})}}function Oe(r,e,t,n,s){var i,o,a,c;if(r=="unary"){let l=(u,f,h)=>e.unary(u,f,h);for(const u of((i=n.interceptors)!==null&&i!==void 0?i:[]).filter(f=>f.interceptUnary).reverse()){const f=l;l=(h,g,y)=>u.interceptUnary(f,h,g,y)}return l(t,s,n)}if(r=="serverStreaming"){let l=(u,f,h)=>e.serverStreaming(u,f,h);for(const u of((o=n.interceptors)!==null&&o!==void 0?o:[]).filter(f=>f.interceptServerStreaming).reverse()){const f=l;l=(h,g,y)=>u.interceptServerStreaming(f,h,g,y)}return l(t,s,n)}if(r=="clientStreaming"){let l=(u,f)=>e.clientStreaming(u,f);for(const u of((a=n.interceptors)!==null&&a!==void 0?a:[]).filter(f=>f.interceptClientStreaming).reverse()){const f=l;l=(h,g)=>u.interceptClientStreaming(f,h,g)}return l(t,n)}if(r=="duplex"){let l=(u,f)=>e.duplex(u,f);for(const u of((c=n.interceptors)!==null&&c!==void 0?c:[]).filter(f=>f.interceptDuplex).reverse()){const f=l;l=(h,g)=>u.interceptDuplex(f,h,g)}return l(t,n)}Sn(r)}var L=(r=>(r[r.UNSPECIFIED=0]="UNSPECIFIED",r[r.OFFER=1]="OFFER",r[r.ANSWER=2]="ANSWER",r[r.PRANSWER=3]="PRANSWER",r[r.ROLLBACK=4]="ROLLBACK",r))(L||{});class Yn extends I{constructor(){super("pulsebeam.v1.PrepareReq",[])}}const Zn=new Yn;class Hn extends I{constructor(){super("pulsebeam.v1.PrepareResp",[{no:1,name:"ice_servers",kind:"message",repeat:1,T:()=>tr}])}}const Qn=new Hn;class er extends I{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}])}}const tr=new er;class nr extends I{constructor(){super("pulsebeam.v1.SendReq",[{no:1,name:"msg",kind:"message",T:()=>Vt}])}}const rr=new nr;class sr extends I{constructor(){super("pulsebeam.v1.SendResp",[])}}const ir=new sr;class or extends I{constructor(){super("pulsebeam.v1.RecvReq",[{no:1,name:"src",kind:"message",T:()=>De}])}}const ar=new or;class cr extends I{constructor(){super("pulsebeam.v1.RecvResp",[{no:1,name:"msg",kind:"message",T:()=>Vt}])}}const lr=new cr;class ur extends I{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}])}}const De=new ur;class fr extends I{constructor(){super("pulsebeam.v1.Message",[{no:1,name:"header",kind:"message",T:()=>mr},{no:2,name:"payload",kind:"message",T:()=>dr}])}}const Vt=new fr;class hr extends I{constructor(){super("pulsebeam.v1.MessagePayload",[{no:1,name:"signal",kind:"message",oneof:"payloadType",T:()=>yr},{no:2,name:"join",kind:"message",oneof:"payloadType",T:()=>Er},{no:3,name:"bye",kind:"message",oneof:"payloadType",T:()=>kr},{no:4,name:"ack",kind:"message",oneof:"payloadType",T:()=>_r},{no:5,name:"ping",kind:"message",oneof:"payloadType",T:()=>Or}])}}const dr=new hr;class pr extends I{constructor(){super("pulsebeam.v1.MessageHeader",[{no:1,name:"src",kind:"message",T:()=>De},{no:2,name:"dst",kind:"message",T:()=>De},{no:7,name:"seqnum",kind:"scalar",T:13},{no:8,name:"reliable",kind:"scalar",T:8}])}}const mr=new pr;class gr extends I{constructor(){super("pulsebeam.v1.Signal",[{no:1,name:"generation_counter",kind:"scalar",T:13},{no:9,name:"sdp",kind:"message",oneof:"data",T:()=>Tr},{no:10,name:"ice_candidate",kind:"message",oneof:"data",T:()=>$t},{no:11,name:"ice_candidate_batch",kind:"message",oneof:"data",T:()=>Sr}])}}const yr=new gr;class br extends I{constructor(){super("pulsebeam.v1.Sdp",[{no:1,name:"kind",kind:"enum",T:()=>["pulsebeam.v1.SdpKind",L,"SDP_KIND_"]},{no:2,name:"sdp",kind:"scalar",T:9}])}}const Tr=new br;class Cr extends I{constructor(){super("pulsebeam.v1.ICECandidateBatch",[{no:1,name:"candidates",kind:"message",repeat:1,T:()=>$t}])}}const Sr=new Cr;class Rr extends I{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}])}}const $t=new Rr;class vr extends I{constructor(){super("pulsebeam.v1.Join",[])}}const Er=new vr;class Ir extends I{constructor(){super("pulsebeam.v1.Bye",[])}}const kr=new Ir;class Nr extends I{constructor(){super("pulsebeam.v1.Ack",[{no:1,name:"ack_ranges",kind:"message",repeat:1,T:()=>Ar}])}}const _r=new Nr;class Pr extends I{constructor(){super("pulsebeam.v1.Ping",[])}}const Or=new Pr;class Dr extends I{constructor(){super("pulsebeam.v1.AckRange",[{no:1,name:"seqnum_start",kind:"scalar",T:13},{no:2,name:"seqnum_end",kind:"scalar",T:13}])}}const Ar=new Dr;class xr extends I{constructor(){super("pulsebeam.v1.DataChannel",[{no:10,name:"heartbeat",kind:"message",oneof:"payload",T:()=>Mr}])}}new xr;class Lr extends I{constructor(){super("pulsebeam.v1.DataChannelHeartbeat",[])}}const Mr=new Lr,Ae=new Kn("pulsebeam.v1.Signaling",[{name:"Prepare",options:{},I:Zn,O:Qn},{name:"Send",options:{},I:rr,O:ir},{name:"Recv",serverStreaming:!0,options:{},I:ar,O:lr}]);class Fr{constructor(e){m(this,"typeName",Ae.typeName);m(this,"methods",Ae.methods);m(this,"options",Ae.options);this._transport=e}prepare(e,t){const n=this.methods[0],s=this._transport.mergeOptions(t);return Oe("unary",this._transport,n,s,e)}send(e,t){const n=this.methods[1],s=this._transport.mergeOptions(t);return Oe("unary",this._transport,n,s,e)}recv(e,t){const n=this.methods[2],s=this._transport.mergeOptions(t);return Oe("serverStreaming",this._transport,n,s,e)}}function wt(r,e){return new Promise(t=>{const n=setTimeout(()=>t(!0),r);e&&e.addEventListener("abort",()=>{clearTimeout(n),t(!1)})})}function xe(...r){const e=new AbortController,t=()=>{e.abort();for(const n of r)n.removeEventListener("abort",t)};for(const n of r)n.addEventListener("abort",t);return e.signal}async function Le(r,e){const{maxRetries:t,baseDelay:n,maxDelay:s,jitterFactor:i=.3,isRecoverable:o=()=>!0,abortSignal:a}=e;let c=0;for(;(c<=t||t<0)&&!(a!=null&&a.aborted);)try{return await r()}catch(l){if(!o(l)||(c++,t>=0&&c>t))throw l;const u=Ur(c,n,s,i);await wt(u,a).catch(()=>{})}if(a!=null&&a.aborted)return null;throw new Error("Retry failed: max retries exceeded")}function Ur(r,e,t,n){const s=Math.min(e*2**(r-1),t),i=Math.random()*n*s;return s+i}const Kt=9e5,qt=50,Me=1e3,jr=wt,Br=r=>{let e;do{const t=new Uint32Array(1);crypto.getRandomValues(t),e=t[0]}while(e>=0&&e<r);return e},Vr=r=>!0;class $r{constructor(e){m(this,"map");m(this,"emitted");m(this,"unreliable");m(this,"processing");m(this,"logger");m(this,"onmsg",async e=>{});this.logger=e.sub("queue"),this.map=new Map,this.emitted=new Map,this.unreliable=[],this.processing=!1}enqueue(e){var t;if(!((t=e.header)!=null&&t.reliable))this.unreliable.push(e);else{const n=e.header.seqnum;if(this.map.has(n)||this.emitted.has(n))return;this.map.set(n,[performance.now(),e])}this.processNext()}async processNext(){if(this.processing)return;let e=this.unreliable.pop();if(!e){const t=this.map.entries().next().value;if(!t)return;const[n,s]=t;this.map.delete(n),this.emitted.set(n,s);const[i,o]=s;if(!o.header)return;e=o}this.processing=!0;try{await this.onmsg(e)}catch(t){const n={msg:e};t instanceof Error&&(n.err=t),this.logger.error("error processing message",n)}this.processing=!1,this.processNext()}}class wr{constructor(e,t){m(this,"info");m(this,"streams");m(this,"abort");m(this,"logger");m(this,"asleep");m(this,"randUint32");m(this,"isRecoverable");m(this,"onstream",e=>{});m(this,"onclosed",e=>{});m(this,"handleControlMessage",e=>{switch(e.payloadType.oneofKind){case"ping":this.logger.debug("received ping");break;default:this.logger.warn("received unknown control message",{payload:e});break}});m(this,"handleMessages",e=>{if(this.logger.debug("received",{msg:e}),this.abort.signal.aborted)return;if(!e.header)return e.payload?this.handleControlMessage(e.payload):void 0;const t=e.header.src,n=e.header.dst;if(!t||!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(const i of this.streams)if(t.groupId===i.other.groupId&&t.peerId===i.other.peerId&&t.connId===i.other.connId){s=i;break}if(!s){if(t.peerId==this.info.peerId){this.logger.warn("loopback detected, ignoring messages");return}this.logger.debug(`session not found, creating one for ${t.peerId}:${t.connId}`),s=new Kr(this,this.info,t,this.logger),this.streams.push(s),this.onstream(s)}s.enqueue(e)});this.client=e,this.opts=t,this.asleep=t.asleep||jr,this.randUint32=t.randUint32||Br,this.isRecoverable=t.isRecoverable||Vr,this.info={groupId:t.groupId,peerId:t.peerId,connId:this.randUint32(16)},this.abort=new AbortController,this.logger=t.logger.sub("transport",{info:this.info}),this.streams=[]}async listen(){const e={abort:this.abort.signal,timeout:Kt},t={baseDelay:qt,maxDelay:Me,maxRetries:-1,abortSignal:this.abort.signal,isRecoverable:this.isRecoverable};for(;!this.abort.signal.aborted;)try{await Le(async()=>{const n=this.client.recv({src:this.info},e);n.responses.onMessage(s=>!!s.msg&&this.handleMessages(s.msg)),await n},t)}catch(n){this.logger.error("unrecoverable error, force closing",{err:n}),this.close();return}this.logger.debug("poll loop is closed")}async close(e){this.abort.signal.aborted||(e=e||"transport is closed",await Promise.all(this.streams.map(t=>t.close(e))),this.abort.abort(e),this.logger.debug("transport is now closed",{reason:e}),this.streams=[],this.onclosed(e))}removeStream(e){this.streams=this.streams.filter(t=>t!==e)}async connect(e,t,n){const s={payloadType:{oneofKind:"join",join:{}}},i={src:this.info,dst:{groupId:e,peerId:t,connId:0},seqnum:0,reliable:!1};let o=!1;const a=xe(n,this.abort.signal);for(;!a.aborted&&!o;)await this.send(a,{header:i,payload:s}),await this.asleep(Me,a).catch(()=>{}),o=!!this.streams.find(c=>c.other.groupId===e&&c.other.peerId===t)}async send(e,t){const n=xe(e,this.abort.signal),s={abort:n,timeout:Kt},i={baseDelay:qt,maxDelay:Me,maxRetries:-1,abortSignal:n,isRecoverable:this.isRecoverable};try{if(await Le(async()=>await this.client.send({msg:t},s),i)===null){this.logger.warn("aborted, message dropped from sending",{msg:t});return}return}catch(o){this.logger.error("unrecoverable error, force closing",{err:o}),this.close();return}}}class Kr{constructor(e,t,n,s){m(this,"logger");m(this,"abort");m(this,"recvq");m(this,"lastSeqnum");m(this,"onsignal",async e=>{});m(this,"onclosed",e=>{});this.transport=e,this.info=t,this.other=n,this.logger=s.sub("stream",{other:n}),this.abort=new AbortController,this.recvq=new $r(this.logger),this.recvq.onmsg=i=>this.handleMessage(i),this.lastSeqnum=0}createSignal(...e){return xe(this.abort.signal,...e)}enqueue(e){if(this.abort.signal.aborted){this.logger.warn("received a message in closed state, ignoring new messages.");return}this.recvq.enqueue(e)}async send(e,t,n){n||(n=this.abort.signal);const s={header:{src:this.transport.info,dst:this.other,seqnum:this.lastSeqnum,reliable:t},payload:{...e}};this.lastSeqnum++,await this.transport.send(n,s)}async handleMessage(e){if(!e.payload){this.logger.warn("payload is missing from the stream message",{msg:e});return}switch(e.payload.payloadType.oneofKind){case"bye":this.close("received bye",!0);return;case"signal":this.onsignal(e.payload.payloadType.signal);return;case"join":return;default:this.logger.warn("unhandled payload type",{msg:e});return}}async close(e,t){this.abort.signal.aborted||(e=e||"session is closed",t||await this.send({payloadType:{oneofKind:"bye",bye:{}}},!1).catch(n=>this.logger.warn("failed to send bye",{e:n})),this.abort.abort(e),this.transport.removeStream(this),this.onclosed(e),this.logger.debug("sent bye to the other peer",{reason:e}))}}const qr={DEBUG:console.debug,INFO:console.info,WARN:console.warn,ERROR:console.error},Gr={DEBUG:r=>console.debug(pe(r)),INFO:r=>console.info(pe(r)),WARN:r=>console.warn(pe(r)),ERROR:r=>console.error(pe(r))};function Gt(r,e,t="root",n=new Set){const s=".";if(!n.has(r)){n.add(r);for(const i in r)if(typeof r[i]=="object"&&r[i]!==null){const o=t+s+i;Gt(r[i],e,o,n)}else{const o=e[t]||[];o.push(`${i}=${r[i]}`),e[t]=o}}}function pe(r){const e={};Gt(r,e);const t=[];for(const n in e)t.push(`[${n}] ${e[n].join(" ")}`);return t.join(`
38
+ `)}class Fe{constructor(e,t,n){m(this,"obj");m(this,"sink");this.name=e,t||(t={}),n||(n=qr),this.sink=n,this.obj={...t,name:e}}log(e,t,n){const s=n||{};e({ts:Date.now(),message:t,...this.obj,...s})}debug(e,t){this.log(this.sink.DEBUG,e,t)}info(e,t){this.log(this.sink.INFO,e,t)}warn(e,t){this.log(this.sink.WARN,e,t)}error(e,t){this.log(this.sink.ERROR,e,t)}sub(e,t){return t||(t={}),new Fe(this.name+"."+e,{...this.obj,...t},this.sink)}}const Jr=1,Jt=5e3,Xt="__internal";function Xr(r){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.password}}function zr(r){switch(r){case L.OFFER:return"offer";case L.ANSWER:return"answer";case L.PRANSWER:return"pranswer";case L.ROLLBACK:return"rollback";default:throw new Error(`unexpected kind: ${r}`)}}function zt(r){switch(r){case"offer":return L.OFFER;case"answer":return L.ANSWER;case"pranswer":return L.PRANSWER;case"rollback":return L.ROLLBACK;default:throw new Error(`unexpected sdp type: ${r}`)}}class Wr{constructor(e,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,"ondatachannel",()=>{});m(this,"onconnectionstatechange",()=>{});m(this,"ontrack",()=>{});m(this,"triggerIceRestart",()=>{if(!this.impolite)return;const e=performance.now()-this.lastIceRestart;if(e<Jt){const t=Jt-e,n=window.setTimeout(()=>{this.triggerIceRestart(),this.timers=this.timers.filter(s=>s===n)},t);return}if(this.pc.connectionState!=="connected"){if(this.iceRestartCount>=Jr){this.close("detected sustained network failure");return}this.logger.debug("triggered ICE restart"),this.pc.restartIce(),this.generationCounter++,this.iceRestartCount++,this.lastIceRestart=performance.now()}});m(this,"sendSignal",e=>{this.stream.send({payloadType:{oneofKind:"signal",signal:{...e,generationCounter:this.generationCounter}}},!0)});m(this,"handleSignal",async e=>{if(e.generationCounter<this.generationCounter){this.logger.warn("detected staled generationCounter signals, ignoring");return}this.addCandidates(e);const t=e.data;if(e.generationCounter>this.generationCounter){if(this.logger.debug("detected new generationCounter",{otherGenerationCounter:e.generationCounter,generationCounter:this.generationCounter,msg:t}),t.oneofKind==="iceCandidate"){this.logger.warn("expecting an offer but got ice candidates during an ICE restart, adding to pending.",{msg:t});return}this.generationCounter=e.generationCounter}if(t.oneofKind!="sdp")return;const n=t.sdp;this.logger.debug("received a SDP signal",{sdpKind:n.kind});const s=n.kind===L.OFFER&&(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:zr(n.kind),sdp:n.sdp}),n.kind===L.OFFER){if(await this.pc.setLocalDescription(),!this.pc.localDescription){this.logger.error("unexpected null local description");return}this.sendSignal({data:{oneofKind:"sdp",sdp:{kind:zt(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(const t of this.pendingCandidates)!t.candidate||t.candidate===""||(this.pc.addIceCandidate(t).catch(n=>{this.logger.warn("failed to add candidate, skipping.",{candidate:t,e:n})}),this.logger.debug(`added ice: ${t.candidate}`));this.pendingCandidates=[]});this.stream=e,this.pc=new RTCPeerConnection(t),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=e.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 Yr(this.logger,100,i=>this.sendLocalIceCandidates(i)),e.onsignal=i=>this.handleSignal(i),e.onclosed=i=>this.close(i),this.pc.oniceconnectionstatechange=async()=>{const i=await this.pc.getStats(),o=[],a=[],c=[];i.forEach(l=>{l.type==="candidate-pair"?o.push(l):l.type==="local-candidate"?a.push(l):l.type==="remote-candidate"&&c.push(l)}),this.logger.debug("iceconnectionstate changed",{connectionstate:this.pc.connectionState,iceconnectionstate:this.pc.iceConnectionState,local:a,remote:c,pair:o,pending:this.pendingCandidates})},this.pc.onsignalingstatechange=()=>{this.checkPendingCandidates()};let n=performance.now();this.pc.onconnectionstatechange=i=>{switch(this.logger.debug("connectionstate changed",{connectionstate:this.pc.connectionState,iceconnectionstate:this.pc.iceConnectionState}),this.setConnectionState(this.pc.connectionState,i),this.pc.connectionState){case"connecting":n=performance.now();break;case"connected":{const o=performance.now()-n;this.logger.debug(`it took ${o}ms to connect`),this.iceRestartCount=0;break}case"disconnected":this.triggerIceRestart();break;case"failed":this.close("connection failed");break}};let s=!0;this.pc.onnegotiationneeded=async()=>{if(s){if(!this.impolite){this.stream.send({payloadType:{oneofKind:"join",join:{}}},!0);return}s=!1}try{if(this.makingOffer=!0,this.logger.debug("creating an offer"),await this.pc.setLocalDescription(),!this.pc.localDescription)throw new Error("expect localDescription to be not empty");this.sendSignal({data:{oneofKind:"sdp",sdp:{kind:zt(this.pc.localDescription.type),sdp:this.pc.localDescription.sdp}}})}catch(i){i instanceof Error&&this.logger.error("failed in negotiating",{err:i})}finally{this.makingOffer=!1}},this.pc.onicecandidate=({candidate:i})=>{this.iceBatcher.addCandidate(i)},this.pc.ondatachannel=i=>{i.channel.label!==Xt&&this.ondatachannel&&this.ondatachannel(i)},this.pc.ontrack=(...i)=>{this.ontrack&&this.ontrack(...i)},this.internalDataChannel=this.pc.createDataChannel(Xt),this.internalDataChannel}addTrack(...e){return this.pc.addTrack(...e)}removeTrack(...e){return this.pc.removeTrack(...e)}createDataChannel(...e){return this.pc.createDataChannel(...e)}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(e){if(this.abort.signal.aborted)return;this.abort.abort(e);for(const n of this.timers)clearTimeout(n);this.timers=[],this.iceBatcher.close(),this.stream.close(),this._closeReason=e,this.pc.close();const t=new Event("connectionstatechange");this.setConnectionState("closed",t),this.logger.debug("session closed",{connectionState:this.connectionState})}sendLocalIceCandidates(e){const t=[];for(const n of e){const 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,t.push(s)}this.sendSignal({data:{oneofKind:"iceCandidateBatch",iceCandidateBatch:{candidates:t}}})}setConnectionState(e,t){e!==this._connectionState&&this.onconnectionstatechange&&this.onconnectionstatechange(t)}addCandidates(e){const t=[];if(e.data.oneofKind==="iceCandidate")t.push(e.data.iceCandidate);else if(e.data.oneofKind==="iceCandidateBatch")t.push(...e.data.iceCandidateBatch.candidates);else return;this.pendingCandidates.push(...t.map(n=>Xr(n))),this.checkPendingCandidates()}}class Yr{constructor(e,t,n){m(this,"candidates",[]);m(this,"timeoutId",null);m(this,"delayMs");m(this,"logger");m(this,"onIceCandidates");m(this,"addCandidate",e=>{if(!e||e.candidate===""){this.logger.debug("ice gathering is finished, force flush local candidates"),this.flushCandidates();return}this.logger.debug("onicecandidate",{candidate:e}),this.candidates.push(e),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=e.sub("icebatcher"),this.delayMs=t,this.onIceCandidates=n}}var p;(function(r){r[r.OK=0]="OK",r[r.CANCELLED=1]="CANCELLED",r[r.UNKNOWN=2]="UNKNOWN",r[r.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",r[r.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",r[r.NOT_FOUND=5]="NOT_FOUND",r[r.ALREADY_EXISTS=6]="ALREADY_EXISTS",r[r.PERMISSION_DENIED=7]="PERMISSION_DENIED",r[r.UNAUTHENTICATED=16]="UNAUTHENTICATED",r[r.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",r[r.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",r[r.ABORTED=10]="ABORTED",r[r.OUT_OF_RANGE=11]="OUT_OF_RANGE",r[r.UNIMPLEMENTED=12]="UNIMPLEMENTED",r[r.INTERNAL=13]="INTERNAL",r[r.UNAVAILABLE=14]="UNAVAILABLE",r[r.DATA_LOSS=15]="DATA_LOSS"})(p||(p={}));var Zr=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(n.next(u))}catch(f){o(f)}}function c(u){try{l(n.throw(u))}catch(f){o(f)}}function l(u){u.done?i(u.value):s(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})};function Wt(r,e,t,n,s){if(n)for(let[i,o]of Object.entries(n))if(typeof o=="string")r.append(i,o);else for(let a of o)r.append(i,a);if(r.set("Content-Type",e==="text"?"application/grpc-web-text":"application/grpc-web+proto"),e=="text"&&r.set("Accept","application/grpc-web-text"),r.set("X-Grpc-Web","1"),typeof t=="number"){if(t<=0)throw new S(`timeout ${t} ms exceeded`,p[p.DEADLINE_EXCEEDED]);r.set("grpc-timeout",`${t}m`)}else if(t){const i=t.getTime(),o=Date.now();if(i<=o)throw new S(`deadline ${t} exceeded`,p[p.DEADLINE_EXCEEDED]);r.set("grpc-timeout",`${i-o}m`)}return r}function Yt(r,e){let t=new Uint8Array(5+r.length);t[0]=F.DATA;for(let n=r.length,s=4;s>0;s--)t[s]=n%256,n>>>=8;return t.set(r,5),e==="binary"?t:kt(t)}function Ue(r,e,t){if(arguments.length===1){let c=r,l;try{l=c.type}catch{}switch(l){case"error":case"opaque":case"opaqueredirect":throw new S(`fetch response type ${c.type}`,p[p.UNKNOWN])}return Ue(ts(c.headers),c.status,c.statusText)}let n=r,s=e>=200&&e<300,i=tn(n),[o,a]=en(n);return(o===void 0||o===p.OK)&&!s&&(o=ns(e),a=t),[o,a,i]}function Zt(r){let e=es(r),[t,n]=en(e),s=tn(e);return[t??p.OK,n,s]}var F;(function(r){r[r.DATA=0]="DATA",r[r.TRAILER=128]="TRAILER"})(F||(F={}));function Ht(r,e,t){return Zr(this,void 0,void 0,function*(){let n,s="",i=new Uint8Array(0),o=Qr(e);if(Hr(r)){let a=r.getReader();n={next:()=>a.read()}}else n=r[Symbol.asyncIterator]();for(;;){let a=yield n.next();if(a.value!==void 0){if(o==="text"){for(let l=0;l<a.value.length;l++)s+=String.fromCharCode(a.value[l]);let c=s.length-s.length%4;if(c===0)continue;i=Qt(i,It(s.substring(0,c))),s=s.substring(c)}else i=Qt(i,a.value);for(;i.length>=5&&i[0]===F.DATA;){let c=0;for(let l=1;l<5;l++)c=(c<<8)+i[l];if(i.length-5>=c)t(F.DATA,i.subarray(5,5+c)),i=i.subarray(5+c);else break}}if(a.done){if(i.length===0)break;if(i[0]!==F.TRAILER||i.length<5)throw new S("premature EOF",p[p.DATA_LOSS]);t(F.TRAILER,i.subarray(5));break}}})}const Hr=r=>typeof r.getReader=="function";function Qt(r,e){let t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function Qr(r){switch(r){case"application/grpc-web-text":case"application/grpc-web-text+proto":return"text";case"application/grpc-web":case"application/grpc-web+proto":return"binary";case void 0:case null:throw new S("missing response content type",p[p.INTERNAL]);default:throw new S("unexpected response content type: "+r,p[p.INTERNAL])}}function en(r){let e,t,n=r["grpc-message"];if(n!==void 0){if(Array.isArray(n))return[p.INTERNAL,"invalid grpc-web message"];t=n}let s=r["grpc-status"];if(s!==void 0){if(Array.isArray(s))return[p.INTERNAL,"invalid grpc-web status"];if(e=parseInt(s,10),p[e]===void 0)return[p.INTERNAL,"invalid grpc-web status"]}return[e,t]}function tn(r){let e={};for(let[t,n]of Object.entries(r))switch(t){case"grpc-message":case"grpc-status":case"content-type":break;default:e[t]=n}return e}function es(r){let e={};for(let t of String.fromCharCode.apply(String,r).trim().split(`\r
39
+ `)){if(t=="")continue;let[n,...s]=t.split(":");const i=s.join(":").trim();n=n.trim();let o=e[n];typeof o=="string"?e[n]=[o,i]:Array.isArray(o)?o.push(i):e[n]=i}return e}function ts(r){let e={};return r.forEach((t,n)=>{let s=e[n];typeof s=="string"?e[n]=[s,t]:Array.isArray(s)?s.push(t):e[n]=t}),e}function ns(r){switch(r){case 200:return p.OK;case 400:return p.INVALID_ARGUMENT;case 401:return p.UNAUTHENTICATED;case 403:return p.PERMISSION_DENIED;case 404:return p.NOT_FOUND;case 409:return p.ABORTED;case 412:return p.FAILED_PRECONDITION;case 429:return p.RESOURCE_EXHAUSTED;case 499:return p.CANCELLED;case 500:return p.UNKNOWN;case 501:return p.UNIMPLEMENTED;case 503:return p.UNAVAILABLE;case 504:return p.DEADLINE_EXCEEDED;default:return p.UNKNOWN}}class rs{constructor(e){this.defaultOptions=e}mergeOptions(e){return qn(this.defaultOptions,e)}makeUrl(e,t){let n=t.baseUrl;return n.endsWith("/")&&(n=n.substring(0,n.length-1)),`${n}/${e.service.typeName}/${e.name}`}clientStreaming(e){const t=new S("Client streaming is not supported by grpc-web",p[p.UNIMPLEMENTED]);throw t.methodName=e.name,t.serviceName=e.service.typeName,t}duplex(e){const t=new S("Duplex streaming is not supported by grpc-web",p[p.UNIMPLEMENTED]);throw t.methodName=e.name,t.serviceName=e.service.typeName,t}serverStreaming(e,t,n){var s,i,o,a;let c=n,l=(s=c.format)!==null&&s!==void 0?s:"text",u=(i=c.fetchInit)!==null&&i!==void 0?i:{},f=this.makeUrl(e,c),h=e.I.toBinary(t,c.binaryOptions),g=new K,y=new Gn,v=!0,E,j=new K,V,X=new K;return globalThis.fetch(f,Object.assign(Object.assign({},u),{method:"POST",headers:Wt(new globalThis.Headers,l,c.timeout,c.meta),body:Yt(h,l),signal:(o=n.abort)!==null&&o!==void 0?o:null})).then(C=>{let[b,_,A]=Ue(C);if(g.resolve(A),b!=null&&b!==p.OK)throw new S(_??p[b],p[b],A);return b!=null&&(E={code:p[b],detail:_??p[b]}),C}).then(C=>{if(!C.body)throw new S("missing response body",p[p.INTERNAL]);return Ht(C.body,C.headers.get("content-type"),(b,_)=>{switch(b){case F.DATA:y.notifyMessage(e.O.fromBinary(_,c.binaryOptions)),v=!1;break;case F.TRAILER:let A,w;[A,w,V]=Zt(_),E={code:p[A],detail:w??p[A]};break}})}).then(()=>{if(!V&&!v)throw new S("missing trailers",p[p.DATA_LOSS]);if(!E)throw new S("missing status",p[p.INTERNAL]);if(E.code!=="OK")throw new S(E.detail,E.code,V);y.notifyComplete(),j.resolve(E),X.resolve(V||{})}).catch(C=>{let b;C instanceof S?b=C:C instanceof Error&&C.name==="AbortError"?b=new S(C.message,p[p.CANCELLED]):b=new S(C instanceof Error?C.message:""+C,p[p.INTERNAL]),b.methodName=e.name,b.serviceName=e.service.typeName,g.rejectPending(b),y.notifyError(b),j.rejectPending(b),X.rejectPending(b)}),new Wn(e,(a=c.meta)!==null&&a!==void 0?a:{},t,g.promise,y,j.promise,X.promise)}unary(e,t,n){var s,i,o,a;let c=n,l=(s=c.format)!==null&&s!==void 0?s:"text",u=(i=c.fetchInit)!==null&&i!==void 0?i:{},f=this.makeUrl(e,c),h=e.I.toBinary(t,c.binaryOptions),g=new K,y,v=new K,E,j=new K,V,X=new K;return globalThis.fetch(f,Object.assign(Object.assign({},u),{method:"POST",headers:Wt(new globalThis.Headers,l,c.timeout,c.meta),body:Yt(h,l),signal:(o=n.abort)!==null&&o!==void 0?o:null})).then(C=>{let[b,_,A]=Ue(C);if(g.resolve(A),b!=null&&b!==p.OK)throw new S(_??p[b],p[b],A);return b!=null&&(E={code:p[b],detail:_??p[b]}),C}).then(C=>{if(!C.body)throw new S("missing response body",p[p.INTERNAL]);return Ht(C.body,C.headers.get("content-type"),(b,_)=>{switch(b){case F.DATA:if(y)throw new S("unary call received 2nd message",p[p.DATA_LOSS]);y=e.O.fromBinary(_,c.binaryOptions);break;case F.TRAILER:let A,w;[A,w,V]=Zt(_),E={code:p[A],detail:w??p[A]};break}})}).then(()=>{if(!V&&y)throw new S("missing trailers",p[p.DATA_LOSS]);if(!E)throw new S("missing status",p[p.INTERNAL]);if(!y&&E.code==="OK")throw new S("expected error status",p[p.DATA_LOSS]);if(!y)throw new S(E.detail,E.code,V);if(v.resolve(y),E.code!=="OK")throw new S(E.detail,E.code,V);j.resolve(E),X.resolve(V||{})}).catch(C=>{let b;C instanceof S?b=C:C instanceof Error&&C.name==="AbortError"?b=new S(C.message,p[p.CANCELLED]):b=new S(C instanceof Error?C.message:""+C,p[p.INTERNAL]),b.methodName=e.name,b.serviceName=e.service.typeName,g.rejectPending(b),v.rejectPending(b),j.rejectPending(b),X.rejectPending(b)}),new Xn(e,(a=c.meta)!==null&&a!==void 0?a:{},t,g.promise,v.promise,j.promise,X.promise)}}class Y extends Error{}Y.prototype.name="InvalidTokenError";function ss(r){return decodeURIComponent(atob(r).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}))}function is(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return ss(e)}catch{return atob(e)}}function os(r,e){if(typeof r!="string")throw new Y("Invalid token specified: must be a string");e||(e={});const t=e.header===!0?0:1,n=r.split(".")[t];if(typeof n!="string")throw new Y(`Invalid token specified: missing part #${t+1}`);let s;try{s=is(n)}catch(i){throw new Y(`Invalid token specified: invalid base64 for part #${t+1} (${i.message})`)}try{return JSON.parse(s)}catch(i){throw new Y(`Invalid token specified: invalid json for part #${t+1} (${i.message})`)}}const as="https://cloud.pulsebeam.dev/grpc";class nn{constructor(e,t,n,s){m(this,"transport");m(this,"logger");m(this,"sessions");m(this,"_state");m(this,"onsession",e=>{});m(this,"onstatechange",()=>{});m(this,"peerId");this.peerId=n.peerId,this.logger=e.sub("peer",{peerId:this.peerId}),this.sessions=[],this._state="new";const i={bundlePolicy:"balanced",iceTransportPolicy:n.forceRelay?"relay":"all",iceCandidatePoolSize:0,iceServers:n.iceServers};this.transport=new wr(t,{enableDiscovery:!1,groupId:n.groupId,peerId:n.peerId,logger:this.logger,isRecoverable:s}),this.transport.onstream=o=>{const a=new Wr(o,i);this.sessions.push(a),this.onsession(a)},this.transport.onclosed=()=>{this.close()}}start(){if(this._state==="closed")throw new Error("peer is already closed");this.transport.listen()}async close(){this.sessions=[],await this.transport.close(),this.setState("closed")}connect(e,t,n){return this.transport.connect(e,t,n)}get state(){return this._state}setState(e){e!==this._state&&(this._state=e,this.onstatechange())}}const cs=[p[p.PERMISSION_DENIED],p[p.INVALID_ARGUMENT],p[p.ABORTED],p[p.NOT_FOUND],p[p.UNAUTHENTICATED]];function rn(r){return r instanceof Error?r instanceof S?!cs.includes(r.code):!0:!1}async function ls(r){const e=r.token,t=new rs({baseUrl:r.baseUrl||as,sendJson:!1,format:"binary",jsonOptions:{emitDefaultValues:!0,enumAsInteger:!0,ignoreUnknownFields:!0},interceptors:[{interceptUnary(l,u,f,h){return h.meta||(h.meta={}),h.meta.Authorization=`Bearer ${e}`,l(u,f,h)}}]}),n=new Fr(t),s=await Le(async()=>await n.prepare({}),{baseDelay:50,maxDelay:1e3,maxRetries:5,isRecoverable:rn});if(s===null)throw new Error("createPeer aborted");const i=[...r.iceServers||[]];for(const l of s.response.iceServers)i.push({urls:l.urls,username:l.username,credential:l.credential});const o=os(e),a={...r,iceServers:i,groupId:o.gid,peerId:o.pid};return new nn(new Fe("pulsebeam",void 0,Gr),n,a,rn)}let us=Symbol("clean"),U=[],q=0;const me=4;let fs=r=>{let e=[],t={get(){return t.lc||t.listen(()=>{})(),t.value},lc:0,listen(n){return t.lc=e.push(n),()=>{for(let i=q+me;i<U.length;)U[i]===n?U.splice(i,me):i+=me;let s=e.indexOf(n);~s&&(e.splice(s,1),--t.lc||t.off())}},notify(n,s){let i=!U.length;for(let o of e)U.push(o,t.value,n,s);if(i){for(q=0;q<U.length;q+=me)U[q](U[q+1],U[q+2],U[q+3]);U.length=0}},off(){},set(n){let s=t.value;s!==n&&(t.value=n,t.notify(s))},subscribe(n){let s=t.listen(n);return n(t.value),s},value:r};return process.env.NODE_ENV!=="production"&&(t[us]=()=>{e=[],t.lc=0,t.off()}),t},je=(r={})=>{let e=fs(r);return e.setKey=function(t,n){let s=e.value;typeof n>"u"&&t in e.value?(e.value={...e.value},delete e.value[t],e.notify(s,t)):e.value[t]!==n&&(e.value={...e.value,[t]:n},e.notify(s,t))},e};const Z=class Z{constructor(e){m(this,"$kv");m(this,"$localStreams");m(this,"$remoteStreams");m(this,"crdtStore");m(this,"replicaId");m(this,"sendChannels");this.peer=e,this.crdtStore={},this.$kv=je({}),this.$localStreams=je({}),this.$remoteStreams=je({}),this.sendChannels={},this.replicaId=e.peerId,e.onsession=t=>{const n=`${t.other.groupId}:${t.other.peerId}:${t.other.connId}`;this.sendChannels[n]=t.createDataChannel(Z.KV_NAMESPACE,{ordered:!0,maxRetransmits:3}),t.ondatachannel=i=>{console.log("debug:ondatachannel",i.channel.label),i.channel.label===Z.KV_NAMESPACE&&(i.channel.onmessage=o=>{const a=JSON.parse(o.data);console.log("debug:onmessage",{update:a}),this.receiveUpdate(a.key,a.entry)},i.channel.onopen=o=>{console.log("debug:sync",{crdt:this.crdtStore});for(const[a,c]of Object.entries(this.crdtStore))console.log("debug:notifying",{key:a,entry:c}),this.notifyPeer(this.sendChannels[n],{key:a,entry:c})})},t.ontrack=i=>{for(const o of i.streams){const a=`${n}:${o.id}`;this.$remoteStreams.setKey(a,o)}},t.onconnectionstatechange=i=>{t.connectionState==="failed"&&(delete this.sendChannels[n],console.log(`connection failed, removed ${n}`))};const s=Object.entries(this.$localStreams.get());for(const[i,o]of s)for(const a of o.getTracks())t.addTrack(a,o)},this.$kv.listen((t,n,s)=>{const i=t[s];this.set(s,i)})}async addUserMedia(e){const t=await navigator.mediaDevices.getUserMedia(e);this.addMediaStream(t)}async addDisplayMedia(e){const t=await navigator.mediaDevices.getDisplayMedia(e);this.addMediaStream(t)}addMediaStream(e){this.$localStreams.setKey(e.id,e)}start(){this.peer.start()}close(){this.peer.close()}set(e,t){const n=this.crdtStore[e];if(n&&n.value===t)return;const s={value:t,timestamp:Date.now(),replicaId:this.replicaId};this.notifyPeers(e,s)}notifyPeer(e,t){e.send(JSON.stringify(t))}notifyPeers(e,t){const n={key:e,entry:t};for(const s of Object.values(this.sendChannels))this.notifyPeer(s,n)}receiveUpdate(e,t){const n=this.crdtStore[e];if(console.log("debug:received_update",{key:e,remoteEntry:t,currentEntry:n}),!n)this.crdtStore[e]=t,this.$kv.setKey(e,t.value),console.log("debug:received_update accepted (resolution=empty)",t);else if(t.timestamp>n.timestamp)this.crdtStore[e]=t,this.$kv.setKey(e,t.value),console.log("debug:received_update accepted (resolution=older)",t);else if(t.timestamp===n.timestamp&&t.replicaId>this.replicaId)this.crdtStore[e]=t,this.$kv.setKey(e,t.value),console.log("debug:received_update accepted (resolution=replicaId)",t);else{console.log("debug:received_update ignored remote update",{remoteEntry:t,currentEntry:n});return}}};m(Z,"KV_NAMESPACE","__crdt_kv");let Be=Z;se.disableLog(!1),se.disableWarnings(!1),console.log("UA: ",navigator.userAgent),console.log("webrtc-adapter is enabled",JSON.stringify({shim:se.browserShim,version:se.browserDetails},null,2)),O.Peer=nn,O.PeerStore=Be,O.createPeer=ls,Object.defineProperty(O,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,7 +1,10 @@
1
1
  {
2
2
  "name": "@pulsebeam/peer",
3
- "version": "0.0.21",
3
+ "version": "0.1.0-rc.2",
4
4
  "type": "module",
5
+ "files": [
6
+ "dist"
7
+ ],
5
8
  "main": "./dist/index.cjs",
6
9
  "module": "dist/index.mjs",
7
10
  "types": "dist/index.d.mts",
@@ -16,17 +19,15 @@
16
19
  }
17
20
  },
18
21
  "scripts": {
19
- "gen": "protoc --ts_out=. --experimental_allow_proto3_optional --ts_opt=client_generic --proto_path proto/v1 ./proto/v1/signaling.proto && node ./scripts/patch.cjs",
20
- "build": "tsup",
21
- "build:watch": "tsup --watch",
22
+ "gen": "bash ./generate.bash",
23
+ "dev": "vite",
24
+ "build": "tsup src/index.ts --format esm,cjs --dts --minify",
22
25
  "clean": "rm -rf dist",
23
26
  "test": "vitest",
27
+ "preview": "vite preview",
24
28
  "show:docs": "npx deno doc --html index.ts && python -m http.server -d docs/",
25
29
  "publish": "jsr publish --allow-slow-types"
26
30
  },
27
- "files": [
28
- "dist"
29
- ],
30
31
  "keywords": [
31
32
  "typescript",
32
33
  "library",
@@ -43,29 +44,17 @@
43
44
  "@protobuf-ts/grpcweb-transport": "^2.9.5",
44
45
  "@protobuf-ts/runtime": "^2.9.4",
45
46
  "@protobuf-ts/runtime-rpc": "^2.9.4",
46
- "jwt-decode": "^4.0.0"
47
+ "jwt-decode": "^4.0.0",
48
+ "nanostores": "^0.11.4"
47
49
  },
48
50
  "devDependencies": {
49
51
  "@protobuf-ts/plugin": "^2.9.4",
50
52
  "jsr": "^0.13.2",
51
53
  "protoc-gen-ts": "^0.8.7",
52
- "tsup": "^8.3.6",
53
- "typescript": "^5.6.3",
54
+ "tsup": "^8.4.0",
55
+ "typescript": "^5.7.2",
56
+ "vite": "^6.2.0",
54
57
  "vitest": "^3.0.5",
55
58
  "webrtc-adapter": "^9.0.1"
56
- },
57
- "tsup": {
58
- "entry": [
59
- "index.ts"
60
- ],
61
- "format": [
62
- "esm",
63
- "cjs"
64
- ],
65
- "dts": true,
66
- "minify": true,
67
- "sourcemap": true,
68
- "target": "esnext",
69
- "outDir": "dist"
70
59
  }
71
60
  }