@urun-sh/core 0.6.29 → 0.6.30

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.
@@ -26,4 +26,4 @@ self.onrtctransform = (event) => {
26
26
  }
27
27
  `;function wn(i){let e=i.match(/a=rtpmap:(\d+) opus\/48000\/2/)?.[1];if(!e)return i;let t="usedtx=1;useinbandfec=1;maxaveragebitrate=32000",n=!1,r=i.split(`\r
28
28
  `).map(s=>s.startsWith(`a=fmtp:${e} `)&&!s.includes("usedtx=")?(n=!0,`${s};${t}`):s);if(!n){let s=r.findIndex(o=>o===`a=rtpmap:${e} opus/48000/2`);s>=0&&r.splice(s+1,0,`a=fmtp:${e} ${t}`)}return r.join(`\r
29
- `)}var Be=class{constructor(e){this.sink=e}sink;frameSeq=0;stopped=!1;deadCb=null;sendPc=null;recvPc=null;sender=null;currentTrack=null;renderSender=null;renderRemoteCb=null;renderEndedListener=null;worker=null;workerUrl=null;nodeBridge=null;endedListener=null;candQueue=null;negotiatedOnce=!1;negotiating=!1;renegotiateQueued=!1;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.currentTrack&&e.readyState==="live")return;let t=null;if(!(e!==null&&(t=Fr(e)?this.bridgedTrack(e):e,!t))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(t)}catch(n){this.die(`replaceTrack: ${n instanceof Error?n.message:String(n)}`);return}this.currentTrack=t,t&&this.wireTrackLiveness(t);return}t!==null&&this.engage(t)}}stop(){if(!this.stopped){this.stopped=!0,this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(e){let t=globalThis;if(typeof t.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof t.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let n;try{n=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let r=this.sendPc.addTrack(e);this.sender=r,this.currentTrack=e,this.wireTrackLiveness(e);let s=t.RTCRtpScriptTransform;if(r.transform=new s(n,{role:"sender"}),this.negotiatedOnce){this.negotiate().catch(o=>this.die(`loopback renegotiate: ${o instanceof Error?o.message:String(o)}`));return}this.negotiate().catch(o=>this.die(`loopback negotiate: ${o instanceof Error?o.message:String(o)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let t=e.RTCPeerConnection;this.sendPc=new t({iceServers:[]}),this.recvPc=new t({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=n=>{if(!n.candidate)return;let r=this.candQueue;r!==null&&(r.toRecv.push(n.candidate),this.flushCandidates())},this.recvPc.onicecandidate=n=>{if(!n.candidate)return;let r=this.candQueue;r!==null&&(r.toSend.push(n.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(n=>this.die(`loopback renegotiate: ${n instanceof Error?n.message:String(n)}`))},this.recvPc.ontrack=n=>{let r=n.transceiver?.mid??null;r!==null&&r===this.renderMidOf()&&this.renderRemoteCb?.(n.track)}}setRenderSource(e){if(!this.stopped){if(e===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(e);else try{this.renderSender.replaceTrack(e)}catch(t){this.die(`render replaceTrack: ${t instanceof Error?t.message:String(t)}`);return}this.wireRenderRemote(e),!this.negotiatedOnce&&this.sender&&this.negotiate().catch(t=>this.die(`loopback negotiate: ${t instanceof Error?t.message:String(t)}`))}}}onRenderTrack(e){this.renderRemoteCb=e}renderMidOf(){if(!this.renderSender)return null;let e=this.sendPc;try{return e.getTransceivers?.().find(t=>t.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(e){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},e.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let e=this.sendPc,t=this.recvPc;if(!(!e||!t||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let n=await e.createOffer();n.sdp=wn(n.sdp??""),await e.setLocalDescription(n),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:n.sdp});let r=await t.createAnswer();r.sdp=wn(r.sdp??""),await t.setLocalDescription(r),await e.setRemoteDescription(t.localDescription??{type:"answer",sdp:r.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let e=this.candQueue;if(e){for(;e.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(e.toSend.shift())).catch(()=>{});for(;e.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(e.toRecv.shift())).catch(()=>{})}}bridgedTrack(e){let t=e;try{let n=t.context.createMediaStreamDestination();t.connect(n);let r=n.stream.getAudioTracks()[0]??null;return r?(this.nodeBridge={node:t,dest:n},r):(this.die("AudioNode bridge produced no audio track"),null)}catch(n){return this.die(`AudioNode bridge: ${n instanceof Error?n.message:String(n)}`),null}}wireTrackLiveness(e){this.endedListener=()=>this.die("mic track ended"),e.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([Nr],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=t=>{let n=t.data;n?.type==="enc"&&n.payload instanceof ArrayBuffer?this.onEncodedFrame(n.rtpTimestamp??0,new Uint8Array(n.payload)):n?.type==="err"&&this.die(`transform: ${n.detail??"unknown"}`)},e.onerror=t=>this.die(`transform worker: ${t.message||"error"}`),this.worker=e,e}onEncodedFrame(e,t){if(this.stopped)return;let n=Rt(this.frameSeq,e,t,this.sink.maxDatagramSize()||pe);if(n===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let r of n)this.sink.send(r);this.frameSeq=this.frameSeq+1>>>0}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function Fr(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var $r=9e4,qr="avc1.42E01F",Br=60,Hr=3,jr=1e4;function Vr(i){return Math.round(i*($r/1e6))%2**32>>>0}var He=class{constructor(e){this.sink=e}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}requestKeyframe(){this.keyframeWanted=!0}setSource(e){if(this.stopped||(this.teardownCapture(),e===null))return;let n=globalThis.MediaStreamTrackProcessor;if(typeof n!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let r=++this.generation,s=new n({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,s.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&r===this.generation;){let{value:a,done:d}=await s.read();if(d)break;if(a){if(o||this.stopped||r!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&r===this.generation&&this.die(`capture: ${a instanceof Error?a.message:String(a)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){this.cancelCapture?.(),this.cancelCapture=null,this.generation++}encodeFrame(e){let t={width:e.codedWidth,height:e.codedHeight};if(!this.encoder||!this.encoderDims||this.encoderDims.width!==t.width||this.encoderDims.height!==t.height){let s=globalThis.VideoEncoder;if(typeof s!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new s({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)})),this.encoderDims=t,this.encoder.configure({codec:qr,avc:{format:"annexb"},width:t.width,height:t.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(o){e.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${o instanceof Error?o.message:String(o)}`);return}}let r=this.keyframeWanted||this.framesSinceKeyframe>=Br;this.keyframeWanted=!1,this.framesSinceKeyframe=r?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:r})}catch(s){this.onEncoderError(s instanceof Error?s:new Error(String(s)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let n=Rt(this.frameSeq,Vr(e.timestamp),t,this.sink.maxDatagramSize()||pe,{lane:fn,keyframe:e.type==="key"});if(n===null){console.warn(`[urun] WT video uplink: AU of ${t.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let r of n)this.sink.send(r);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(n=>t-n<jr),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=Hr){this.die(`video encoder: ${e.message}`);return}console.warn("[urun] WT video uplink encoder error \u2014 re-initializing:",e.message);try{this.encoder?.close()}catch{}this.encoder=null,this.encoderDims=null}die(e){this.stopped||(console.warn(`[urun] WT video uplink lane dead (${e}) \u2014 the camera reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function Gr(i){return i.byteLength>=2&&i[0]===1&&i[1]===3}var je=class{constructor(e){this.transport=e}transport;streams=new Map;dead=null;deadCb=null;chain=Promise.resolve();onDead(e){this.deadCb=e}send(e,t){let n=new TextEncoder().encode(e);if(n.byteLength===0||n.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${n.byteLength})`));let r=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let s=this.streams.get(e);if(!s){let a=await this.transport.openUniStream(),d=new Uint8Array(2+n.byteLength);d[0]=1,d[1]=n.byteLength,d.set(n,2),await a.write(d),s={writer:a},this.streams.set(e,s)}let o=new Uint8Array(4+t.byteLength);new DataView(o.buffer).setUint32(0,t.byteLength,!0),o.set(t,4),await s.writer.write(o),Gr(t)&&(this.streams.delete(e),await s.writer.close().catch(()=>{}))}catch(s){throw this.die(s instanceof Error?s.message:String(s)),s}});return this.chain=r.catch(()=>{}),r}stop(e="stopped"){if(this.dead===null){this.dead=e;for(let t of this.streams.values())t.writer.close().catch(()=>{});this.streams.clear()}}die(e){this.dead===null&&(console.warn(`[urun] WT data uplink lane dead (${e})`),this.stop(e),this.deadCb?.(e))}};var yn=250,Kr=25,zr=2e3,Yr=15e3,Qr=1e3,Xr=45e3,Jr=5e3,Zr={llm:!0},ei=500,bn=10,ti=2,ni=2,At=2,he=class i{constructor(e,t,n,r,s,o,a){this.offer=e;this.sessionId=t;this.canvas=n;this.audioLane=r;this.audioUplink=s;this.videoUplink=o;this.dataUplink=a;this.firstMedia=new Promise((d,l)=>{this.firstFrameResolve=d,this.firstFrameReject=l}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorLogged=!1;writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;stallWatch=null;stallTimer=null;audioLaneLastArrivalAt=null;lastInboundControlAt=null;lastInboundDataAt=null;firstInboundDataAt=null;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new ue({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=this.offer.codec,n=t!==void 0&&t!=="";this.hasVideoLane=n,n&&St(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(c=>({algorithm:"sha-256",value:Uint8Array.from(atob(c),p=>p.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let r=await this.wt.createBidirectionalStream();this.writer=r.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let s=r.readable.getReader(),o=new ce,a=[],d=await this.readControl(s,o,a);if(d?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");let l=d;if(this.lastInboundControlAt=performance.now(),typeof l.pingIntervalMs=="number"&&l.pingIntervalMs>0?this.advertisedPingIntervalMs=l.pingIntervalMs:this.noCadenceLogged||(this.noCadenceLogged=!0,console.warn("[urun] gateway advertises no liveness cadence (pre-#2826 or mid-roll gateway) \u2014 the downlink-stall watch will never judge this leg dead on silence alone")),n&&(St(l.codec,"hello-ack"),this.initDecoder(l.codec,l.width,l.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let c={setSource:u=>{this.renderSource=u,this.audioUplinkLane?.setRenderSource?.(u)},onRemote:u=>{this.renderRemoteCb=u}},p=new qe(this.offer.audio,{...this.audioLane,renderHop:c});try{p.start(),this.audioPlayout=p}catch(u){console.warn(`[urun] WT audio lane failed to start (${u instanceof Error?u.message:String(u)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),p.stop()}}if(this.offer.audioUp===!0&&this.audioUplink&&this.engageUplinkLane("audio"),this.offer.videoUp===!0&&this.videoUplink&&this.engageUplinkLane("video"),this.offer.dataUp===!0&&this.dataUplink)try{let c=this.wt.createUnidirectionalStream?.bind(this.wt);if(!c)throw new Error("WebTransport uni streams are not creatable in this environment");let p=new je({openUniStream:async()=>(await c()).getWriter()});p.onDead(u=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(u,p)}),this.dataUplinkSender=p,this.dataUplink.onUplink(p)}catch(c){let p=c instanceof Error?c.message:String(c);console.warn(`[urun] WT data uplink failed to engage (${p}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(p)}this.controlLoop(s,o,a).catch(c=>this.die(`control loop: ${c}`)),this.datagramLoop().catch(c=>this.die(`datagram loop: ${c}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),ei)),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(c=>{this.closedReason=`connection error: ${c}`,this.die(`connection error: ${c}`)})}pathLiveness(){return this.closedReason?{alive:!1,evidence:`quic session closed (${this.closedReason})`}:this.controlWriteError?{alive:!1,evidence:`quic control stream refused a write (${this.controlWriteError}) \u2014 the send path is gone`}:this.stopped?{alive:!1,evidence:"webtransport session stopped"}:{alive:!0,evidence:`quic session open; ${this.controlWritesAccepted} control frames accepted by the QUIC stack (one per ${yn}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Yr},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Qr))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let t=typeof e.ds=="number"?e.ds:null,n=typeof e.ur=="number"?e.ur:null;if(t===null&&n===null)return;this.gatewayExposesCounters=!0;let r=this.audioDgramsReceived,s=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:n,recvDownlink:r,sentUplink:s},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,d=n!==null&&o.ur!==null?n-o.ur:null,l=r-o.recvDownlink,c=s-o.sentUplink,p="none";if(a!==null&&a>=bn&&l<=0?p="downlink":d!==null&&c>=bn&&d<=0&&(p="uplink"),p==="none"){this.severedStreak="none",this.observePlayoutProgress(l,t);return}if(this.severedStreak!==p){this.severedStreak=p;return}this.severedStreak="none";let u=p==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${c} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+u+` (gateway flow counters ds=${t} ur=${n}, client received=${r} accepted=${s}, confirmed on ${ti} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,t){let n=this.audioPlayout;if(!n){this.playoutScheduledSeen=null;return}let r=n.playoutProgress(),s=r.surfaced;if(this.playoutScheduledSeen!==null&&r.scheduled>this.playoutScheduledSeen&&s){this.playoutScheduledSeen=r.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=r.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<ni)){if(!this.playoutStallRebuilt){this.playoutStallRebuilt=!0,this.playoutStallStreak=0,console.warn(`[urun] WT playout stalled while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${r.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{n.rebuildSurface()}catch(o){console.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=At}return}this.playoutStallStreak<At||(this.playoutStallStreak=0,this.playoutStallRebuilt=!1,this.die(`playout stalled past its in-place surface rebuild while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${r.scheduled} on ${At} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let t=this.pathLiveness();if(!t.alive)return;let n=performance.now(),r=this.audioLaneLastArrivalAt===null?null:n-this.audioLaneLastArrivalAt,s=this.lastInboundControlAt===null?null:n-this.lastInboundControlAt,o=r===null&&s===null?!0:(r===null||r>=e.stallMs)&&(s===null||s>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&s!==null&&s>=2*a){this.die(`downlink stall: the gateway advertised a ${Math.round(a/1e3)}s liveness cadence but delivered no inbound frame of any kind for ${Math.round(s/1e3)}s while the path reports alive (${t.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}let d=!!(this.offer.audio&&this.audioLane),l=this.lastInboundDataAt===null?null:n-this.lastInboundDataAt,c=r!==null?r:this.firstInboundDataAt===null?null:n-this.firstInboundDataAt,p=c!==null&&c>=e.stallMs;if(d&&p&&l!==null&&l<=Jr&&this.gatewayPings>0){this.die(`media-starved leg: no audio datagram for ${Math.round((c??0)/1e3)}s while the data lane delivered a frame ${Math.round((l??0)/1e3)}s ago (${this.gatewayPings} gateway pings; ${t.evidence}) \u2014 the reliable lanes are alive so the application is mid-conversation, and a dark audio lane under it is severed media fanout, never an idle application; re-dialing`);return}o&&s!==null&&s>=Xr&&this.gatewayPings>0&&this.die(`one-way downlink stall: the gateway pinged this leg before (its downlink pipe demonstrably worked) but NOTHING has arrived \u2014 no audio datagram, no inbound control frame \u2014 for ${Math.round(s/1e3)}s while the path reports alive (${t.evidence}) and client control writes keep resolving \u2014 the downlink is severed in one direction; re-dialing (owner ruling 2026-09-26)`)}async stop(){this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks("webtransport session stopped"),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}datagramWriter(){if(!this.dgramWriter){let e=this.wt.datagrams.writable;if(!e)throw new Error("WebTransport datagrams are not writable in this environment");this.dgramWriter=e.getWriter()}return this.dgramWriter}releaseDatagramWriter(){let e=this.dgramWriter;if(e){this.dgramWriter=null;try{e.releaseLock?.()}catch{}}}dropUplinks(e){this.dropDatagramUplinks(e);let t=this.dataUplinkSender;t&&(this.dataUplinkSender=null,t.stop(e),this.dataUplink?.onUplinkLost(e,t))}dropDatagramUplinks(e){if(this.clearUplinkRetryTimers(),this.audioUplinkLane!==null||this.audioUplinkRetry!==null){let r=this.audioUplinkLane;r?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e,r??void 0)}if(this.videoUplinkLane!==null||this.videoUplinkRetry!==null){let r=this.videoUplinkLane;r?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e,r??void 0)}}onDead(e){this.deadCb=e}stats(){return this.lastStats}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");let t={onData:(n,r)=>{if(Zr[n]===!0){let s=performance.now();this.firstInboundDataAt===null&&(this.firstInboundDataAt=s),this.lastInboundDataAt=s}e.onData(n,r)},onLaneError:n=>e.onLaneError(n)};this.dataLaneSink=t,kt(this.wt.incomingUnidirectionalStreams,t).catch(n=>{this.die(`data lane: ${n instanceof Error?n.message:String(n)}`)})}initDecoder(e,t,n){let r=globalThis.VideoDecoder;if(typeof r!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let s=this.canvas.getContext("2d");if(!s)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:n};let o=new r({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,s.drawImage(a,0,0),a.close()},error:a=>this.onDecoderError(a)});o.configure({codec:e,...t>0&&n>0?{codedWidth:t,codedHeight:n}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"}),this.decoder=o}onDecoderError(e){if(this.stopped||this.deadFired)return;console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=this.decoderConfig;if(!t){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder error with no retained config to re-init from \u2014 video stays down: ${e.message}`));return}try{this.initDecoder(t.codec,t.width,t.height),this.decoderErrorLogged=!1}catch(n){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${n instanceof Error?n.message:String(n)}`));return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}uplinkSend(e,t){if(this.stopped||this.deadFired)return;this.datagramWriter().write(e).then(t,r=>this.onUplinkSendError(r))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let t=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,console.error(`[urun] WT uplink datagram send FAILED (${t}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let n=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(r=>n-r<zr),this.uplinkSendErrorsAt.push(n),!(this.uplinkSendErrorsAt.length<Kr)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSink(e){this.datagramWriter();let t=0;return{send:n=>this.uplinkSend(n,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??pe}}engageAudioUplink(){let e=new Be(this.uplinkSink("audio"));e.onDead(t=>this.onUplinkLaneDead("audio",t,e)),e.onRenderTrack?.(t=>this.renderRemoteCb?.(t)),this.renderSource&&e.setRenderSource?.(this.renderSource),this.audioUplinkLane=e,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(e)}engageVideoUplink(){let e=new He(this.uplinkSink("video"));e.onDead(t=>this.onUplinkLaneDead("video",t,e)),this.videoUplinkLane=e,this.videoUplinkRetry=this.freshLaneBuilt(this.videoUplinkRetry),this.videoUplink.onUplink(e)}engageUplinkLane(e){let t=e==="audio"?"mic":"video";try{e==="audio"?this.engageAudioUplink():this.engageVideoUplink()}catch(n){let r=n instanceof Error?n.message:String(n);console.warn(`[urun] WT ${t} uplink failed to engage (${r}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,r)}}freshLaneBuilt(e){let t={count:e?.count??0,builtAt:Date.now(),timer:void 0};return e&&(clearTimeout(e.timer),e.timer=void 0),t}onUplinkLaneDead(e,t,n){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let r=e==="audio"?"mic":"video",s=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,a=s?.builtAt!=null&&Date.now()-s.builtAt>=i.UPLINK_LANE_HEALTHY_MS?1:(s?.count??0)+1;if(a>i.UPLINK_LANE_RETRY_MAX){console.error(`[urun] WT ${r} uplink lane dead (${t}) \u2014 ${i.UPLINK_LANE_RETRY_MAX} recovery attempts exhausted; the lane is down until the transport's own revert runs (onUplinkLost)`),e==="audio"?this.audioUplinkRetry=null:this.videoUplinkRetry=null,this.seamUplinkLost(e,`lane dead after ${i.UPLINK_LANE_RETRY_MAX} recovery attempts: ${t}`,n);return}console.warn(`[urun] WT ${r} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${a}/${i.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let d={count:a,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=d:this.videoUplinkRetry=d,d.timer=setTimeout(()=>{d.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},i.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,t,n){e==="audio"?this.audioUplink.onUplinkLost(t,n):this.videoUplink.onUplinkLost(t,n)}clearUplinkRetryTimers(){for(let e of[this.audioUplinkRetry,this.videoUplinkRetry])e&&(clearTimeout(e.timer),e.timer=void 0)}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:n}=await e.read();if(n)break;if(!t)continue;if(t.byteLength>=P&&t[11]===Fe){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let r=performance.now();if(this.lastArrivalTs>0){let s=r-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(s-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=r,this.reassembler.push(t)}}decodeFrame(e,t,n){let r=globalThis.EncodedVideoChunk;if(typeof r=="function"){if(!this.decoder&&this.decoderConfig)try{this.initDecoder(this.decoderConfig.codec,this.decoderConfig.width,this.decoderConfig.height),this.decoderErrorLogged=!1}catch{return}this.decoder&&(this.decoder.decode(new r({type:t?"key":"delta",timestamp:e*(1e6/24),data:n})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(yt(e)),this.controlWritesAccepted++}catch(t){let n=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=n),this.die(`control stream write refused: ${n}`),t}}async sendControlRaw(e){try{let t=new Uint8Array(4+e.byteLength);new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),await this.writer.write(t),this.controlWritesAccepted++}catch(t){let n=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=n),this.die(`control stream write refused: ${n}`),t}}async readControl(e,t,n=[]){for(;;){let r=n.shift();if(r)return r;let{value:s,done:o}=await e.read();if(o)return null;s&&n.push(...t.push(s))}}async controlLoop(e,t,n){for(;!this.stopped;){let r=await this.readControl(e,t,n);if(!r)break;let s=r;if(this.lastInboundControlAt=performance.now(),s.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(hn(r.raw,"pong"))}catch{}}(s.t==="ping"||s.t==="pong")&&this.observeFlowCounters(s),s.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),n=(t-e)/1e3;e=t;let r=this.reassembler.drainWindow(),s=r.delivered+r.abandoned;this.lastStats={recvBps:n>0?r.bytes*8/n:0,lossPct:s>0?100*r.abandoned/s:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},yn)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks(e),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var Sn=2500,kn=["av01.0.08M.08","avc1.42E01F","avc1.640028"],ri=1e4,me=class i{constructor(e,t,n){this.signaling=e;this.sessionId=t;this.opts=n}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;static WT_REDIAL_BASE_MS=2e3;static WT_REDIAL_MAX=3;static WT_REDIAL_CAP_MS=3e4;wtRedialFailures=0;wtRedialTimer=null;wtDialedHost;wtHostMismatchCount=0;disconnected=!1;downlinkStallWatch=null;watchDownlinkStall(e={}){this.downlinkStallWatch={stallMs:e.stallMs??15e3},this.applyStallWatch()}applyStallWatch(){let e=this.session;!e||e.kind!=="webtransport"||!this.downlinkStallWatch||e.watchDownlinkStall?.(this.downlinkStallWatch)}failCurrentWtLeg(e){if(this.disconnected)return;let t=this.session;!t||t.kind!=="webtransport"||t.fail?.(e)}get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis;this.disconnected=!1;let t=typeof e.WebTransport=="function",n=typeof e.VideoDecoder=="function",r=this.opts.allowWebTransport??!0,s={webtransport:t&&n&&r,webcodecs:n,codecs:kn,wtData:t&&n&&r&&this.opts.dataLane!==void 0,wtAudio:t&&n&&r&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&r&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:t&&n&&r&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&n&&r&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:s}),this.noteOfferedWtHost();let o=s.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,d=o&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(d||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),s.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let l=null;try{return l=this.createWebTransportSession(),await Ct(l.start(),this.opts.quicDeadlineMs??Sn,"quic connect deadline"),this.wtDialedHost=Et(this.offer.webtransport?.url)??this.wtDialedHost,this.engageQuicDataLane(l,s.wtData===!0),this.session=l,d&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(c){if(console.warn(`[urun] WT dial failed (${fe(c)}) \u2014 dialed ${_n(this.offer.webtransport?.url)}`),l?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let p=String(c instanceof Error?c.message:c);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${p}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(p),c}console.warn("[urun] webtransport failed, falling back to webrtc:",c),this.proceedWebRtcDial(`wt failed: ${String(c instanceof Error?c.message:c)}`),this.notifyEstablished("webrtc",String(c instanceof Error?c.message:c))}}if(this.opts.allowWebRtcFallback===!1){let l=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${l} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(l),new Error(`[urun] WT required but unavailable: ${l}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.disconnected=!0,this.wtRedialTimer!==null&&(clearTimeout(this.wtRedialTimer),this.wtRedialTimer=null),this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,await e?.stop()}noteOfferedWtHost(){let e=Et(this.offer?.webtransport?.url);e===void 0||this.wtDialedHost===void 0||e===this.wtDialedHost||(this.wtHostMismatchCount+=1,console.error(`[urun] re-dial offered host ${e} != original host ${this.wtDialedHost}`+(ii(e)?" \u2014 the offered host looks INTERNAL (RFC1918/.internal): an external browser cannot dial it":"")+` (mismatch #${this.wtHostMismatchCount}) \u2014 evidence only, no policy change`))}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let n=this.session,r=this.opts.dataLane!==void 0,s=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",o=this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",a=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",d=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:kn,wtData:r,wtAudio:s,wtAudioUp:o,wtVideoUp:a,wtDataUp:d}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let l=this.createWebTransportSession();try{await Ct(l.start(),this.opts.quicDeadlineMs??Sn,"quic connect deadline")}catch(c){throw console.warn(`[urun] WT dial failed (${fe(c)}) \u2014 dialed ${_n(this.offer.webtransport?.url)}`),l.stop().catch(()=>{}),c}if(this.wtDialedHost=Et(this.offer.webtransport?.url)??this.wtDialedHost,this.session!==n)return l.stop().catch(()=>{}),null;try{this.engageQuicDataLane(l,r)}catch(c){throw l.stop().catch(()=>{}),c}if(this.disconnected)return l.stop().catch(()=>{}),null;this.session=l;{let c=this.offer.webtransport;c&&(this.opts.audioLane===void 0||c.audio!==void 0)&&(this.opts.audioUplink===void 0||c.audioUp===!0)&&(this.opts.videoUplink===void 0||c.videoUp===!0)&&(this.opts.dataLane===void 0||c.data===!0)&&(this.opts.dataUplink===void 0||c.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),n?.stop().catch(()=>{}),l}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let n=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(r,s)=>n.onData(r,s),onLaneError:r=>n.onLaneError(r)}),n.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e,this.opts.audioLane);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new he(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;this.wtRedialFailures=0,this.applyStallWatch(),e.onDead(t=>{if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; re-dialing WT (attempt 1 immediate, then the bounded ladder)`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.redialWtAfterDeath(t,!0);return}let n=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),n){this.session=null,this.wtOnlyLeg=!1,console.warn("[urun] quic died mid-session on a WT-only leg \u2014 RE-DIALING WebTransport first (same session id; the late WebRTC dial is the fallback):",t),this.redialWtAfterDeath(t,!0);return}console.warn("[urun] quic died mid-session, failing over to webrtc:",t),this.lateWebRtcFailover(e,t,n)})}redialWtAfterDeath(e,t=!1){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures>=i.WT_REDIAL_MAX){if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT re-dial failed ${i.WT_REDIAL_MAX} times (${e}) \u2014 WT-REQUIRED policy: no WebRTC floor exists to escalate to; the forever-retry continues in the background`),this.opts.onWtRequiredOutage?.(e);return}console.error(`[urun] WT re-dial failed ${i.WT_REDIAL_MAX} times (${e}) \u2014 standing up the deferred WebRTC dial as the floor; WT keeps retrying in the background`),this.proceedWebRtcDial(`wt re-dial spent: ${e}`),this.lateWebRtcFailover(null,e,!0);return}let n=this.wtRedialFailures+1,r=Dt(i.WT_REDIAL_BASE_MS,n,i.WT_REDIAL_CAP_MS,n===1&&t?0:void 0);console.warn(`[urun] WT re-dial attempt ${n} scheduled in ${Math.round(r)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},r)}async attemptWtRedial(e){if(!(this.disconnected||this.session!==null)){if(this.signaling.isOpen?.()===!1){this.redialWtAfterDeath(`${e}; signaling socket closed \u2014 waiting for the reconnect`);return}this.wtRedialFailures+=1;try{if(await this.retryWebTransport()!==null){console.warn(`[urun] WT leg re-established on the live session (re-dial attempt ${this.wtRedialFailures}/${i.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(t){let n=fe(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${i.WT_REDIAL_MAX} failed (${n}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${n}`)}}}lateWebRtcFailover(e,t,n){this.disconnected||(async()=>{let r=this.createWebRtc();try{let s=await Ct(this.startWebRtcOn(r),this.opts.webRtcFailoverDeadlineMs??ri,"webrtc failover produced no media transport");if(this.session!==e){s.stop().catch(()=>{});return}this.session=s,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(s){if(r.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=s instanceof Error?s.message:String(s),a=n?`media transport lost \u2014 the WebTransport connection dropped (${t}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${t}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;console.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function fe(i){if(i instanceof Error)return i.message;if(typeof i=="string")return i;if(i&&typeof i=="object"){try{let e=JSON.stringify(i);if(e!==void 0&&e!=="{}")return e}catch{}return i.constructor?.name??Object.prototype.toString.call(i).slice(8,-1)}return String(i)}function Et(i){if(i)try{return new URL(i).host}catch{return}}function _n(i){if(!i)return"(no offer url)";try{let e=new URL(i);return e.searchParams.delete("token"),e.toString()}catch{return i.replace(/[?&]token=[^&\s]*/g,"")}}function ii(i){if(!i)return!1;let e=i.replace(/^\[/,"").split("]")[0]?.split(":")[0]??"";return/^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(e)?!0:e.endsWith(".internal")||e.endsWith(".svc.cluster.local")||/^ip-\d+(-\d+)+/.test(e)}function Dt(i,e,t,n){if(n!==void 0)return n;let r=Math.min(i*2**Math.max(0,e-2),t);return Math.round(r*(.75+Math.random()*.5))}function Ct(i,e,t){return new Promise((n,r)=>{let s=setTimeout(()=>r(new Error(t)),e);i.then(o=>{clearTimeout(s),n(o)},o=>{clearTimeout(s),r(o)})})}var si=1e4,ge=class{constructor(e,t=si){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let n=Ie();return new Promise((r,s)=>{let o=setTimeout(()=>{a(),s(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(d=>{if(d.type!==`${e}.response`||d.requestId!==n)return;if(clearTimeout(o),a(),d.error){s(new Error(`[urun] ${e} failed: ${String(d.error)}`));return}let{type:l,requestId:c,...p}=d;r(p)});this.carrier.sendSignal({type:e,requestId:n,...t})||(clearTimeout(o),a(),s(new Error(`[urun] signaling request not sent: ${e} \u2014 the signaling socket is not open`)))})}notify(e,t){this.carrier.sendSignal({type:e,...t})||this.carrier.emitDiagnostic({level:"warning",kind:"signaling-notify-undelivered",message:`signaling notify not sent: ${e} \u2014 the signaling socket is not open`,detail:{method:e}})}on(e,t){return this.carrier.onSignal(n=>{n.type===e&&t(n)})}};var oi="video",ve=class{constructor(e,t=oi){this.transport=e;this.streamName=t;this.firstMedia=new Promise((n,r)=>{this.firstMediaResolve=n,this.firstMediaReject=r}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let n=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(n(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(n)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};function Tn(i){let e=i;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var ai="video";var di=45e3;async function ci(i,e,t){let r=e?.current()?.name??null;if(r==="live")return"live";if(r==="error")return"gone";if(r==="idle"||r==="connecting")return"live";if(!e)return"unconfirmed";let s=e,o=t.runtimeWaitCapMs??di;return new Promise(a=>{let d=!1,l,c=null,p=null,u=!1,f=g=>{d||(d=!0,h(),p!==null&&(clearTimeout(p),p=null),l?.(),a(g))};p=setTimeout(()=>{if(u||d||t.isDisposed())return;u=!0;let g=s.current();i.emitDiagnostic({level:"info",kind:"runtime-pending",message:`waiting for a runtime to pick up session ${t.sessionId} (server status: ${g?.reason??g?.name??"unknown"}) \u2014 media negotiation starts once the runtime is live; this is not a transport failure`})},2e3);let y=()=>{c===null&&!d&&(c=setTimeout(()=>f("unconfirmed"),o))},h=()=>{c!==null&&(clearTimeout(c),c=null)};l=e.subscribe(g=>{let v=g?.name;if(v==="live")return f("live");if(v==="error")return f("gone");h(),Ae(v)||y()}),Ae(r)||y()})}function Rn(i,e,t){let n=globalThis,r=n.document;if(!(typeof r?.createElement=="function"&&typeof n.WebTransport=="function"&&typeof n.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=i.holdWebRtcDial?.(),a=r.createElement("canvas"),d=!1,l=null,c=!1,p=()=>{if(l){for(let S of l.getVideoTracks())try{S.stop()}catch{}l=null}c&&(c=!1,t.onOverrideTrack(null))},u=new me(new ge(i),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new ve(i,t.streamName??ai)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(S,A)=>i.dispatchQuicStreamData(S,A),onQuicLane:()=>i.markStreamDataLaneQuic(),onQuicLaneLost:S=>i.quicStreamDataLaneLost(S),onLaneError:S=>i.raiseQuicStreamDataError(S)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,ctx:t.audioPlayout?.audioContext,onTrack:S=>{d||(S&&i.noteQuicMediaFlowing?.(),t.onOverrideAudioTrack(S))}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>C(),onMediaTransportLost:S=>{d||(p(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(S),C())},onTransportChange:(S,A)=>{d||(S==="webrtc"&&(p(),C()),t.onTransportChange?.(S,A))}}),f=i.onWtOnlyLegDeath?.(S=>u.failCurrentWtLeg(S)),m=null,y=()=>{m!==null&&(clearInterval(m),m=null)},h=t.wtRetryBaseMs??2e3,g=t.wtRetryCapMs??3e4,v=null,R=0,C=()=>{if(d||v!==null||u.activeTransport==="webtransport")return;let S=Dt(h,R+2,g);v=setTimeout(()=>{v=null,R+=1,u.retryWebTransport().then(A=>{if(d){A&&u.disconnect().catch(()=>{});return}if(A)return console.debug(`[urun] webtransport upgraded in background (retry ${R})`),R=0,W(A);C()}).catch(A=>{d||(console.debug(`[urun] webtransport background retry ${R} failed: `+fe(A)),C())})},S)},E=()=>{v!==null&&(clearTimeout(v),v=null)},W=async S=>{if(d||S.kind!=="webtransport")return;let A=t.pathHealthProbeMs??1e4;y();let V=!1;m=setInterval(()=>{if(d||u.activeTransport!=="webtransport")return;let U=Tn(S);if(!U){console.error("[urun] BUG: webtransport session does not implement PathHealthReporting \u2014 the path-health probe cannot run and this leg cannot be judged; disarming (no verdict is better than a verdict derived from media arrival)"),y();return}let M=U.pathLiveness();if(!M.alive){let B=u.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${M.evidence}`+(B?" \u2014 this is a WT-ONLY leg (the WebRTC dial was skipped, so NO RTCPeerConnection and no webrtc track exist to fall back to)":" \u2014 a WebRTC floor exists and stays authoritative")+"; failing the leg so WT is re-established"),y(),U.fail(`path health: ${M.evidence}`);return}if(!V){if(V=!0,u.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${A}ms \u2014 the QUIC PATH IS HEALTHY (${M.evidence}), so this is an IDLE APPLICATION, not a dead path; keeping the leg (WT-only leg: no webrtc track exists) and continuing to watch the path`);return}console.warn(`[urun] webtransport established but no QUIC media after ${A}ms \u2014 no media datagrams reached this client (path healthy: ${M.evidence}); webrtc track remains authoritative`)}},A);try{await S.firstMedia}catch(U){y(),console.debug("[urun] webtransport ended before any media flowed:",U);return}if(y(),d||u.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;l=a.captureStream();let $=l.getVideoTracks()[0];$&&(c=!0,t.onOverrideTrack($))},x=!1;return(async()=>{let S=await ci(i,t.runtimePhase,{sessionId:e,runtimeWaitCapMs:t.runtimeWaitCapMs,isDisposed:()=>d});if(d)return;if(S==="gone"){console.debug(`[urun] session ${e} ended while waiting for a runtime to pick it up \u2014 no media negotiation`),o?.proceed("session ended before a runtime was pulled \u2014 releasing the held WebRTC dial");return}x=!0;let A=await u.connect();if(d){u.disconnect().catch(()=>{});return}await W(A)})().catch(S=>{if(y(),d){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",S);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",S),C();return}o?.proceed(`negotiation unavailable: ${S instanceof Error?S.message:String(S)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",S),C()}),{activeTransport:()=>u.activeTransport,mediaTransportAttempted:()=>x,watchDownlinkStall(S){u.watchDownlinkStall(S)},dispose(){d=!0,f?.(),y(),E(),p(),t.onOverrideAudioTrack?.(null),u.disconnect().catch(()=>{})}}}var li=new Set;function Pt(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var ui="rpc",pi="$presence",Cn=3e4,An=3e4,hi="rpc-resp";function fi(i){return`${hi}:${i}`}function It(){return Ie()}function mi(i){if(i&&typeof i=="object"){let e=i.error;if(e&&typeof e=="object"){let{message:t,code:n}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof n=="string"?n:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof i=="string"?i:JSON.stringify(i)}}function gi(i,e,t,n,r,s,o,a,d,l){let c=[],p=null,u=!1,f=null,m=!1,y,h,g=new Promise((w,_)=>{y=w,h=_});g.catch(()=>{});let v=o(),R=null,C=null,E=null,W=null,x=null,S=null,A=!0,V=()=>{E&&(clearTimeout(E),E=null),W&&(W(),W=null)},$=()=>{x&&(clearTimeout(x),x=null),S&&(S(),S=null)},U=!1,M=()=>{U||!m||(U=!0,i.set({rpc:{[e]:null}}))},B=()=>{A=!1,V(),$(),R?.(),R=null,C?.(),C=null,a?.removeEventListener("abort",k),v.dispose(),M()},J=()=>{if(p){if(c.length>0){let w=p;p=null,w.resolve({value:c.shift(),done:!1})}else if(f!==null){let w=p;p=null,w.reject(f)}else if(u){let w=p;p=null,w.resolve({value:void 0,done:!0})}}},Se=w=>{u||(c.push(w),J())},G=w=>{u||(f=w,u=!0,h(w),B(),J())},b=w=>{u||(u=!0,y(w),B(),J())},k=()=>{let w=a?.reason;G(w instanceof Te?w:new Re(e))},T=w=>{if(!(u||!w||typeof w!="object"))switch($(),M(),w.t){case"delta":typeof w.delta=="string"&&Se(w.delta);break;case"response":b(w.body);break;case"error":{let{message:_,code:H}=mi(w.body);G(new Te(_,{requestId:e,code:w.code??H}));break}}},D=()=>{let w=v.messages()[Symbol.asyncIterator]();R=()=>{w.return?.(void 0)};let _=()=>{A&&w.next().then(H=>{if(A){if(H.done){u||b(void 0);return}T(H.value),_()}},H=>{A&&G(H)})};_()},I=()=>{if(!m){if(m=!0,a){if(a.aborted){G(new Re(e));return}a.addEventListener("abort",k,{once:!0})}C=d?.(w=>G(w))??null,D(),i.set({rpc:{[e]:{args:t,respond_on:n,consumer_id:r,stream:s}}}),l&&l>0&&!i.synced&&(E=setTimeout(()=>{E=null,!u&&!i.synced&&G(new Ze(l,e))},l),W=i.onSynced(()=>V())),S=i.onSynced(()=>{S=null,!(u||U||x)&&(x=setTimeout(()=>{x=null,!(u||U)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(An/1e3)}s. If this app is a urun-python serve app (\`ctx.serve\`), its runtime does not read the \`rpc\` doc that request()/requestStream()/complete() writes \u2014 the call will never resolve (urun-sh/urun-ts#330). Serve-app chat rides the \`llm\` doc + \`llm-resp:<id>\` stream contract instead. The request keeps waiting; abort it via options.signal (request() also supports options.timeout).`)},An))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(I(),c.length>0)return Promise.resolve({value:c.shift(),done:!1});if(f!==null){let w=f;return f=null,Promise.reject(w)}return u?Promise.resolve({value:void 0,done:!0}):new Promise((w,_)=>{p={resolve:w,reject:_}})},return(){return u||(u=!0,y(void 0),B()),Promise.resolve({value:void 0,done:!0})},throw(w){return u||(u=!0,h(w),B()),Promise.reject(w)}}}},body:g,start:I}}function En(i){if(i&&typeof i=="object"){let{epoch:e,by:t}=i,n={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(n.by=t),n}}function vi(i,e){let n=i.get("streams")?.[e];if(!n||typeof n!="object")return null;let{kind:r,rt:s,br:o}=n,a={};(r==="audio"||r==="video"||r==="data")&&(a.kind=r);let d=En(s);d&&(a.rt=d);let l=En(o);return l&&(a.br=l),a}var Lt=class{constructor(e,t,n,r,s){this._name=e;this._transport=t;this._streamData=n;this._controlDoc=r;this._onActivity=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],n=null,r=!1,s=null,o={push(d){if(!r)if(n){let l=n;n=null,l.resolve({value:d,done:!1})}else t.push(d)},end(){if(r=!0,n){let d=n;n=null,d.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{r=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(d=>{if(!(d===null||r)&&(s=e._streamConsumeUnavailableError(d),a(),n)){let l=n;n=null,l.reject(s)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.reject(s):r?Promise.resolve({value:void 0,done:!0}):new Promise((d,l)=>{n={resolve:d,reject:l}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,n=this._handlers.get("track");if(n)for(let r of n)r(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),n=vi(t,this._name),r=n?.br;if(r?.by==="runtime")throw new et(this._name,"runtime","browser");if(r)return;let s={br:{epoch:1}};n?.rt&&(s.rt=n.rt);let o=n?.kind??e;o&&(s.kind=o),t.set({streams:{[this._name]:s}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??vt;return un(t,{track:()=>this.track,onTrack:r=>this.on("track",r)})}onSeeked(e){return this._transport.on("seeked",(t,n)=>{t===this._name&&e(n)})}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n?.delete(t),n?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let n of t)n(e)}},we=class i{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Jt;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,n,r,s,o){this._sessionId=e,this._multiplexer=t,this._transport=n,this._recordingsAuth=r,this._artifactsAuth=s,this._streamData=Qt(n),this._wireControlDocIncarnation(),this._lifecycleUnsub=ft(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=ht({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new ae({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(pi).awareness.setLocalState({role:"client"}),this._activation=new ie({onPhase:a=>this.onPhase(a),hint:()=>this.doc(at).get(dt)??this.doc("control").get(ct),onData:(a,d)=>this._streamData.onData(a,d)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let n=await zt({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),r=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,s=new ke,o=new Le({url:n.wsUrl,orgId:t.orgId,jwt:r,authProvider:t.authProvider,sessionId:e,iceServers:n.response.ice_servers}),a=new i(e,s,o,Pt(t),se({...t,baseUrl:n.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&s.setTarget(o.multiplexer)}),o.setConnection({url:n.wsUrl,sessionId:e,iceServers:n.response.ice_servers}),o.setEndsAt(n.endsAt),Ee()&&await Ce();let d=t.getAccessToken,l=d?async()=>await d()??r:r;return a.setDocTransport({wsUrl:n.wsUrl,token:l}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}get region(){return this._transport.region}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return nt(this,e)}on(e,t){if(e!=="generationTick")throw new Error(`[urun] unknown session event ${String(e)}`);return this._generationTickHandlers.add(t),this._generationTickStop||(this._generationTickStop=ut(this.doc("control"),n=>{for(let r of Array.from(this._generationTickHandlers))try{r(n)}catch(s){console.warn("[urun] generationTick handler failed:",s)}})),()=>{this._generationTickHandlers.delete(t),this._generationTickHandlers.size===0&&(this._generationTickStop?.(),this._generationTickStop=null)}}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new te(e);return this._recordingsAccessor={list:n=>t.list(n??this._sessionId),get:n=>t.get(n),retain:(n,r)=>t.retain(n,r),pin:n=>t.pin(n),unpin:n=>t.unpin(n),permanent:n=>t.permanent(n),delete:n=>t.delete(n)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new Y(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new Y(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let n of this._docs.values())n.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new Lt(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._autoTouch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new Zt(e,this._sessionId,li.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=en(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}_autoTouch(){this._activityMode!=="explicit"&&this._activity?.touch()}activity(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=Pe(e.wsUrl),n=typeof e.token=="function"?"<token-supplier>":e.token??"",r=`${t}\0${n}\0${this._sessionId}`;r!==this._docEndpointKey&&(this._docEndpointKey=r,this.connectDocs(Xt({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let n=It(),r=new AbortController;t.signal&&(t.signal.aborted?r.abort(t.signal.reason):t.signal.addEventListener("abort",()=>r.abort(t.signal.reason),{once:!0}));let s=null;if(typeof t.timeout=="number"&&t.timeout>=0){let d=t.timeout;s=setTimeout(()=>r.abort(new Je(d,n)),d)}let o=this._consumeResponse(n,e,!1,r.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{s&&clearTimeout(s),a?.()})}_consumeResponse(e,t,n,r,s){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(ui),a=fi(e);return gi(o,e,t,a,this._streamData.consumerId,n,()=>this.stream(a),r,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),s??Cn)}requestStream(e,t={}){let n=It();return this._consumeResponse(n,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let n=It(),r=this._consumeResponse(n,e,!1,t.signal,t.docSyncTimeout);return r.start(),r.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}connect(){return this._transport.connect()}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=Rn(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,runtimePhase:{current:()=>this._transport.phase??null,subscribe:t=>this._transport.on("phase",t)},onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t),onOverrideAudioTrack:t=>this.stream("audio")._setOverrideTrack(t),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}),this._downlinkStallWatch&&this._dialNegotiation?.watchDownlinkStall(this._downlinkStallWatch))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}get mediaTransportAttempted(){return this._dialNegotiation?.mediaTransportAttempted()??!1}watchDownlinkStall(e={}){return this._downlinkStallWatch=e,this._dialNegotiation?.watchDownlinkStall(e),()=>{this._downlinkStallWatch=null}}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.detach(e.status==="paused"?e.reason:void 0),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new K)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new K);let e=this._cancelHandler().then(t=>(this.disconnect(),t));return this._cancelPromise=e,e.catch(()=>{this._cancelPromise===e&&(this._cancelPromise=void 0)}),e}disconnect(){this.detach()}detach(e){let t=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let r of t)try{r()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let n=Array.from(this._activeRequests);this._activeRequests.clear();for(let r of n)try{r(new tt)}catch{}for(let r of this._docs.values())r.dispose();this._docs.clear();for(let r of this._streams.values())r.dispose();this._streams.clear(),this._transport.disconnect(e)}};function Dn(i){return`urun:session:v2:${i.orgId}:${i.app}:${i.functionName}`}function xt(){try{return globalThis.sessionStorage??null}catch{return null}}var Ut=new Map;function Ve(i){if(!i)return;let e=i.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=JSON.parse(atob(t+"=".repeat((4-t.length%4)%4)));return typeof n?.sub=="string"&&n.sub.length>0?n.sub:void 0}catch{return}}function wi(i,e){return i!==void 0&&e!==void 0&&i!==e}function Mt(i,e){let t=xt(),n=null;if(t)try{let s=t.getItem(i);if(s){let o=JSON.parse(s);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(n={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{n=null}let r=Ut.get(i)??n??null;return!r||wi(r.actor,e)?null:r}function In(i,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};Ut.set(i,t);let n=xt();if(n)try{n.setItem(i,JSON.stringify(t))}catch{}}function Ge(i){Ut.delete(i);let e=xt();if(e)try{e.removeItem(i)}catch{}}var Ln=new Set(["paused","acquiring","live"]),yi=new Set(["24h","keep"]);function Pn(i){if(typeof i!="string"||i.length===0)return null;let e=new Date(i);return Number.isFinite(e.getTime())?e:null}function bi(i){if(typeof i?.id!="string"||i.id.length===0)throw new _e("[urun] session list returned a row with no id \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_row"});if(typeof i.state!="string"||!Ln.has(i.state))throw new _e(`[urun] session ${i.id} reported an unrecognized state ${JSON.stringify(i.state)} \u2014 this @urun-sh/core build knows only ${[...Ln].join(", ")}. The SDK may be out of date for this control plane. NOTE: there is no terminal session state; a word like "closed" or "ended" arriving here is a server-side bug.`,{code:"unknown_session_state"});let e=!1;return typeof i.recordings_expired=="boolean"?e=i.recordings_expired:console.warn(`[urun] session ${i.id} list row has no recordings_expired (or a non-boolean value) \u2014 this control plane predates it; treating the session as not-expired`),{id:i.id,label:typeof i.label=="string"&&i.label.length>0?i.label:null,state:i.state,app:typeof i.app=="string"?i.app:"",functionName:typeof i.function=="string"?i.function:"",createdAt:Pn(i.created_at),lastActiveAt:Pn(i.last_active_at),archived:i.archived===!0,preview:typeof i.preview=="string"&&i.preview.length>0?i.preview:null,recordingsExpired:e,retention:yi.has(i.retention)?i.retention:(i.retention!==void 0&&console.warn(`[urun] session ${i.id} reported an unrecognized retention ${JSON.stringify(i.retention)} \u2014 defaulting to '24h'`),"24h")}}var ye=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:n}=await Vt({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(bi),nextCursor:n}}async end(e){await Gt({...this._request,sessionId:e})}async archive(e){await it({...this._request,sessionId:e,archived:!0})}async unarchive(e){await it({...this._request,sessionId:e,archived:!1})}async setName(e,t,n={}){await Kt({...this._request,sessionId:e,name:t,source:n.source})}};function xn(i,e,t){let n=Ve(t);In(i,n!==void 0?{sessionId:e,actor:n}:{sessionId:e})}var Si=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function ki(i,e){return new ye(i,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function _i(i,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(t,n){if(!(Si.has(n)||typeof n!="string"))return(r,s)=>{let o=r??{},a=Dn({orgId:e.orgId,app:i,functionName:n}),d=!s?.sessionId&&!e.sessionKey&&!!s?.label,l,c=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,p=c(),u=e.jwt,f=e.getAccessToken?async b=>{let k=await e.getAccessToken(b);return k&&(u=k),k}:void 0,m={...e,getAccessToken:f},y=new ke,h=new Le({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:p,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),g=new we(p,y,h,Pt(m),se(m),{activity:s?.activity}),v,R=!1,C=!1,E,W,x=new Promise(b=>{W=b}),S,A=b=>{b.sessionId||E||(E="teardown",S="ticket",De({baseUrl:b.baseUrl,requestId:b.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))},V=b=>{E||b.sessionId||(E="abandon",De({baseUrl:b.baseUrl,requestId:b.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider,reason:"client_abandoned"}))},$=b=>{let k=b.sessionId||!l?b:{...b,sessionId:l};v=k,W({status:"ready",handle:k}),(C||E==="teardown")&&A(k)};g.setEndHandler(async()=>{let b=v?{status:"ready",handle:v}:await x;if(b.status==="unavailable")throw new K("[urun] session allocation failed before a releasable request was created",{cause:b.cause});let k=v??b.handle;return Ge(a),E==="teardown"?k.sessionId?{status:"paused",sessionId:k.sessionId,reason:"client_ended"}:{status:"canceled",requestId:k.requestId}:(E="end",k.sessionId?Ht({baseUrl:k.baseUrl,sessionId:k.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):rt({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),g.setCancelHandler(async()=>{let b=v?{status:"ready",handle:v}:await x;if(b.status==="unavailable")throw new K("[urun] session allocation failed before a cancellable request was created",{cause:b.cause});let k=v??b.handle;if(k.sessionId)throw new Xe(`[urun] cancel() is for a queued admission request, but this call already has session ${k.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:k.sessionId,code:"cancel_on_live_session"});E="end";try{let T=await rt({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return Ge(a),T}catch(T){throw E==="end"&&(E=void 0),T}});let U=async b=>{let k,T=s?.sessionId??e.sessionKey??l,D,I;if(T===void 0&&!d){let N=Mt(a);if(N?.sessionId){if(I=Ve(u),N.actor!==void 0&&I===void 0&&f){let Qe=await Promise.resolve(f()).catch(()=>{});I=Ve(Qe??e.jwt)}D=N.actor!==void 0&&I!==void 0&&N.actor!==I?void 0:N.sessionId}}let O=T??D,w=(N,Qe)=>jt({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:n,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,idempotencyKey:N,sessionKey:Qe,label:s?.label,...s?.sharedApp?{sharedApp:!0}:{},concurrencyKey:s?.concurrencyKey,priority:e.priority,onAdmission:j=>{h.reportAdmission(j),j.sessionId&&!l&&(l=j.sessionId,k=j.sessionId,v&&v.sessionId!==j.sessionId&&$({...v,sessionId:j.sessionId}),R||(e.sessionKey||xn(a,j.sessionId,u),g.setSessionId(j.sessionId)))},onRequest:$}),_;try{_=await w(b,O)}catch(N){if(D===void 0||!(N instanceof z)||N.code!=="session_name_not_yours")throw N;console.warn(`[urun] session_name_not_yours: the control plane refused session ${D} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),Mt(a,I)?.sessionId===D&&Ge(a),_=await w(c(),void 0)}let H=f?await f()??void 0:e.jwt;if(k&&k!==_.sessionId)throw v&&v.sessionId!==_.sessionId&&$({...v,sessionId:_.sessionId}),new z(`Gateway contract violation: admission minted session ${k} but allocation completed as ${_.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return l=_.sessionId,v&&v.sessionId!==_.sessionId&&$({...v,sessionId:_.sessionId}),R||(e.sessionKey||xn(a,_.sessionId,u),g.setSessionId(_.sessionId),g.setArtifactsAuth(se({...m,baseUrl:_.baseUrl})),h.setEndsAt(_.endsAt),h.seedRegion(Yt(_.response))),{url:_.wsUrl,sessionId:_.sessionId,jwt:H,iceServers:_.response.ice_servers,endsAt:_.endsAt}},M,B=0,J=f?async()=>{let b=B++>0;return await f(b?{forceRefresh:!0,reason:"background"}:void 0)??M}:()=>M,Se=()=>{let b=h.connectedUrl;return b?Pe(b):void 0};if(h.setConnectionResolver(async()=>{let b=await U(c());return M=b.jwt,b}),h.on("connected",()=>{h.multiplexer&&y.setTarget(h.multiplexer);let b=h.connectedUrl;b&&g.setDocTransport({wsUrl:b,token:J,resolveServerUrl:Se})}),(async b=>{let k;try{k=await U(b)}catch(T){if(R){W({status:"unavailable",cause:T});return}console.error(`[urun] Failed to create session for ${n}:`,T),v&&V(v);let D=T instanceof Error?T:new Error(String(T)),I=T instanceof z?T.httpStatus:void 0,O=T instanceof z?T.code:void 0,w=T instanceof z?T.retryAfterSeconds:void 0;h.reportAllocationFailure(D,I,O,w),W({status:"unavailable",cause:T});return}R||(h.setAuth({jwt:k.jwt,authProvider:e.authProvider,orgId:e.orgId}),h.setConnection({url:k.url,sessionId:k.sessionId,iceServers:k.iceServers}),Ee()&&await Ce(),M=k.jwt,g.setDocTransport({wsUrl:k.url,token:J,resolveServerUrl:Se}),await h.connect({app:i,functionName:n,args:o}),g.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(p).catch(b=>{console.error(`[urun] Failed to connect session for ${n}:`,b)}),e.releaseOnLeave!==!1){let b=mt(()=>{if(R=!0,h.leaveLeg())return;if(h.connectedUrl!==null){h.disconnect();return}h.disconnect();let O=v;O?A(O):C=!0});g.onDisconnect(b);let k,T,D=!1,I=()=>{D||(D=!0,k?.(),T?.())};x.then(O=>{O.status!=="ready"||D||(k=gt(()=>v!==void 0))}),T=g.onPhase(O=>{let w=O?.name;(w==="paused"||w==="error")&&I()}),D&&T(),g.onDisconnect(I)}return g}}})}var Un="https://api.urun.sh",Mn="URUN_DEV";function Ti(){if(typeof process>"u")return!1;let i=process.env?.[Mn];if(typeof i!="string")return!1;let e=i.trim().toLowerCase();return e==="1"||e==="true"}var X=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Ri(i,e={}){if(!i)throw new X("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,n=Z(e.baseUrl??Un),r={};e.expiresIn!==void 0&&(r.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(r.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(r.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(r.max_session_s=e.maxSessionS),e.subject!==void 0&&(r.subject=e.subject),e.metadata!==void 0&&(r.metadata=e.metadata),e.sharedApp&&(r.shared_app=!0),(e.dev??Ti())&&(r.dev=!0);let s;try{s=await t(`${n}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(r)})}catch(u){throw new X(`[urun] client token mint request failed: ${u instanceof Error?u.message:String(u)}`)}let o={};try{o=await s.json()}catch{}if(!s.ok){let u=typeof o.message=="string"?o.message:`HTTP ${s.status}`;throw new X(`[urun] client token mint failed: ${u}`,s.status)}let a=typeof o.token=="string"?o.token:"",d=typeof o.org_id=="string"?o.org_id:"",l=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,c=typeof o.expires_in=="number"?o.expires_in:void 0;if(!a)throw new X("[urun] client token mint returned no token (control-plane contract violation)",s.status);let p=Number.isFinite(l)?new Date(l):new Date(Date.now()+(c??60)*1e3);return{token:a,expiresAt:p,orgId:d}}var Wn=3e4,On="stream:",Wt=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",n=>{let r;try{r=JSON.parse(typeof n.data=="string"?n.data:"")}catch{return}if(r.rpcId&&this._pendingRpc.has(r.rpcId)){let s=this._pendingRpc.get(r.rpcId);this._pendingRpc.delete(r.rpcId),clearTimeout(s.timer),r.error?s.reject(new Error(r.error)):s.resolve(r.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let n=`${On}${e}`;return this._multiplexer.on(n,r=>{t(r)})}emit(e,t){let n=`${On}${e}`,r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(n,r)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((n,r)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){r(new Error("WebSocket not open"));return}let s=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(s)&&(this._pendingRpc.delete(s),r(new Error(`RPC request "${e}" timed out after ${Wn}ms`)))},Wn);this._pendingRpc.set(s,{resolve:n,reject:r,timer:o}),this._ws.send(JSON.stringify({rpcId:s,type:e,...t}))})}};function Ai(i){let n=`${i.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(i.orgId)}`,r=new WebSocket(n);(i.jwt||i.apiKey)&&r.addEventListener("open",()=>{r.send(JSON.stringify({type:"auth",orgId:i.orgId,jwt:i.jwt,authProvider:i.authProvider,apiKey:i.apiKey}))});let s=new qt(r);return new Wt(r,s)}var Ei='video/mp4; codecs="avc1.42E01E"';function Ci(i,e){let t=e?.codec??Ei,n=document.createElement("video");n.muted=!0,n.playsInline=!0;let r=new MediaSource,s=URL.createObjectURL(r);n.src=s,r.addEventListener("sourceopen",()=>{let u;try{u=r.addSourceBuffer(t)}catch(h){throw h instanceof DOMException&&h.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):h}let f=i.getReader();function m(){return u.updating?new Promise(h=>{u.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function y(){try{for(;;){let{done:h,value:g}=await f.read();if(h){await m(),r.readyState==="open"&&r.endOfStream();return}await m();try{u.appendBuffer(g)}catch(v){if(v instanceof DOMException&&v.name==="QuotaExceededError"){let R=u.buffered;if(R.length>0){let C=R.start(R.length-1);u.remove(0,C),await m(),u.appendBuffer(g)}else throw v}else throw v}}}catch{if(r.readyState==="open")try{r.endOfStream("decode")}catch{}}}y()}),n.play().catch(()=>{});let o=n,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let d=a.call(n),l=d.getTracks(),c=0,p=l.length;if(p===0)n.addEventListener("emptied",()=>{URL.revokeObjectURL(s)},{once:!0});else for(let u of l)u.addEventListener("ended",()=>{c++,c>=p&&URL.revokeObjectURL(s)});return d}function Di(i){return i.status.startsWith("pending_")}var ne=class extends Error{status;code;constructor(e,t){super(e),this.name="CreditsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},be=class extends ne{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function Ii(i,e,t){let n=t||e||`HTTP ${i}`;return i===401?new be(n,e??"unauthorized"):new ne(n,{status:i,code:e??`http_${i}`})}var Ke=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let e=await this._request("GET","/balance");if(!e||typeof e!="object"||typeof e.org_id!="string")throw new ne("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let n=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(n)?n:[]}async _request(e,t,n={}){let r=this._buildUrl(t,n.params),s=await this._resolveToken(),o=await this._fetch(r,e,s);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await this._fetch(r,e,s))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw Ii(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let n=`${this._base}${e}`,r=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return r&&(n+=`?${r}`),n}_fetch(e,t,n){let r={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(r["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:t,headers:r})}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new be("[urun] credits: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let n=(await e.json()).error;if(n&&typeof n=="object"){let{code:r,message:s}=n;return{code:typeof r=="string"?r:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Li(i){return new Ke(i)}var ze=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function Nn(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function Pi(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function xi(i,e){let t=i.getTracks();if(t.length===1&&t[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function Ot(i,e){for(let t of[...i.lostListeners])try{t(e)}catch{}}var Ye=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let n=this.claims.get(e);n&&(this.claims.delete(e),n.released=!0,n.track=null,n.stream=null,Ot(n,new Error(`${e} capture claim superseded by a newer claim`)));let r=this.createState(e,t);return this.claims.set(e,r),await this.converge(r),r.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new ze;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),n={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},r;try{r=await t(n)}catch(o){let a=`one-capture getUserMedia(${Nn(n)}) failed`,d=o instanceof Error?o.message:String(o);for(let l of[...this.claims.values()])if(this.claims.delete(l.kind),l.released=!0,l!==e){let c=new Error(`${a} \u2014 ${l.kind} capture lost: ${d||o}`);c.cause=o,Ot(l,c)}throw o}let s=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of s){let a=Pi(r,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let d=Object.assign(new Error(`one-capture getUserMedia(${Nn(n)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw d;Ot(o,d);continue}if(o.track=a,o.stream=xi(r,a),o!==e)for(let d of[...o.trackListeners])try{d(a,o.stream)}catch{}}}createState(e,t){let n=this,r={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return r.track},get stream(){return r.stream},update(s){return n.enqueue(async()=>{if(r.released)throw new Error(`${e} capture claim already released`);if(r.constraints=s,await n.converge(r),!r.track)throw new Error(`${e} capture update yielded no track`);return r.track})},release(){r.released||(r.released=!0,n.claims.get(e)===r&&n.claims.delete(e),r.track?.stop(),r.track=null,r.stream=null)},onTrack(s){return r.trackListeners.add(s),()=>r.trackListeners.delete(s)},onLost(s){return r.lostListeners.add(s),()=>r.lostListeners.delete(s)}}};return r}},Ui=null;function Mi(){return Ui??=new Ye}var Fn="input",Wi=30;function Oi(i){let e=i.now??Date.now,t=i.field??Fn,n=1e3/Math.max(i.hz??30,.001),r=new Set,s=0,o=0,a=0,d=0,l,c=null,p=!1,u=()=>{if(p)return;l=e(),d+=1;let m={keys:[...r],buttons:s,pointer:{x:o,y:a},seq:d,at:l};try{i.awareness.setLocalStateField(t,m)}catch{}},f=()=>{if(p)return;let m=e();if(l===void 0||m-l>=n){c&&(clearTimeout(c),c=null),u();return}if(c)return;let y=Math.max(n-(m-l),0);c=setTimeout(()=>{c=null,u()},y),c.unref?.()};return{keyDown(m){let y=String(m).toLowerCase();r.has(y)||(r.add(y),f())},keyUp(m){let y=String(m).toLowerCase();r.delete(y)&&f()},setButtons(m){let y=Number.isFinite(m)?Number(m):0;y!==s&&(s=y,f())},movePointer(m,y){let h=Number.isFinite(m)?Number(m):0,g=Number.isFinite(y)?Number(y):0;h===0&&g===0||(o+=h,a+=g,f())},heldKeys(){return[...r]},clear(){p||(r.clear(),s=0,c&&(clearTimeout(c),c=null),u())},dispose(){if(p)return;let m=r.size>0||s!==0;r.clear(),s=0,c&&(clearTimeout(c),c=null),m&&u(),p=!0}}}var Ni=1024,Fi=.92,$i=262144,qi=256e3,Nt=[.9,.8,.7,.6,.5],$n=.8,Bi=8;function $t(i,e,t){if(!(i>0)||!(e>0))throw new Error(`reference image has no pixels (${i}x${e})`);let n=Math.min(1,t/Math.max(i,e));return{width:Math.max(1,Math.round(i*n)),height:Math.max(1,Math.round(e*n))}}async function Hi(i){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(i,{imageOrientation:"from-image"})}async function Bn(i,e,t){let n=await new Promise(r=>{i.toBlob(r,e,e==="image/jpeg"?t:void 0)});if(!n)throw new Error(`could not encode the reference image as ${e}`);return n}function qn(i,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${i} -> ${e} bytes`)}async function Ft(i,e,t,n,r){let s=document.createElement("canvas");s.width=e,s.height=t;let o=s.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return n==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,t)),o.drawImage(i,0,0,e,t),await Bn(s,n,r)}async function ji(i,e,t,n){let{width:r,height:s}=e,o=await Ft(i,r,s,t,n);if(o.size<=256e3)return{blob:o,width:r,height:s};if(t==="image/jpeg"){for(let d of Nt)if(!(d>=n)&&(o=await Ft(i,r,s,t,d),o.size<=256e3))return qn(`quality ${n} -> ${d}`,o.size),{blob:o,width:r,height:s}}let a=t==="image/jpeg"?Nt[Nt.length-1]:n;for(let d=0;d<Bi;d++)if(r=Math.max(16,Math.round(r*$n)),s=Math.max(16,Math.round(s*$n)),o=await Ft(i,r,s,t,a),o.size<=256e3)return qn(`downscaled to ${r}x${s} @ q${a}`,o.size),{blob:o,width:r,height:s};throw new Error(`this image cannot be sent: even at ${r}x${s} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function Vi(i,e){let{maxSize:t=1024,type:n="image/jpeg",quality:r=.92,source:s}=e,o=await Hi(i);try{let a=$t(o.width,o.height,t),d=await ji(o,a,n,r);return{bytes:new Uint8Array(await d.blob.arrayBuffer()),type:n,width:d.width,height:d.height,source:s}}finally{o.close()}}function Gi(i){let e=i instanceof Error?i.name:"",t=i instanceof Error?i.message:String(i);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function Ki(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function zi(i,e){let t=i.videoWidth,n=i.videoHeight;if(!(t>0)||!(n>0))throw new Error("the camera has not shown a frame yet");let{maxSize:r=1024,type:s="image/jpeg",quality:o=.92}=e??{},a=$t(t,n,r),d=document.createElement("canvas");d.width=a.width,d.height=a.height;let l=d.getContext("2d");if(!l)throw new Error("could not prepare the reference image (no 2d canvas context)");s==="image/jpeg"&&(l.fillStyle="#fff",l.fillRect(0,0,a.width,a.height)),l.drawImage(i,0,0,a.width,a.height);let c=await Bn(d,s,o);return{bytes:new Uint8Array(await c.arrayBuffer()),type:s,width:a.width,height:a.height,source:"camera"}}var Yi=new Set(["w","a","s","d"]),re=(i,e)=>Math.min(e,Math.max(-e,i));function Qi(i={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:n=.18,decayTauMs:r=900,frameRelax:s=.06,maxPan:o=.12,maxLogZoom:a=.22}=i,d=0,l=0,c=0,p=null,u=new Set;return{pointerDelta(f,m){d=re(d-f*e,o),l=re(l-m*e,o)},keyDown(f){let m=f.toLowerCase();Yi.has(m)&&u.add(m)},keyUp(f){u.delete(f.toLowerCase())},clearKeys(){u.clear()},frameArrived(){let f=1-s;d*=f,l*=f,c*=f},tick(f){if(p===null){p=f;return}let m=Math.max(0,Math.min(100,f-p))/1e3;p=f,u.has("w")&&(c=re(c+t*m,a)),u.has("s")&&(c=re(c-t*m,a)),u.has("a")&&(d=re(d+n*m,o)),u.has("d")&&(d=re(d-n*m,o));let y=Math.exp(-m*1e3/r);d*=y,l*=y,c*=y},transform(){return{translateX:d,translateY:l,scale:Math.exp(c)}},isIdentity(f=5e-4){return Math.abs(d)<f&&Math.abs(l)<f&&Math.abs(c)<f},reset(){d=0,l=0,c=0,u.clear()}}}export{ur as ACTIVATION_COLD_BOOT_AFTER_MS,pr as ACTIVATION_DEGRADED_AFTER_MS,dt as ACTIVATION_HINT_PATH,lr as ACTIVATION_STILL_AFTER_MS,pt as ACTIVITY_DOM_EVENTS,sn as ACTIVITY_FIELD,Tr as ACTIVITY_STAMP_MIN_INTERVAL_MS,ie as ActivationMonitor,_i as App,Zn as BACKOFF_BASE_MS,tr as BACKOFF_MAX_ATTEMPTS,er as BACKOFF_MAX_MS,Xn as COLD_BOOT_WHEN_LIVE_TIMEOUT_MS,Ye as CaptureController,ze as CaptureUnavailableError,X as ClientTokenError,Ke as CreditsClient,ne as CreditsError,be as CreditsUnauthorizedError,$i as DATA_CHANNEL_MESSAGE_CEILING,Cn as DEFAULT_DOC_SYNC_TIMEOUT_MS,Un as DEFAULT_GATEWAY_URL,Hn as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Fi as DEFAULT_REFERENCE_JPEG_QUALITY,Ni as DEFAULT_REFERENCE_MAX_SIZE,Qn as DEFAULT_WHEN_LIVE_TIMEOUT_MS,or as DERIVED_LEG_SEP,P as DGRAM_HEADER_BYTES,cn as FOCUS_FIELD,Ar as FOREGROUND_COALESCE_MS,ue as FrameReassembler,kr as GENERATION_TICK_EMIT_INTERVAL_MS,_r as GENERATION_TICK_MAX_EXTRAPOLATION_MS,Wi as INPUT_PRESENCE_DEFAULT_HZ,Fn as INPUT_PRESENCE_FIELD,ee as InvalidDurationError,ct as LEGACY_ACTIVATION_HINT_PATH,at as PLATFORM_DOC_NAME,Ne as PermanentLockedError,Oe as PinRequiresActiveTempError,ae as PresenceTracker,jn as ProduceAckTimeoutError,Me as RecordingNotFoundError,te as RecordingsClient,F as RecordingsError,oe as RecordingsUnauthorizedError,Re as RequestAbortError,tt as RequestCancelledError,Ze as RequestDocSyncError,Te as RequestError,Je as RequestTimeoutError,We as RetainNotTempError,Ue as RuntimeArtifactNotFoundError,Y as RuntimeArtifactsClient,L as RuntimeArtifactsError,xe as RuntimeArtifactsUnauthorizedError,cr as SIGNALING_PROTOCOL_VERSION,st as STREAM_END,we as Session,z as SessionAllocationError,ye as SessionDirectory,_e as SessionDirectoryError,Xe as SessionEndError,K as SessionEndUnavailableError,Gn as SessionFailedError,et as StreamDirectionConflict,me as TransportNegotiator,zn as TransportSessionMismatchError,ge as TransportSessionSignaling,Mn as URUN_DEV_ENV,dn as USER_ACTIVITY_FIELD,Rr as USER_ACTIVITY_MIN_INTERVAL_MS,on as VISIBILITY_FIELD,qi as WIRE_MESSAGE_BUDGET,pn as WT_CONTROL_FRAME_MAX,gn as WT_DATA_STREAM_VERSION,ve as WebRtcSession,he as WebTransportSession,ce as WtControlDecoder,$e as WtDataStreamParser,tn as activationHintFrom,Ki as cameraCaptureAvailable,zi as captureStillFromVideo,nr as computeBackoffDelay,kt as consumeWtDataStreams,ht as createActivityTracker,Qi as createCameraWarp,Ri as createClientToken,Li as createCreditsClient,Oi as createInputPresencePublisher,Sr as createRecordingsClient,fr as createRuntimeArtifactsClient,Ai as createStore,ot as decodeStreamEnvelope,dr as derivedLegName,ar as derivedLegRole,Vn as describeSessionFailure,Jn as describeSessionPhase,sr as encodeStreamEnvelope,yt as encodeWtControlFrame,$t as fitWithin,lt as isDurationString,Yn as isPausedPhase,Di as isPendingRecording,rr as isRetryableSessionError,Ae as isWakingPhase,vt as mediaRecorderChunkSource,Vi as normalizeReferenceImage,yr as normalizeRetention,gt as observeLeaveConfirm,ft as observePageLifecycle,mt as observePageTeardown,le as parseDgramHeader,ir as prewake,Gi as referenceImageErrorMessage,De as releaseSessionBeacon,ki as sessionDirectory,Kn as sessionFailureFromMediaError,Mi as sharedCaptureController,Ci as videoStream,ut as watchGenerationTick,nt as whenLive,bt as writeDgramHeader};
29
+ `)}var Be=class{constructor(e){this.sink=e}sink;frameSeq=0;stopped=!1;deadCb=null;sendPc=null;recvPc=null;sender=null;currentTrack=null;renderSender=null;renderRemoteCb=null;renderEndedListener=null;worker=null;workerUrl=null;nodeBridge=null;endedListener=null;candQueue=null;negotiatedOnce=!1;negotiating=!1;renegotiateQueued=!1;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.currentTrack&&e.readyState==="live")return;let t=null;if(!(e!==null&&(t=Fr(e)?this.bridgedTrack(e):e,!t))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(t)}catch(n){this.die(`replaceTrack: ${n instanceof Error?n.message:String(n)}`);return}this.currentTrack=t,t&&this.wireTrackLiveness(t);return}t!==null&&this.engage(t)}}stop(){if(!this.stopped){this.stopped=!0,this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(e){let t=globalThis;if(typeof t.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof t.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let n;try{n=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let r=this.sendPc.addTrack(e);this.sender=r,this.currentTrack=e,this.wireTrackLiveness(e);let s=t.RTCRtpScriptTransform;if(r.transform=new s(n,{role:"sender"}),this.negotiatedOnce){this.negotiate().catch(o=>this.die(`loopback renegotiate: ${o instanceof Error?o.message:String(o)}`));return}this.negotiate().catch(o=>this.die(`loopback negotiate: ${o instanceof Error?o.message:String(o)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let t=e.RTCPeerConnection;this.sendPc=new t({iceServers:[]}),this.recvPc=new t({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=n=>{if(!n.candidate)return;let r=this.candQueue;r!==null&&(r.toRecv.push(n.candidate),this.flushCandidates())},this.recvPc.onicecandidate=n=>{if(!n.candidate)return;let r=this.candQueue;r!==null&&(r.toSend.push(n.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(n=>this.die(`loopback renegotiate: ${n instanceof Error?n.message:String(n)}`))},this.recvPc.ontrack=n=>{let r=n.transceiver?.mid??null;r!==null&&r===this.renderMidOf()&&this.renderRemoteCb?.(n.track)}}setRenderSource(e){if(!this.stopped){if(e===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(e);else try{this.renderSender.replaceTrack(e)}catch(t){this.die(`render replaceTrack: ${t instanceof Error?t.message:String(t)}`);return}this.wireRenderRemote(e),!this.negotiatedOnce&&this.sender&&this.negotiate().catch(t=>this.die(`loopback negotiate: ${t instanceof Error?t.message:String(t)}`))}}}onRenderTrack(e){this.renderRemoteCb=e}renderMidOf(){if(!this.renderSender)return null;let e=this.sendPc;try{return e.getTransceivers?.().find(t=>t.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(e){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},e.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let e=this.sendPc,t=this.recvPc;if(!(!e||!t||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let n=await e.createOffer();n.sdp=wn(n.sdp??""),await e.setLocalDescription(n),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:n.sdp});let r=await t.createAnswer();r.sdp=wn(r.sdp??""),await t.setLocalDescription(r),await e.setRemoteDescription(t.localDescription??{type:"answer",sdp:r.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let e=this.candQueue;if(e){for(;e.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(e.toSend.shift())).catch(()=>{});for(;e.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(e.toRecv.shift())).catch(()=>{})}}bridgedTrack(e){let t=e;try{let n=t.context.createMediaStreamDestination();t.connect(n);let r=n.stream.getAudioTracks()[0]??null;return r?(this.nodeBridge={node:t,dest:n},r):(this.die("AudioNode bridge produced no audio track"),null)}catch(n){return this.die(`AudioNode bridge: ${n instanceof Error?n.message:String(n)}`),null}}wireTrackLiveness(e){this.endedListener=()=>this.die("mic track ended"),e.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([Nr],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=t=>{let n=t.data;n?.type==="enc"&&n.payload instanceof ArrayBuffer?this.onEncodedFrame(n.rtpTimestamp??0,new Uint8Array(n.payload)):n?.type==="err"&&this.die(`transform: ${n.detail??"unknown"}`)},e.onerror=t=>this.die(`transform worker: ${t.message||"error"}`),this.worker=e,e}onEncodedFrame(e,t){if(this.stopped)return;let n=Rt(this.frameSeq,e,t,this.sink.maxDatagramSize()||pe);if(n===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let r of n)this.sink.send(r);this.frameSeq=this.frameSeq+1>>>0}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function Fr(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var $r=9e4,qr="avc1.42E01F",Br=60,Hr=3,jr=1e4;function Vr(i){return Math.round(i*($r/1e6))%2**32>>>0}var He=class{constructor(e){this.sink=e}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}requestKeyframe(){this.keyframeWanted=!0}setSource(e){if(this.stopped||(this.teardownCapture(),e===null))return;let n=globalThis.MediaStreamTrackProcessor;if(typeof n!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let r=++this.generation,s=new n({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,s.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&r===this.generation;){let{value:a,done:d}=await s.read();if(d)break;if(a){if(o||this.stopped||r!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&r===this.generation&&this.die(`capture: ${a instanceof Error?a.message:String(a)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){this.cancelCapture?.(),this.cancelCapture=null,this.generation++}encodeFrame(e){let t={width:e.codedWidth,height:e.codedHeight};if(!this.encoder||!this.encoderDims||this.encoderDims.width!==t.width||this.encoderDims.height!==t.height){let s=globalThis.VideoEncoder;if(typeof s!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new s({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)})),this.encoderDims=t,this.encoder.configure({codec:qr,avc:{format:"annexb"},width:t.width,height:t.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(o){e.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${o instanceof Error?o.message:String(o)}`);return}}let r=this.keyframeWanted||this.framesSinceKeyframe>=Br;this.keyframeWanted=!1,this.framesSinceKeyframe=r?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:r})}catch(s){this.onEncoderError(s instanceof Error?s:new Error(String(s)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let n=Rt(this.frameSeq,Vr(e.timestamp),t,this.sink.maxDatagramSize()||pe,{lane:fn,keyframe:e.type==="key"});if(n===null){console.warn(`[urun] WT video uplink: AU of ${t.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let r of n)this.sink.send(r);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(n=>t-n<jr),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=Hr){this.die(`video encoder: ${e.message}`);return}console.warn("[urun] WT video uplink encoder error \u2014 re-initializing:",e.message);try{this.encoder?.close()}catch{}this.encoder=null,this.encoderDims=null}die(e){this.stopped||(console.warn(`[urun] WT video uplink lane dead (${e}) \u2014 the camera reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function Gr(i){return i.byteLength>=2&&i[0]===1&&i[1]===3}var je=class{constructor(e){this.transport=e}transport;streams=new Map;dead=null;deadCb=null;chain=Promise.resolve();onDead(e){this.deadCb=e}send(e,t){let n=new TextEncoder().encode(e);if(n.byteLength===0||n.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${n.byteLength})`));let r=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let s=this.streams.get(e);if(!s){let a=await this.transport.openUniStream(),d=new Uint8Array(2+n.byteLength);d[0]=1,d[1]=n.byteLength,d.set(n,2),await a.write(d),s={writer:a},this.streams.set(e,s)}let o=new Uint8Array(4+t.byteLength);new DataView(o.buffer).setUint32(0,t.byteLength,!0),o.set(t,4),await s.writer.write(o),Gr(t)&&(this.streams.delete(e),await s.writer.close().catch(()=>{}))}catch(s){throw this.die(s instanceof Error?s.message:String(s)),s}});return this.chain=r.catch(()=>{}),r}stop(e="stopped"){if(this.dead===null){this.dead=e;for(let t of this.streams.values())t.writer.close().catch(()=>{});this.streams.clear()}}die(e){this.dead===null&&(console.warn(`[urun] WT data uplink lane dead (${e})`),this.stop(e),this.deadCb?.(e))}};var yn=250,Kr=25,zr=2e3,Yr=15e3,Qr=1e3,Xr=45e3,Jr=5e3,Zr={llm:!0},ei=500,bn=10,ti=2,ni=2,At=2,he=class i{constructor(e,t,n,r,s,o,a){this.offer=e;this.sessionId=t;this.canvas=n;this.audioLane=r;this.audioUplink=s;this.videoUplink=o;this.dataUplink=a;this.firstMedia=new Promise((d,l)=>{this.firstFrameResolve=d,this.firstFrameReject=l}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorLogged=!1;writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;stallWatch=null;stallTimer=null;audioLaneLastArrivalAt=null;lastInboundControlAt=null;lastInboundDataAt=null;firstInboundDataAt=null;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new ue({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=this.offer.codec,n=t!==void 0&&t!=="";this.hasVideoLane=n,n&&St(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(c=>({algorithm:"sha-256",value:Uint8Array.from(atob(c),p=>p.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let r=await this.wt.createBidirectionalStream();this.writer=r.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let s=r.readable.getReader(),o=new ce,a=[],d=await this.readControl(s,o,a);if(d?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");let l=d;if(this.lastInboundControlAt=performance.now(),typeof l.pingIntervalMs=="number"&&l.pingIntervalMs>0?this.advertisedPingIntervalMs=l.pingIntervalMs:this.noCadenceLogged||(this.noCadenceLogged=!0,console.warn("[urun] gateway advertises no liveness cadence (pre-#2826 or mid-roll gateway) \u2014 the downlink-stall watch will never judge this leg dead on silence alone")),n&&(St(l.codec,"hello-ack"),this.initDecoder(l.codec,l.width,l.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let c={setSource:u=>{this.renderSource=u,this.audioUplinkLane?.setRenderSource?.(u)},onRemote:u=>{this.renderRemoteCb=u}},p=new qe(this.offer.audio,{...this.audioLane,renderHop:c});try{p.start(),this.audioPlayout=p}catch(u){console.warn(`[urun] WT audio lane failed to start (${u instanceof Error?u.message:String(u)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),p.stop()}}if(this.offer.audioUp===!0&&this.audioUplink&&this.engageUplinkLane("audio"),this.offer.videoUp===!0&&this.videoUplink&&this.engageUplinkLane("video"),this.offer.dataUp===!0&&this.dataUplink)try{let c=this.wt.createUnidirectionalStream?.bind(this.wt);if(!c)throw new Error("WebTransport uni streams are not creatable in this environment");let p=new je({openUniStream:async()=>(await c()).getWriter()});p.onDead(u=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(u,p)}),this.dataUplinkSender=p,this.dataUplink.onUplink(p)}catch(c){let p=c instanceof Error?c.message:String(c);console.warn(`[urun] WT data uplink failed to engage (${p}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(p)}this.controlLoop(s,o,a).catch(c=>this.die(`control loop: ${c}`)),this.datagramLoop().catch(c=>this.die(`datagram loop: ${c}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),ei)),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(c=>{this.closedReason=`connection error: ${c}`,this.die(`connection error: ${c}`)})}pathLiveness(){return this.closedReason?{alive:!1,evidence:`quic session closed (${this.closedReason})`}:this.controlWriteError?{alive:!1,evidence:`quic control stream refused a write (${this.controlWriteError}) \u2014 the send path is gone`}:this.stopped?{alive:!1,evidence:"webtransport session stopped"}:{alive:!0,evidence:`quic session open; ${this.controlWritesAccepted} control frames accepted by the QUIC stack (one per ${yn}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Yr},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Qr))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let t=typeof e.ds=="number"?e.ds:null,n=typeof e.ur=="number"?e.ur:null;if(t===null&&n===null)return;this.gatewayExposesCounters=!0;let r=this.audioDgramsReceived,s=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:n,recvDownlink:r,sentUplink:s},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,d=n!==null&&o.ur!==null?n-o.ur:null,l=r-o.recvDownlink,c=s-o.sentUplink,p="none";if(a!==null&&a>=bn&&l<=0?p="downlink":d!==null&&c>=bn&&d<=0&&(p="uplink"),p==="none"){this.severedStreak="none",this.observePlayoutProgress(l,t);return}if(this.severedStreak!==p){this.severedStreak=p;return}this.severedStreak="none";let u=p==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${c} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+u+` (gateway flow counters ds=${t} ur=${n}, client received=${r} accepted=${s}, confirmed on ${ti} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,t){let n=this.audioPlayout;if(!n){this.playoutScheduledSeen=null;return}let r=n.playoutProgress(),s=r.surfaced;if(this.playoutScheduledSeen!==null&&r.scheduled>this.playoutScheduledSeen&&s){this.playoutScheduledSeen=r.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=r.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<ni)){if(!this.playoutStallRebuilt){this.playoutStallRebuilt=!0,this.playoutStallStreak=0,console.warn(`[urun] WT playout stalled while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${r.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{n.rebuildSurface()}catch(o){console.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=At}return}this.playoutStallStreak<At||(this.playoutStallStreak=0,this.playoutStallRebuilt=!1,this.die(`playout stalled past its in-place surface rebuild while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${r.scheduled} on ${At} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let t=this.pathLiveness();if(!t.alive)return;let n=performance.now(),r=this.audioLaneLastArrivalAt===null?null:n-this.audioLaneLastArrivalAt,s=this.lastInboundControlAt===null?null:n-this.lastInboundControlAt,o=r===null&&s===null?!0:(r===null||r>=e.stallMs)&&(s===null||s>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&s!==null&&s>=2*a){this.die(`downlink stall: the gateway advertised a ${Math.round(a/1e3)}s liveness cadence but delivered no inbound frame of any kind for ${Math.round(s/1e3)}s while the path reports alive (${t.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}let d=!!(this.offer.audio&&this.audioLane),l=this.lastInboundDataAt===null?null:n-this.lastInboundDataAt,c=r!==null?r:this.firstInboundDataAt===null?null:n-this.firstInboundDataAt,p=c!==null&&c>=e.stallMs;if(d&&p&&l!==null&&l<=Jr&&this.gatewayPings>0){this.die(`media-starved leg: no audio datagram for ${Math.round((c??0)/1e3)}s while the data lane delivered a frame ${Math.round((l??0)/1e3)}s ago (${this.gatewayPings} gateway pings; ${t.evidence}) \u2014 the reliable lanes are alive so the application is mid-conversation, and a dark audio lane under it is severed media fanout, never an idle application; re-dialing`);return}o&&s!==null&&s>=Xr&&this.gatewayPings>0&&this.die(`one-way downlink stall: the gateway pinged this leg before (its downlink pipe demonstrably worked) but NOTHING has arrived \u2014 no audio datagram, no inbound control frame \u2014 for ${Math.round(s/1e3)}s while the path reports alive (${t.evidence}) and client control writes keep resolving \u2014 the downlink is severed in one direction; re-dialing (owner ruling 2026-09-26)`)}async stop(){this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks("webtransport session stopped"),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}datagramWriter(){if(!this.dgramWriter){let e=this.wt.datagrams.writable;if(!e)throw new Error("WebTransport datagrams are not writable in this environment");this.dgramWriter=e.getWriter()}return this.dgramWriter}releaseDatagramWriter(){let e=this.dgramWriter;if(e){this.dgramWriter=null;try{e.releaseLock?.()}catch{}}}dropUplinks(e){this.dropDatagramUplinks(e);let t=this.dataUplinkSender;t&&(this.dataUplinkSender=null,t.stop(e),this.dataUplink?.onUplinkLost(e,t))}dropDatagramUplinks(e){if(this.clearUplinkRetryTimers(),this.audioUplinkLane!==null||this.audioUplinkRetry!==null){let r=this.audioUplinkLane;r?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e,r??void 0)}if(this.videoUplinkLane!==null||this.videoUplinkRetry!==null){let r=this.videoUplinkLane;r?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e,r??void 0)}}onDead(e){this.deadCb=e}stats(){return this.lastStats}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");let t={onData:(n,r)=>{if(Zr[n]===!0){let s=performance.now();this.firstInboundDataAt===null&&(this.firstInboundDataAt=s),this.lastInboundDataAt=s}e.onData(n,r)},onLaneError:n=>e.onLaneError(n)};this.dataLaneSink=t,kt(this.wt.incomingUnidirectionalStreams,t).catch(n=>{this.die(`data lane: ${n instanceof Error?n.message:String(n)}`)})}initDecoder(e,t,n){let r=globalThis.VideoDecoder;if(typeof r!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let s=this.canvas.getContext("2d");if(!s)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:n};let o=new r({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,s.drawImage(a,0,0),a.close()},error:a=>this.onDecoderError(a)});o.configure({codec:e,...t>0&&n>0?{codedWidth:t,codedHeight:n}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"}),this.decoder=o}onDecoderError(e){if(this.stopped||this.deadFired)return;console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=this.decoderConfig;if(!t){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder error with no retained config to re-init from \u2014 video stays down: ${e.message}`));return}try{this.initDecoder(t.codec,t.width,t.height),this.decoderErrorLogged=!1}catch(n){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${n instanceof Error?n.message:String(n)}`));return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}uplinkSend(e,t){if(this.stopped||this.deadFired)return;this.datagramWriter().write(e).then(t,r=>this.onUplinkSendError(r))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let t=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,console.error(`[urun] WT uplink datagram send FAILED (${t}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let n=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(r=>n-r<zr),this.uplinkSendErrorsAt.push(n),!(this.uplinkSendErrorsAt.length<Kr)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSink(e){this.datagramWriter();let t=0;return{send:n=>this.uplinkSend(n,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??pe}}engageAudioUplink(){let e=new Be(this.uplinkSink("audio"));e.onDead(t=>this.onUplinkLaneDead("audio",t,e)),e.onRenderTrack?.(t=>this.renderRemoteCb?.(t)),this.renderSource&&e.setRenderSource?.(this.renderSource),this.audioUplinkLane=e,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(e)}engageVideoUplink(){let e=new He(this.uplinkSink("video"));e.onDead(t=>this.onUplinkLaneDead("video",t,e)),this.videoUplinkLane=e,this.videoUplinkRetry=this.freshLaneBuilt(this.videoUplinkRetry),this.videoUplink.onUplink(e)}engageUplinkLane(e){let t=e==="audio"?"mic":"video";try{e==="audio"?this.engageAudioUplink():this.engageVideoUplink()}catch(n){let r=n instanceof Error?n.message:String(n);console.warn(`[urun] WT ${t} uplink failed to engage (${r}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,r)}}freshLaneBuilt(e){let t={count:e?.count??0,builtAt:Date.now(),timer:void 0};return e&&(clearTimeout(e.timer),e.timer=void 0),t}onUplinkLaneDead(e,t,n){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let r=e==="audio"?"mic":"video",s=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,a=s?.builtAt!=null&&Date.now()-s.builtAt>=i.UPLINK_LANE_HEALTHY_MS?1:(s?.count??0)+1;if(a>i.UPLINK_LANE_RETRY_MAX){console.error(`[urun] WT ${r} uplink lane dead (${t}) \u2014 ${i.UPLINK_LANE_RETRY_MAX} recovery attempts exhausted; the lane is down until the transport's own revert runs (onUplinkLost)`),e==="audio"?this.audioUplinkRetry=null:this.videoUplinkRetry=null,this.seamUplinkLost(e,`lane dead after ${i.UPLINK_LANE_RETRY_MAX} recovery attempts: ${t}`,n);return}console.warn(`[urun] WT ${r} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${a}/${i.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let d={count:a,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=d:this.videoUplinkRetry=d,d.timer=setTimeout(()=>{d.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},i.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,t,n){e==="audio"?this.audioUplink.onUplinkLost(t,n):this.videoUplink.onUplinkLost(t,n)}clearUplinkRetryTimers(){for(let e of[this.audioUplinkRetry,this.videoUplinkRetry])e&&(clearTimeout(e.timer),e.timer=void 0)}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:n}=await e.read();if(n)break;if(!t)continue;if(t.byteLength>=P&&t[11]===Fe){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let r=performance.now();if(this.lastArrivalTs>0){let s=r-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(s-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=r,this.reassembler.push(t)}}decodeFrame(e,t,n){let r=globalThis.EncodedVideoChunk;if(typeof r=="function"){if(!this.decoder&&this.decoderConfig)try{this.initDecoder(this.decoderConfig.codec,this.decoderConfig.width,this.decoderConfig.height),this.decoderErrorLogged=!1}catch{return}this.decoder&&(this.decoder.decode(new r({type:t?"key":"delta",timestamp:e*(1e6/24),data:n})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(yt(e)),this.controlWritesAccepted++}catch(t){let n=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=n),this.die(`control stream write refused: ${n}`),t}}async sendControlRaw(e){try{let t=new Uint8Array(4+e.byteLength);new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),await this.writer.write(t),this.controlWritesAccepted++}catch(t){let n=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=n),this.die(`control stream write refused: ${n}`),t}}async readControl(e,t,n=[]){for(;;){let r=n.shift();if(r)return r;let{value:s,done:o}=await e.read();if(o)return null;s&&n.push(...t.push(s))}}async controlLoop(e,t,n){for(;!this.stopped;){let r=await this.readControl(e,t,n);if(!r)break;let s=r;if(this.lastInboundControlAt=performance.now(),s.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(hn(r.raw,"pong"))}catch{}}(s.t==="ping"||s.t==="pong")&&this.observeFlowCounters(s),s.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),n=(t-e)/1e3;e=t;let r=this.reassembler.drainWindow(),s=r.delivered+r.abandoned;this.lastStats={recvBps:n>0?r.bytes*8/n:0,lossPct:s>0?100*r.abandoned/s:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},yn)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks(e),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var Sn=2500,kn=["av01.0.08M.08","avc1.42E01F","avc1.640028"],ri=1e4,me=class i{constructor(e,t,n){this.signaling=e;this.sessionId=t;this.opts=n}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;static WT_REDIAL_BASE_MS=2e3;static WT_REDIAL_MAX=3;static WT_REDIAL_CAP_MS=3e4;wtRedialFailures=0;wtRedialTimer=null;wtDialedHost;wtHostMismatchCount=0;disconnected=!1;downlinkStallWatch=null;watchDownlinkStall(e={}){this.downlinkStallWatch={stallMs:e.stallMs??15e3},this.applyStallWatch()}applyStallWatch(){let e=this.session;!e||e.kind!=="webtransport"||!this.downlinkStallWatch||e.watchDownlinkStall?.(this.downlinkStallWatch)}failCurrentWtLeg(e){if(this.disconnected)return;let t=this.session;!t||t.kind!=="webtransport"||t.fail?.(e)}get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis;this.disconnected=!1;let t=typeof e.WebTransport=="function",n=typeof e.VideoDecoder=="function",r=this.opts.allowWebTransport??!0,s={webtransport:t&&n&&r,webcodecs:n,codecs:kn,wtData:t&&n&&r&&this.opts.dataLane!==void 0,wtAudio:t&&n&&r&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&r&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:t&&n&&r&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&n&&r&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:s}),this.noteOfferedWtHost();let o=s.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,d=o&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(d||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),s.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let l=null;try{return l=this.createWebTransportSession(),await Ct(l.start(),this.opts.quicDeadlineMs??Sn,"quic connect deadline"),this.wtDialedHost=Et(this.offer.webtransport?.url)??this.wtDialedHost,this.engageQuicDataLane(l,s.wtData===!0),this.session=l,d&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(c){if(console.warn(`[urun] WT dial failed (${fe(c)}) \u2014 dialed ${_n(this.offer.webtransport?.url)}`),l?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let p=String(c instanceof Error?c.message:c);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${p}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(p),c}console.warn("[urun] webtransport failed, falling back to webrtc:",c),this.proceedWebRtcDial(`wt failed: ${String(c instanceof Error?c.message:c)}`),this.notifyEstablished("webrtc",String(c instanceof Error?c.message:c))}}if(this.opts.allowWebRtcFallback===!1){let l=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${l} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(l),new Error(`[urun] WT required but unavailable: ${l}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.disconnected=!0,this.wtRedialTimer!==null&&(clearTimeout(this.wtRedialTimer),this.wtRedialTimer=null),this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,await e?.stop()}noteOfferedWtHost(){let e=Et(this.offer?.webtransport?.url);e===void 0||this.wtDialedHost===void 0||e===this.wtDialedHost||(this.wtHostMismatchCount+=1,console.error(`[urun] re-dial offered host ${e} != original host ${this.wtDialedHost}`+(ii(e)?" \u2014 the offered host looks INTERNAL (RFC1918/.internal): an external browser cannot dial it":"")+` (mismatch #${this.wtHostMismatchCount}) \u2014 evidence only, no policy change`))}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let n=this.session,r=this.opts.dataLane!==void 0,s=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",o=this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",a=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",d=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:kn,wtData:r,wtAudio:s,wtAudioUp:o,wtVideoUp:a,wtDataUp:d}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let l=this.createWebTransportSession();try{await Ct(l.start(),this.opts.quicDeadlineMs??Sn,"quic connect deadline")}catch(c){throw console.warn(`[urun] WT dial failed (${fe(c)}) \u2014 dialed ${_n(this.offer.webtransport?.url)}`),l.stop().catch(()=>{}),c}if(this.wtDialedHost=Et(this.offer.webtransport?.url)??this.wtDialedHost,this.session!==n)return l.stop().catch(()=>{}),null;try{this.engageQuicDataLane(l,r)}catch(c){throw l.stop().catch(()=>{}),c}if(this.disconnected)return l.stop().catch(()=>{}),null;this.session=l;{let c=this.offer.webtransport;c&&(this.opts.audioLane===void 0||c.audio!==void 0)&&(this.opts.audioUplink===void 0||c.audioUp===!0)&&(this.opts.videoUplink===void 0||c.videoUp===!0)&&(this.opts.dataLane===void 0||c.data===!0)&&(this.opts.dataUplink===void 0||c.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),n?.stop().catch(()=>{}),l}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let n=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(r,s)=>n.onData(r,s),onLaneError:r=>n.onLaneError(r)}),n.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e,this.opts.audioLane);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new he(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;this.wtRedialFailures=0,this.applyStallWatch(),e.onDead(t=>{if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; re-dialing WT (attempt 1 immediate, then the bounded ladder)`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.redialWtAfterDeath(t,!0);return}let n=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),n){this.session=null,this.wtOnlyLeg=!1,console.warn("[urun] quic died mid-session on a WT-only leg \u2014 RE-DIALING WebTransport first (same session id; the late WebRTC dial is the fallback):",t),this.redialWtAfterDeath(t,!0);return}console.warn("[urun] quic died mid-session, failing over to webrtc:",t),this.lateWebRtcFailover(e,t,n)})}redialWtAfterDeath(e,t=!1){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures>=i.WT_REDIAL_MAX){if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT re-dial failed ${i.WT_REDIAL_MAX} times (${e}) \u2014 WT-REQUIRED policy: no WebRTC floor exists to escalate to; the forever-retry continues in the background`),this.opts.onWtRequiredOutage?.(e);return}console.error(`[urun] WT re-dial failed ${i.WT_REDIAL_MAX} times (${e}) \u2014 standing up the deferred WebRTC dial as the floor; WT keeps retrying in the background`),this.proceedWebRtcDial(`wt re-dial spent: ${e}`),this.lateWebRtcFailover(null,e,!0);return}let n=this.wtRedialFailures+1,r=Dt(i.WT_REDIAL_BASE_MS,n,i.WT_REDIAL_CAP_MS,n===1&&t?0:void 0);console.warn(`[urun] WT re-dial attempt ${n} scheduled in ${Math.round(r)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},r)}async attemptWtRedial(e){if(!(this.disconnected||this.session!==null)){if(this.signaling.isOpen?.()===!1){this.redialWtAfterDeath(`${e}; signaling socket closed \u2014 waiting for the reconnect`);return}this.wtRedialFailures+=1;try{if(await this.retryWebTransport()!==null){console.warn(`[urun] WT leg re-established on the live session (re-dial attempt ${this.wtRedialFailures}/${i.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(t){let n=fe(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${i.WT_REDIAL_MAX} failed (${n}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${n}`)}}}lateWebRtcFailover(e,t,n){this.disconnected||(async()=>{let r=this.createWebRtc();try{let s=await Ct(this.startWebRtcOn(r),this.opts.webRtcFailoverDeadlineMs??ri,"webrtc failover produced no media transport");if(this.session!==e){s.stop().catch(()=>{});return}this.session=s,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(s){if(r.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=s instanceof Error?s.message:String(s),a=n?`media transport lost \u2014 the WebTransport connection dropped (${t}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${t}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;console.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function fe(i){if(i instanceof Error)return i.message;if(typeof i=="string")return i;if(i&&typeof i=="object"){try{let e=JSON.stringify(i);if(e!==void 0&&e!=="{}")return e}catch{}return i.constructor?.name??Object.prototype.toString.call(i).slice(8,-1)}return String(i)}function Et(i){if(i)try{return new URL(i).host}catch{return}}function _n(i){if(!i)return"(no offer url)";try{let e=new URL(i);return e.searchParams.delete("token"),e.toString()}catch{return i.replace(/[?&]token=[^&\s]*/g,"")}}function ii(i){if(!i)return!1;let e=i.replace(/^\[/,"").split("]")[0]?.split(":")[0]??"";return/^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(e)?!0:e.endsWith(".internal")||e.endsWith(".svc.cluster.local")||/^ip-\d+(-\d+)+/.test(e)}function Dt(i,e,t,n){if(n!==void 0)return n;let r=Math.min(i*2**Math.max(0,e-2),t);return Math.round(r*(.75+Math.random()*.5))}function Ct(i,e,t){return new Promise((n,r)=>{let s=setTimeout(()=>r(new Error(t)),e);i.then(o=>{clearTimeout(s),n(o)},o=>{clearTimeout(s),r(o)})})}var si=1e4,ge=class{constructor(e,t=si){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let n=Ie();return new Promise((r,s)=>{let o=setTimeout(()=>{a(),s(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(d=>{if(d.type!==`${e}.response`||d.requestId!==n)return;if(clearTimeout(o),a(),d.error){s(new Error(`[urun] ${e} failed: ${String(d.error)}`));return}let{type:l,requestId:c,...p}=d;r(p)});this.carrier.sendSignal({type:e,requestId:n,...t})||(clearTimeout(o),a(),s(new Error(`[urun] signaling request not sent: ${e} \u2014 the signaling socket is not open`)))})}notify(e,t){this.carrier.sendSignal({type:e,...t})||this.carrier.emitDiagnostic({level:"warning",kind:"signaling-notify-undelivered",message:`signaling notify not sent: ${e} \u2014 the signaling socket is not open`,detail:{method:e}})}on(e,t){return this.carrier.onSignal(n=>{n.type===e&&t(n)})}};var oi="video",ve=class{constructor(e,t=oi){this.transport=e;this.streamName=t;this.firstMedia=new Promise((n,r)=>{this.firstMediaResolve=n,this.firstMediaReject=r}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let n=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(n(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(n)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};function Tn(i){let e=i;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var ai="video";var di=45e3;async function ci(i,e,t){let r=e?.current()?.name??null;if(r==="live")return"live";if(r==="error")return"gone";if(r==="idle"||r==="connecting")return"live";if(!e)return"unconfirmed";let s=e,o=t.runtimeWaitCapMs??di;return new Promise(a=>{let d=!1,l,c=null,p=null,u=!1,f=g=>{d||(d=!0,h(),p!==null&&(clearTimeout(p),p=null),l?.(),a(g))};p=setTimeout(()=>{if(u||d||t.isDisposed())return;u=!0;let g=s.current();i.emitDiagnostic({level:"info",kind:"runtime-pending",message:`waiting for a runtime to pick up session ${t.sessionId} (server status: ${g?.reason??g?.name??"unknown"}) \u2014 media negotiation starts once the runtime is live; this is not a transport failure`})},2e3);let y=()=>{c===null&&!d&&(c=setTimeout(()=>f("unconfirmed"),o))},h=()=>{c!==null&&(clearTimeout(c),c=null)};l=e.subscribe(g=>{let v=g?.name;if(v==="live")return f("live");if(v==="error")return f("gone");h(),Ae(v)||y()}),Ae(r)||y()})}function Rn(i,e,t){let n=globalThis,r=n.document;if(!(typeof r?.createElement=="function"&&typeof n.WebTransport=="function"&&typeof n.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=i.holdWebRtcDial?.(),a=r.createElement("canvas"),d=!1,l=null,c=!1,p=()=>{if(l){for(let S of l.getVideoTracks())try{S.stop()}catch{}l=null}c&&(c=!1,t.onOverrideTrack(null))},u=new me(new ge(i),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new ve(i,t.streamName??ai)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(S,A)=>i.dispatchQuicStreamData(S,A),onQuicLane:()=>i.markStreamDataLaneQuic(),onQuicLaneLost:S=>i.quicStreamDataLaneLost(S),onLaneError:S=>i.raiseQuicStreamDataError(S)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,ctx:t.audioPlayout?.audioContext,onTrack:S=>{d||(S&&i.noteQuicMediaFlowing?.(),t.onOverrideAudioTrack(S))}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>C(),onMediaTransportLost:S=>{d||(p(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(S),C())},onTransportChange:(S,A)=>{d||(S==="webrtc"&&(p(),C()),t.onTransportChange?.(S,A))}}),f=i.onWtOnlyLegDeath?.(S=>u.failCurrentWtLeg(S)),m=null,y=()=>{m!==null&&(clearInterval(m),m=null)},h=t.wtRetryBaseMs??2e3,g=t.wtRetryCapMs??3e4,v=null,R=0,C=()=>{if(d||v!==null||u.activeTransport==="webtransport")return;let S=Dt(h,R+2,g);v=setTimeout(()=>{v=null,R+=1,u.retryWebTransport().then(A=>{if(d){A&&u.disconnect().catch(()=>{});return}if(A)return console.debug(`[urun] webtransport upgraded in background (retry ${R})`),R=0,W(A);C()}).catch(A=>{d||(console.debug(`[urun] webtransport background retry ${R} failed: `+fe(A)),C())})},S)},E=()=>{v!==null&&(clearTimeout(v),v=null)},W=async S=>{if(d||S.kind!=="webtransport")return;let A=t.pathHealthProbeMs??1e4;y();let V=!1;m=setInterval(()=>{if(d||u.activeTransport!=="webtransport")return;let U=Tn(S);if(!U){console.error("[urun] BUG: webtransport session does not implement PathHealthReporting \u2014 the path-health probe cannot run and this leg cannot be judged; disarming (no verdict is better than a verdict derived from media arrival)"),y();return}let M=U.pathLiveness();if(!M.alive){let B=u.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${M.evidence}`+(B?" \u2014 this is a WT-ONLY leg (the WebRTC dial was skipped, so NO RTCPeerConnection and no webrtc track exist to fall back to)":" \u2014 a WebRTC floor exists and stays authoritative")+"; failing the leg so WT is re-established"),y(),U.fail(`path health: ${M.evidence}`);return}if(!V){if(V=!0,u.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${A}ms \u2014 the QUIC PATH IS HEALTHY (${M.evidence}), so this is an IDLE APPLICATION, not a dead path; keeping the leg (WT-only leg: no webrtc track exists) and continuing to watch the path`);return}console.warn(`[urun] webtransport established but no QUIC media after ${A}ms \u2014 no media datagrams reached this client (path healthy: ${M.evidence}); webrtc track remains authoritative`)}},A);try{await S.firstMedia}catch(U){y(),console.debug("[urun] webtransport ended before any media flowed:",U);return}if(y(),d||u.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;l=a.captureStream();let $=l.getVideoTracks()[0];$&&(c=!0,t.onOverrideTrack($))},x=!1;return(async()=>{let S=await ci(i,t.runtimePhase,{sessionId:e,runtimeWaitCapMs:t.runtimeWaitCapMs,isDisposed:()=>d});if(d)return;if(S==="gone"){console.debug(`[urun] session ${e} ended while waiting for a runtime to pick it up \u2014 no media negotiation`),o?.proceed("session ended before a runtime was pulled \u2014 releasing the held WebRTC dial");return}x=!0;let A=await u.connect();if(d){u.disconnect().catch(()=>{});return}await W(A)})().catch(S=>{if(y(),d){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",S);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",S),C();return}o?.proceed(`negotiation unavailable: ${S instanceof Error?S.message:String(S)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",S),C()}),{activeTransport:()=>u.activeTransport,mediaTransportAttempted:()=>x,watchDownlinkStall(S){u.watchDownlinkStall(S)},dispose(){d=!0,f?.(),y(),E(),p(),t.onOverrideAudioTrack?.(null),u.disconnect().catch(()=>{})}}}var li=new Set;function Pt(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var ui="rpc",pi="$presence",Cn=3e4,An=3e4,hi="rpc-resp";function fi(i){return`${hi}:${i}`}function It(){return Ie()}function mi(i){if(i&&typeof i=="object"){let e=i.error;if(e&&typeof e=="object"){let{message:t,code:n}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof n=="string"?n:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof i=="string"?i:JSON.stringify(i)}}function gi(i,e,t,n,r,s,o,a,d,l){let c=[],p=null,u=!1,f=null,m=!1,y,h,g=new Promise((w,_)=>{y=w,h=_});g.catch(()=>{});let v=o(),R=null,C=null,E=null,W=null,x=null,S=null,A=!0,V=()=>{E&&(clearTimeout(E),E=null),W&&(W(),W=null)},$=()=>{x&&(clearTimeout(x),x=null),S&&(S(),S=null)},U=!1,M=()=>{U||!m||(U=!0,i.set({rpc:{[e]:null}}))},B=()=>{A=!1,V(),$(),R?.(),R=null,C?.(),C=null,a?.removeEventListener("abort",k),v.dispose(),M()},J=()=>{if(p){if(c.length>0){let w=p;p=null,w.resolve({value:c.shift(),done:!1})}else if(f!==null){let w=p;p=null,w.reject(f)}else if(u){let w=p;p=null,w.resolve({value:void 0,done:!0})}}},Se=w=>{u||(c.push(w),J())},G=w=>{u||(f=w,u=!0,h(w),B(),J())},b=w=>{u||(u=!0,y(w),B(),J())},k=()=>{let w=a?.reason;G(w instanceof Te?w:new Re(e))},T=w=>{if(!(u||!w||typeof w!="object"))switch($(),M(),w.t){case"delta":typeof w.delta=="string"&&Se(w.delta);break;case"response":b(w.body);break;case"error":{let{message:_,code:H}=mi(w.body);G(new Te(_,{requestId:e,code:w.code??H}));break}}},D=()=>{let w=v.messages()[Symbol.asyncIterator]();R=()=>{w.return?.(void 0)};let _=()=>{A&&w.next().then(H=>{if(A){if(H.done){u||b(void 0);return}T(H.value),_()}},H=>{A&&G(H)})};_()},I=()=>{if(!m){if(m=!0,a){if(a.aborted){G(new Re(e));return}a.addEventListener("abort",k,{once:!0})}C=d?.(w=>G(w))??null,D(),i.set({rpc:{[e]:{args:t,respond_on:n,consumer_id:r,stream:s}}}),l&&l>0&&!i.synced&&(E=setTimeout(()=>{E=null,!u&&!i.synced&&G(new Ze(l,e))},l),W=i.onSynced(()=>V())),S=i.onSynced(()=>{S=null,!(u||U||x)&&(x=setTimeout(()=>{x=null,!(u||U)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(An/1e3)}s. If this app is a urun-python serve app (\`ctx.serve\`), its runtime does not read the \`rpc\` doc that request()/requestStream()/complete() writes \u2014 the call will never resolve (urun-sh/urun-ts#330). Serve-app chat rides the \`llm\` doc + \`llm-resp:<id>\` stream contract instead. The request keeps waiting; abort it via options.signal (request() also supports options.timeout).`)},An))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(I(),c.length>0)return Promise.resolve({value:c.shift(),done:!1});if(f!==null){let w=f;return f=null,Promise.reject(w)}return u?Promise.resolve({value:void 0,done:!0}):new Promise((w,_)=>{p={resolve:w,reject:_}})},return(){return u||(u=!0,y(void 0),B()),Promise.resolve({value:void 0,done:!0})},throw(w){return u||(u=!0,h(w),B()),Promise.reject(w)}}}},body:g,start:I}}function En(i){if(i&&typeof i=="object"){let{epoch:e,by:t}=i,n={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(n.by=t),n}}function vi(i,e){let n=i.get("streams")?.[e];if(!n||typeof n!="object")return null;let{kind:r,rt:s,br:o}=n,a={};(r==="audio"||r==="video"||r==="data")&&(a.kind=r);let d=En(s);d&&(a.rt=d);let l=En(o);return l&&(a.br=l),a}var Lt=class{constructor(e,t,n,r,s){this._name=e;this._transport=t;this._streamData=n;this._controlDoc=r;this._onActivity=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_directOut=!1;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],n=null,r=!1,s=null,o={push(d){if(!r)if(n){let l=n;n=null,l.resolve({value:d,done:!1})}else t.push(d)},end(){if(r=!0,n){let d=n;n=null,d.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{r=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(d=>{if(!(d===null||r)&&(s=e._streamConsumeUnavailableError(d),a(),n)){let l=n;n=null,l.reject(s)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.reject(s):r?Promise.resolve({value:void 0,done:!0}):new Promise((d,l)=>{n={resolve:d,reject:l}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}get directOut(){return this._directOut}_setOverrideTrack(e,t){if(this._overrideTrack===e&&this._directOut===(t?.directOut??!1))return;this._overrideTrack=e,this._directOut=e?t?.directOut??!1:!1,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let n=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let s of r)s(n)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),n=vi(t,this._name),r=n?.br;if(r?.by==="runtime")throw new et(this._name,"runtime","browser");if(r)return;let s={br:{epoch:1}};n?.rt&&(s.rt=n.rt);let o=n?.kind??e;o&&(s.kind=o),t.set({streams:{[this._name]:s}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??vt;return un(t,{track:()=>this.track,onTrack:r=>this.on("track",r)})}onSeeked(e){return this._transport.on("seeked",(t,n)=>{t===this._name&&e(n)})}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n?.delete(t),n?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let n of t)n(e)}},we=class i{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Jt;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,n,r,s,o){this._sessionId=e,this._multiplexer=t,this._transport=n,this._recordingsAuth=r,this._artifactsAuth=s,this._streamData=Qt(n),this._wireControlDocIncarnation(),this._lifecycleUnsub=ft(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=ht({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new ae({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(pi).awareness.setLocalState({role:"client"}),this._activation=new ie({onPhase:a=>this.onPhase(a),hint:()=>this.doc(at).get(dt)??this.doc("control").get(ct),onData:(a,d)=>this._streamData.onData(a,d)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let n=await zt({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),r=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,s=new ke,o=new Le({url:n.wsUrl,orgId:t.orgId,jwt:r,authProvider:t.authProvider,sessionId:e,iceServers:n.response.ice_servers}),a=new i(e,s,o,Pt(t),se({...t,baseUrl:n.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&s.setTarget(o.multiplexer)}),o.setConnection({url:n.wsUrl,sessionId:e,iceServers:n.response.ice_servers}),o.setEndsAt(n.endsAt),Ee()&&await Ce();let d=t.getAccessToken,l=d?async()=>await d()??r:r;return a.setDocTransport({wsUrl:n.wsUrl,token:l}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}get region(){return this._transport.region}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return nt(this,e)}on(e,t){if(e!=="generationTick")throw new Error(`[urun] unknown session event ${String(e)}`);return this._generationTickHandlers.add(t),this._generationTickStop||(this._generationTickStop=ut(this.doc("control"),n=>{for(let r of Array.from(this._generationTickHandlers))try{r(n)}catch(s){console.warn("[urun] generationTick handler failed:",s)}})),()=>{this._generationTickHandlers.delete(t),this._generationTickHandlers.size===0&&(this._generationTickStop?.(),this._generationTickStop=null)}}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new te(e);return this._recordingsAccessor={list:n=>t.list(n??this._sessionId),get:n=>t.get(n),retain:(n,r)=>t.retain(n,r),pin:n=>t.pin(n),unpin:n=>t.unpin(n),permanent:n=>t.permanent(n),delete:n=>t.delete(n)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new Y(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new Y(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let n of this._docs.values())n.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new Lt(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._autoTouch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new Zt(e,this._sessionId,li.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=en(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}_autoTouch(){this._activityMode!=="explicit"&&this._activity?.touch()}activity(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=Pe(e.wsUrl),n=typeof e.token=="function"?"<token-supplier>":e.token??"",r=`${t}\0${n}\0${this._sessionId}`;r!==this._docEndpointKey&&(this._docEndpointKey=r,this.connectDocs(Xt({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let n=It(),r=new AbortController;t.signal&&(t.signal.aborted?r.abort(t.signal.reason):t.signal.addEventListener("abort",()=>r.abort(t.signal.reason),{once:!0}));let s=null;if(typeof t.timeout=="number"&&t.timeout>=0){let d=t.timeout;s=setTimeout(()=>r.abort(new Je(d,n)),d)}let o=this._consumeResponse(n,e,!1,r.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{s&&clearTimeout(s),a?.()})}_consumeResponse(e,t,n,r,s){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(ui),a=fi(e);return gi(o,e,t,a,this._streamData.consumerId,n,()=>this.stream(a),r,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),s??Cn)}requestStream(e,t={}){let n=It();return this._consumeResponse(n,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let n=It(),r=this._consumeResponse(n,e,!1,t.signal,t.docSyncTimeout);return r.start(),r.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}connect(){return this._transport.connect()}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=Rn(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,runtimePhase:{current:()=>this._transport.phase??null,subscribe:t=>this._transport.on("phase",t)},onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t),onOverrideAudioTrack:t=>this.stream("audio")._setOverrideTrack(t,{directOut:!0}),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}),this._downlinkStallWatch&&this._dialNegotiation?.watchDownlinkStall(this._downlinkStallWatch))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}get mediaTransportAttempted(){return this._dialNegotiation?.mediaTransportAttempted()??!1}watchDownlinkStall(e={}){return this._downlinkStallWatch=e,this._dialNegotiation?.watchDownlinkStall(e),()=>{this._downlinkStallWatch=null}}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.detach(e.status==="paused"?e.reason:void 0),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new K)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new K);let e=this._cancelHandler().then(t=>(this.disconnect(),t));return this._cancelPromise=e,e.catch(()=>{this._cancelPromise===e&&(this._cancelPromise=void 0)}),e}disconnect(){this.detach()}detach(e){let t=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let r of t)try{r()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let n=Array.from(this._activeRequests);this._activeRequests.clear();for(let r of n)try{r(new tt)}catch{}for(let r of this._docs.values())r.dispose();this._docs.clear();for(let r of this._streams.values())r.dispose();this._streams.clear(),this._transport.disconnect(e)}};function Dn(i){return`urun:session:v2:${i.orgId}:${i.app}:${i.functionName}`}function xt(){try{return globalThis.sessionStorage??null}catch{return null}}var Ut=new Map;function Ve(i){if(!i)return;let e=i.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=JSON.parse(atob(t+"=".repeat((4-t.length%4)%4)));return typeof n?.sub=="string"&&n.sub.length>0?n.sub:void 0}catch{return}}function wi(i,e){return i!==void 0&&e!==void 0&&i!==e}function Mt(i,e){let t=xt(),n=null;if(t)try{let s=t.getItem(i);if(s){let o=JSON.parse(s);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(n={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{n=null}let r=Ut.get(i)??n??null;return!r||wi(r.actor,e)?null:r}function In(i,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};Ut.set(i,t);let n=xt();if(n)try{n.setItem(i,JSON.stringify(t))}catch{}}function Ge(i){Ut.delete(i);let e=xt();if(e)try{e.removeItem(i)}catch{}}var Ln=new Set(["paused","acquiring","live"]),yi=new Set(["24h","keep"]);function Pn(i){if(typeof i!="string"||i.length===0)return null;let e=new Date(i);return Number.isFinite(e.getTime())?e:null}function bi(i){if(typeof i?.id!="string"||i.id.length===0)throw new _e("[urun] session list returned a row with no id \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_row"});if(typeof i.state!="string"||!Ln.has(i.state))throw new _e(`[urun] session ${i.id} reported an unrecognized state ${JSON.stringify(i.state)} \u2014 this @urun-sh/core build knows only ${[...Ln].join(", ")}. The SDK may be out of date for this control plane. NOTE: there is no terminal session state; a word like "closed" or "ended" arriving here is a server-side bug.`,{code:"unknown_session_state"});let e=!1;return typeof i.recordings_expired=="boolean"?e=i.recordings_expired:console.warn(`[urun] session ${i.id} list row has no recordings_expired (or a non-boolean value) \u2014 this control plane predates it; treating the session as not-expired`),{id:i.id,label:typeof i.label=="string"&&i.label.length>0?i.label:null,state:i.state,app:typeof i.app=="string"?i.app:"",functionName:typeof i.function=="string"?i.function:"",createdAt:Pn(i.created_at),lastActiveAt:Pn(i.last_active_at),archived:i.archived===!0,preview:typeof i.preview=="string"&&i.preview.length>0?i.preview:null,recordingsExpired:e,retention:yi.has(i.retention)?i.retention:(i.retention!==void 0&&console.warn(`[urun] session ${i.id} reported an unrecognized retention ${JSON.stringify(i.retention)} \u2014 defaulting to '24h'`),"24h")}}var ye=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:n}=await Vt({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(bi),nextCursor:n}}async end(e){await Gt({...this._request,sessionId:e})}async archive(e){await it({...this._request,sessionId:e,archived:!0})}async unarchive(e){await it({...this._request,sessionId:e,archived:!1})}async setName(e,t,n={}){await Kt({...this._request,sessionId:e,name:t,source:n.source})}};function xn(i,e,t){let n=Ve(t);In(i,n!==void 0?{sessionId:e,actor:n}:{sessionId:e})}var Si=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function ki(i,e){return new ye(i,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function _i(i,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(t,n){if(!(Si.has(n)||typeof n!="string"))return(r,s)=>{let o=r??{},a=Dn({orgId:e.orgId,app:i,functionName:n}),d=!s?.sessionId&&!e.sessionKey&&!!s?.label,l,c=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,p=c(),u=e.jwt,f=e.getAccessToken?async b=>{let k=await e.getAccessToken(b);return k&&(u=k),k}:void 0,m={...e,getAccessToken:f},y=new ke,h=new Le({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:p,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),g=new we(p,y,h,Pt(m),se(m),{activity:s?.activity}),v,R=!1,C=!1,E,W,x=new Promise(b=>{W=b}),S,A=b=>{b.sessionId||E||(E="teardown",S="ticket",De({baseUrl:b.baseUrl,requestId:b.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))},V=b=>{E||b.sessionId||(E="abandon",De({baseUrl:b.baseUrl,requestId:b.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider,reason:"client_abandoned"}))},$=b=>{let k=b.sessionId||!l?b:{...b,sessionId:l};v=k,W({status:"ready",handle:k}),(C||E==="teardown")&&A(k)};g.setEndHandler(async()=>{let b=v?{status:"ready",handle:v}:await x;if(b.status==="unavailable")throw new K("[urun] session allocation failed before a releasable request was created",{cause:b.cause});let k=v??b.handle;return Ge(a),E==="teardown"?k.sessionId?{status:"paused",sessionId:k.sessionId,reason:"client_ended"}:{status:"canceled",requestId:k.requestId}:(E="end",k.sessionId?Ht({baseUrl:k.baseUrl,sessionId:k.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):rt({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),g.setCancelHandler(async()=>{let b=v?{status:"ready",handle:v}:await x;if(b.status==="unavailable")throw new K("[urun] session allocation failed before a cancellable request was created",{cause:b.cause});let k=v??b.handle;if(k.sessionId)throw new Xe(`[urun] cancel() is for a queued admission request, but this call already has session ${k.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:k.sessionId,code:"cancel_on_live_session"});E="end";try{let T=await rt({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return Ge(a),T}catch(T){throw E==="end"&&(E=void 0),T}});let U=async b=>{let k,T=s?.sessionId??e.sessionKey??l,D,I;if(T===void 0&&!d){let N=Mt(a);if(N?.sessionId){if(I=Ve(u),N.actor!==void 0&&I===void 0&&f){let Qe=await Promise.resolve(f()).catch(()=>{});I=Ve(Qe??e.jwt)}D=N.actor!==void 0&&I!==void 0&&N.actor!==I?void 0:N.sessionId}}let O=T??D,w=(N,Qe)=>jt({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:n,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,idempotencyKey:N,sessionKey:Qe,label:s?.label,...s?.sharedApp?{sharedApp:!0}:{},concurrencyKey:s?.concurrencyKey,priority:e.priority,onAdmission:j=>{h.reportAdmission(j),j.sessionId&&!l&&(l=j.sessionId,k=j.sessionId,v&&v.sessionId!==j.sessionId&&$({...v,sessionId:j.sessionId}),R||(e.sessionKey||xn(a,j.sessionId,u),g.setSessionId(j.sessionId)))},onRequest:$}),_;try{_=await w(b,O)}catch(N){if(D===void 0||!(N instanceof z)||N.code!=="session_name_not_yours")throw N;console.warn(`[urun] session_name_not_yours: the control plane refused session ${D} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),Mt(a,I)?.sessionId===D&&Ge(a),_=await w(c(),void 0)}let H=f?await f()??void 0:e.jwt;if(k&&k!==_.sessionId)throw v&&v.sessionId!==_.sessionId&&$({...v,sessionId:_.sessionId}),new z(`Gateway contract violation: admission minted session ${k} but allocation completed as ${_.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return l=_.sessionId,v&&v.sessionId!==_.sessionId&&$({...v,sessionId:_.sessionId}),R||(e.sessionKey||xn(a,_.sessionId,u),g.setSessionId(_.sessionId),g.setArtifactsAuth(se({...m,baseUrl:_.baseUrl})),h.setEndsAt(_.endsAt),h.seedRegion(Yt(_.response))),{url:_.wsUrl,sessionId:_.sessionId,jwt:H,iceServers:_.response.ice_servers,endsAt:_.endsAt}},M,B=0,J=f?async()=>{let b=B++>0;return await f(b?{forceRefresh:!0,reason:"background"}:void 0)??M}:()=>M,Se=()=>{let b=h.connectedUrl;return b?Pe(b):void 0};if(h.setConnectionResolver(async()=>{let b=await U(c());return M=b.jwt,b}),h.on("connected",()=>{h.multiplexer&&y.setTarget(h.multiplexer);let b=h.connectedUrl;b&&g.setDocTransport({wsUrl:b,token:J,resolveServerUrl:Se})}),(async b=>{let k;try{k=await U(b)}catch(T){if(R){W({status:"unavailable",cause:T});return}console.error(`[urun] Failed to create session for ${n}:`,T),v&&V(v);let D=T instanceof Error?T:new Error(String(T)),I=T instanceof z?T.httpStatus:void 0,O=T instanceof z?T.code:void 0,w=T instanceof z?T.retryAfterSeconds:void 0;h.reportAllocationFailure(D,I,O,w),W({status:"unavailable",cause:T});return}R||(h.setAuth({jwt:k.jwt,authProvider:e.authProvider,orgId:e.orgId}),h.setConnection({url:k.url,sessionId:k.sessionId,iceServers:k.iceServers}),Ee()&&await Ce(),M=k.jwt,g.setDocTransport({wsUrl:k.url,token:J,resolveServerUrl:Se}),await h.connect({app:i,functionName:n,args:o}),g.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(p).catch(b=>{console.error(`[urun] Failed to connect session for ${n}:`,b)}),e.releaseOnLeave!==!1){let b=mt(()=>{if(R=!0,h.leaveLeg())return;if(h.connectedUrl!==null){h.disconnect();return}h.disconnect();let O=v;O?A(O):C=!0});g.onDisconnect(b);let k,T,D=!1,I=()=>{D||(D=!0,k?.(),T?.())};x.then(O=>{O.status!=="ready"||D||(k=gt(()=>v!==void 0))}),T=g.onPhase(O=>{let w=O?.name;(w==="paused"||w==="error")&&I()}),D&&T(),g.onDisconnect(I)}return g}}})}var Un="https://api.urun.sh",Mn="URUN_DEV";function Ti(){if(typeof process>"u")return!1;let i=process.env?.[Mn];if(typeof i!="string")return!1;let e=i.trim().toLowerCase();return e==="1"||e==="true"}var X=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Ri(i,e={}){if(!i)throw new X("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,n=Z(e.baseUrl??Un),r={};e.expiresIn!==void 0&&(r.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(r.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(r.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(r.max_session_s=e.maxSessionS),e.subject!==void 0&&(r.subject=e.subject),e.metadata!==void 0&&(r.metadata=e.metadata),e.sharedApp&&(r.shared_app=!0),(e.dev??Ti())&&(r.dev=!0);let s;try{s=await t(`${n}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(r)})}catch(u){throw new X(`[urun] client token mint request failed: ${u instanceof Error?u.message:String(u)}`)}let o={};try{o=await s.json()}catch{}if(!s.ok){let u=typeof o.message=="string"?o.message:`HTTP ${s.status}`;throw new X(`[urun] client token mint failed: ${u}`,s.status)}let a=typeof o.token=="string"?o.token:"",d=typeof o.org_id=="string"?o.org_id:"",l=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,c=typeof o.expires_in=="number"?o.expires_in:void 0;if(!a)throw new X("[urun] client token mint returned no token (control-plane contract violation)",s.status);let p=Number.isFinite(l)?new Date(l):new Date(Date.now()+(c??60)*1e3);return{token:a,expiresAt:p,orgId:d}}var Wn=3e4,On="stream:",Wt=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",n=>{let r;try{r=JSON.parse(typeof n.data=="string"?n.data:"")}catch{return}if(r.rpcId&&this._pendingRpc.has(r.rpcId)){let s=this._pendingRpc.get(r.rpcId);this._pendingRpc.delete(r.rpcId),clearTimeout(s.timer),r.error?s.reject(new Error(r.error)):s.resolve(r.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let n=`${On}${e}`;return this._multiplexer.on(n,r=>{t(r)})}emit(e,t){let n=`${On}${e}`,r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(n,r)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((n,r)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){r(new Error("WebSocket not open"));return}let s=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(s)&&(this._pendingRpc.delete(s),r(new Error(`RPC request "${e}" timed out after ${Wn}ms`)))},Wn);this._pendingRpc.set(s,{resolve:n,reject:r,timer:o}),this._ws.send(JSON.stringify({rpcId:s,type:e,...t}))})}};function Ai(i){let n=`${i.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(i.orgId)}`,r=new WebSocket(n);(i.jwt||i.apiKey)&&r.addEventListener("open",()=>{r.send(JSON.stringify({type:"auth",orgId:i.orgId,jwt:i.jwt,authProvider:i.authProvider,apiKey:i.apiKey}))});let s=new qt(r);return new Wt(r,s)}var Ei='video/mp4; codecs="avc1.42E01E"';function Ci(i,e){let t=e?.codec??Ei,n=document.createElement("video");n.muted=!0,n.playsInline=!0;let r=new MediaSource,s=URL.createObjectURL(r);n.src=s,r.addEventListener("sourceopen",()=>{let u;try{u=r.addSourceBuffer(t)}catch(h){throw h instanceof DOMException&&h.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):h}let f=i.getReader();function m(){return u.updating?new Promise(h=>{u.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function y(){try{for(;;){let{done:h,value:g}=await f.read();if(h){await m(),r.readyState==="open"&&r.endOfStream();return}await m();try{u.appendBuffer(g)}catch(v){if(v instanceof DOMException&&v.name==="QuotaExceededError"){let R=u.buffered;if(R.length>0){let C=R.start(R.length-1);u.remove(0,C),await m(),u.appendBuffer(g)}else throw v}else throw v}}}catch{if(r.readyState==="open")try{r.endOfStream("decode")}catch{}}}y()}),n.play().catch(()=>{});let o=n,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let d=a.call(n),l=d.getTracks(),c=0,p=l.length;if(p===0)n.addEventListener("emptied",()=>{URL.revokeObjectURL(s)},{once:!0});else for(let u of l)u.addEventListener("ended",()=>{c++,c>=p&&URL.revokeObjectURL(s)});return d}function Di(i){return i.status.startsWith("pending_")}var ne=class extends Error{status;code;constructor(e,t){super(e),this.name="CreditsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},be=class extends ne{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function Ii(i,e,t){let n=t||e||`HTTP ${i}`;return i===401?new be(n,e??"unauthorized"):new ne(n,{status:i,code:e??`http_${i}`})}var Ke=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let e=await this._request("GET","/balance");if(!e||typeof e!="object"||typeof e.org_id!="string")throw new ne("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let n=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(n)?n:[]}async _request(e,t,n={}){let r=this._buildUrl(t,n.params),s=await this._resolveToken(),o=await this._fetch(r,e,s);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await this._fetch(r,e,s))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw Ii(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let n=`${this._base}${e}`,r=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return r&&(n+=`?${r}`),n}_fetch(e,t,n){let r={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(r["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:t,headers:r})}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new be("[urun] credits: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let n=(await e.json()).error;if(n&&typeof n=="object"){let{code:r,message:s}=n;return{code:typeof r=="string"?r:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Li(i){return new Ke(i)}var ze=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function Nn(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function Pi(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function xi(i,e){let t=i.getTracks();if(t.length===1&&t[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function Ot(i,e){for(let t of[...i.lostListeners])try{t(e)}catch{}}var Ye=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let n=this.claims.get(e);n&&(this.claims.delete(e),n.released=!0,n.track=null,n.stream=null,Ot(n,new Error(`${e} capture claim superseded by a newer claim`)));let r=this.createState(e,t);return this.claims.set(e,r),await this.converge(r),r.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new ze;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),n={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},r;try{r=await t(n)}catch(o){let a=`one-capture getUserMedia(${Nn(n)}) failed`,d=o instanceof Error?o.message:String(o);for(let l of[...this.claims.values()])if(this.claims.delete(l.kind),l.released=!0,l!==e){let c=new Error(`${a} \u2014 ${l.kind} capture lost: ${d||o}`);c.cause=o,Ot(l,c)}throw o}let s=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of s){let a=Pi(r,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let d=Object.assign(new Error(`one-capture getUserMedia(${Nn(n)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw d;Ot(o,d);continue}if(o.track=a,o.stream=xi(r,a),o!==e)for(let d of[...o.trackListeners])try{d(a,o.stream)}catch{}}}createState(e,t){let n=this,r={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return r.track},get stream(){return r.stream},update(s){return n.enqueue(async()=>{if(r.released)throw new Error(`${e} capture claim already released`);if(r.constraints=s,await n.converge(r),!r.track)throw new Error(`${e} capture update yielded no track`);return r.track})},release(){r.released||(r.released=!0,n.claims.get(e)===r&&n.claims.delete(e),r.track?.stop(),r.track=null,r.stream=null)},onTrack(s){return r.trackListeners.add(s),()=>r.trackListeners.delete(s)},onLost(s){return r.lostListeners.add(s),()=>r.lostListeners.delete(s)}}};return r}},Ui=null;function Mi(){return Ui??=new Ye}var Fn="input",Wi=30;function Oi(i){let e=i.now??Date.now,t=i.field??Fn,n=1e3/Math.max(i.hz??30,.001),r=new Set,s=0,o=0,a=0,d=0,l,c=null,p=!1,u=()=>{if(p)return;l=e(),d+=1;let m={keys:[...r],buttons:s,pointer:{x:o,y:a},seq:d,at:l};try{i.awareness.setLocalStateField(t,m)}catch{}},f=()=>{if(p)return;let m=e();if(l===void 0||m-l>=n){c&&(clearTimeout(c),c=null),u();return}if(c)return;let y=Math.max(n-(m-l),0);c=setTimeout(()=>{c=null,u()},y),c.unref?.()};return{keyDown(m){let y=String(m).toLowerCase();r.has(y)||(r.add(y),f())},keyUp(m){let y=String(m).toLowerCase();r.delete(y)&&f()},setButtons(m){let y=Number.isFinite(m)?Number(m):0;y!==s&&(s=y,f())},movePointer(m,y){let h=Number.isFinite(m)?Number(m):0,g=Number.isFinite(y)?Number(y):0;h===0&&g===0||(o+=h,a+=g,f())},heldKeys(){return[...r]},clear(){p||(r.clear(),s=0,c&&(clearTimeout(c),c=null),u())},dispose(){if(p)return;let m=r.size>0||s!==0;r.clear(),s=0,c&&(clearTimeout(c),c=null),m&&u(),p=!0}}}var Ni=1024,Fi=.92,$i=262144,qi=256e3,Nt=[.9,.8,.7,.6,.5],$n=.8,Bi=8;function $t(i,e,t){if(!(i>0)||!(e>0))throw new Error(`reference image has no pixels (${i}x${e})`);let n=Math.min(1,t/Math.max(i,e));return{width:Math.max(1,Math.round(i*n)),height:Math.max(1,Math.round(e*n))}}async function Hi(i){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(i,{imageOrientation:"from-image"})}async function Bn(i,e,t){let n=await new Promise(r=>{i.toBlob(r,e,e==="image/jpeg"?t:void 0)});if(!n)throw new Error(`could not encode the reference image as ${e}`);return n}function qn(i,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${i} -> ${e} bytes`)}async function Ft(i,e,t,n,r){let s=document.createElement("canvas");s.width=e,s.height=t;let o=s.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return n==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,t)),o.drawImage(i,0,0,e,t),await Bn(s,n,r)}async function ji(i,e,t,n){let{width:r,height:s}=e,o=await Ft(i,r,s,t,n);if(o.size<=256e3)return{blob:o,width:r,height:s};if(t==="image/jpeg"){for(let d of Nt)if(!(d>=n)&&(o=await Ft(i,r,s,t,d),o.size<=256e3))return qn(`quality ${n} -> ${d}`,o.size),{blob:o,width:r,height:s}}let a=t==="image/jpeg"?Nt[Nt.length-1]:n;for(let d=0;d<Bi;d++)if(r=Math.max(16,Math.round(r*$n)),s=Math.max(16,Math.round(s*$n)),o=await Ft(i,r,s,t,a),o.size<=256e3)return qn(`downscaled to ${r}x${s} @ q${a}`,o.size),{blob:o,width:r,height:s};throw new Error(`this image cannot be sent: even at ${r}x${s} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function Vi(i,e){let{maxSize:t=1024,type:n="image/jpeg",quality:r=.92,source:s}=e,o=await Hi(i);try{let a=$t(o.width,o.height,t),d=await ji(o,a,n,r);return{bytes:new Uint8Array(await d.blob.arrayBuffer()),type:n,width:d.width,height:d.height,source:s}}finally{o.close()}}function Gi(i){let e=i instanceof Error?i.name:"",t=i instanceof Error?i.message:String(i);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function Ki(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function zi(i,e){let t=i.videoWidth,n=i.videoHeight;if(!(t>0)||!(n>0))throw new Error("the camera has not shown a frame yet");let{maxSize:r=1024,type:s="image/jpeg",quality:o=.92}=e??{},a=$t(t,n,r),d=document.createElement("canvas");d.width=a.width,d.height=a.height;let l=d.getContext("2d");if(!l)throw new Error("could not prepare the reference image (no 2d canvas context)");s==="image/jpeg"&&(l.fillStyle="#fff",l.fillRect(0,0,a.width,a.height)),l.drawImage(i,0,0,a.width,a.height);let c=await Bn(d,s,o);return{bytes:new Uint8Array(await c.arrayBuffer()),type:s,width:a.width,height:a.height,source:"camera"}}var Yi=new Set(["w","a","s","d"]),re=(i,e)=>Math.min(e,Math.max(-e,i));function Qi(i={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:n=.18,decayTauMs:r=900,frameRelax:s=.06,maxPan:o=.12,maxLogZoom:a=.22}=i,d=0,l=0,c=0,p=null,u=new Set;return{pointerDelta(f,m){d=re(d-f*e,o),l=re(l-m*e,o)},keyDown(f){let m=f.toLowerCase();Yi.has(m)&&u.add(m)},keyUp(f){u.delete(f.toLowerCase())},clearKeys(){u.clear()},frameArrived(){let f=1-s;d*=f,l*=f,c*=f},tick(f){if(p===null){p=f;return}let m=Math.max(0,Math.min(100,f-p))/1e3;p=f,u.has("w")&&(c=re(c+t*m,a)),u.has("s")&&(c=re(c-t*m,a)),u.has("a")&&(d=re(d+n*m,o)),u.has("d")&&(d=re(d-n*m,o));let y=Math.exp(-m*1e3/r);d*=y,l*=y,c*=y},transform(){return{translateX:d,translateY:l,scale:Math.exp(c)}},isIdentity(f=5e-4){return Math.abs(d)<f&&Math.abs(l)<f&&Math.abs(c)<f},reset(){d=0,l=0,c=0,u.clear()}}}export{ur as ACTIVATION_COLD_BOOT_AFTER_MS,pr as ACTIVATION_DEGRADED_AFTER_MS,dt as ACTIVATION_HINT_PATH,lr as ACTIVATION_STILL_AFTER_MS,pt as ACTIVITY_DOM_EVENTS,sn as ACTIVITY_FIELD,Tr as ACTIVITY_STAMP_MIN_INTERVAL_MS,ie as ActivationMonitor,_i as App,Zn as BACKOFF_BASE_MS,tr as BACKOFF_MAX_ATTEMPTS,er as BACKOFF_MAX_MS,Xn as COLD_BOOT_WHEN_LIVE_TIMEOUT_MS,Ye as CaptureController,ze as CaptureUnavailableError,X as ClientTokenError,Ke as CreditsClient,ne as CreditsError,be as CreditsUnauthorizedError,$i as DATA_CHANNEL_MESSAGE_CEILING,Cn as DEFAULT_DOC_SYNC_TIMEOUT_MS,Un as DEFAULT_GATEWAY_URL,Hn as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Fi as DEFAULT_REFERENCE_JPEG_QUALITY,Ni as DEFAULT_REFERENCE_MAX_SIZE,Qn as DEFAULT_WHEN_LIVE_TIMEOUT_MS,or as DERIVED_LEG_SEP,P as DGRAM_HEADER_BYTES,cn as FOCUS_FIELD,Ar as FOREGROUND_COALESCE_MS,ue as FrameReassembler,kr as GENERATION_TICK_EMIT_INTERVAL_MS,_r as GENERATION_TICK_MAX_EXTRAPOLATION_MS,Wi as INPUT_PRESENCE_DEFAULT_HZ,Fn as INPUT_PRESENCE_FIELD,ee as InvalidDurationError,ct as LEGACY_ACTIVATION_HINT_PATH,at as PLATFORM_DOC_NAME,Ne as PermanentLockedError,Oe as PinRequiresActiveTempError,ae as PresenceTracker,jn as ProduceAckTimeoutError,Me as RecordingNotFoundError,te as RecordingsClient,F as RecordingsError,oe as RecordingsUnauthorizedError,Re as RequestAbortError,tt as RequestCancelledError,Ze as RequestDocSyncError,Te as RequestError,Je as RequestTimeoutError,We as RetainNotTempError,Ue as RuntimeArtifactNotFoundError,Y as RuntimeArtifactsClient,L as RuntimeArtifactsError,xe as RuntimeArtifactsUnauthorizedError,cr as SIGNALING_PROTOCOL_VERSION,st as STREAM_END,we as Session,z as SessionAllocationError,ye as SessionDirectory,_e as SessionDirectoryError,Xe as SessionEndError,K as SessionEndUnavailableError,Gn as SessionFailedError,et as StreamDirectionConflict,me as TransportNegotiator,zn as TransportSessionMismatchError,ge as TransportSessionSignaling,Mn as URUN_DEV_ENV,dn as USER_ACTIVITY_FIELD,Rr as USER_ACTIVITY_MIN_INTERVAL_MS,on as VISIBILITY_FIELD,qi as WIRE_MESSAGE_BUDGET,pn as WT_CONTROL_FRAME_MAX,gn as WT_DATA_STREAM_VERSION,ve as WebRtcSession,he as WebTransportSession,ce as WtControlDecoder,$e as WtDataStreamParser,tn as activationHintFrom,Ki as cameraCaptureAvailable,zi as captureStillFromVideo,nr as computeBackoffDelay,kt as consumeWtDataStreams,ht as createActivityTracker,Qi as createCameraWarp,Ri as createClientToken,Li as createCreditsClient,Oi as createInputPresencePublisher,Sr as createRecordingsClient,fr as createRuntimeArtifactsClient,Ai as createStore,ot as decodeStreamEnvelope,dr as derivedLegName,ar as derivedLegRole,Vn as describeSessionFailure,Jn as describeSessionPhase,sr as encodeStreamEnvelope,yt as encodeWtControlFrame,$t as fitWithin,lt as isDurationString,Yn as isPausedPhase,Di as isPendingRecording,rr as isRetryableSessionError,Ae as isWakingPhase,vt as mediaRecorderChunkSource,Vi as normalizeReferenceImage,yr as normalizeRetention,gt as observeLeaveConfirm,ft as observePageLifecycle,mt as observePageTeardown,le as parseDgramHeader,ir as prewake,Gi as referenceImageErrorMessage,De as releaseSessionBeacon,ki as sessionDirectory,Kn as sessionFailureFromMediaError,Mi as sharedCaptureController,Ci as videoStream,ut as watchGenerationTick,nt as whenLive,bt as writeDgramHeader};
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { ag as SessionDirectoryRequestOptions, al as SessionNameSource, h as AppOptions, g as App$1, am as SessionPhase, as as SessionStatus, ao as SessionPhaseName, a as AccessTokenOptions, a5 as RuntimeArtifact, a6 as RuntimeArtifactDownload, Z as Recording, aJ as TransportState, ae as Session$1, C as ChannelEndpoint, aG as TransportSession, d as ActivitySignalMode, i as AttachOptions, af as SessionDiagnostic, b as ActivationEvent, ar as SessionStatsSample, H as GenerationTick, a1 as RecordingsAccessor, a7 as RuntimeArtifactsAccessor, aj as SessionEndResult, at as SessionStream$1, aB as StreamDataTransport, ai as SessionDocumentImpl, aA as StreamChunkOptions, p as ChunkReadable, T as Presence, y as DocConnector, E as DocTokenSupplier, z as DocServerUrlResolver, a3 as RequestOptions, a4 as RequestStreamOptions, az as StoreOptions, ay as Store, n as ChannelMultiplexer, ak as SessionFailureKind, O as MediaSession, R as PathHealthReporting, aF as TransportOfferResponse, aO as WtAudioLaneSeam, aP as WtAudioUplinkSeam, aW as WtVideoUplinkSeam, aV as WtDataUplinkSender, S as PathLiveness, aT as WtDataLaneSink } from './backoff-CR4PB7JI.mjs';
2
- export { c as ActivationState, j as AudioPlayoutOptions, B as BACKOFF_BASE_MS, k as BACKOFF_MAX_ATTEMPTS, l as BACKOFF_MAX_MS, D as DERIVED_LEG_SEP, q as DGRAM_HEADER_BYTES, u as DerivedLegRole, v as DgramHeader, x as DocConnectionState, G as GENERATION_TICK_EMIT_INTERVAL_MS, F as GENERATION_TICK_MAX_EXTRAPOLATION_MS, I as InboundStatsSample, M as MediaChunkBinding, J as MediaChunkSource, K as MediaChunkSourceFactory, N as MediaRecorderChunkSourceOptions, P as NegotiatorDataLaneSeam, Q as NegotiatorOptions, U as PresenceState, V as PrewakeOptions, W as PrewakeResult, X as PrewakeStatus, Y as QuicStreamDataTransport, _ as RecordingBucket, $ as RecordingLifecycle, a0 as RecordingStatus, a2 as ReleaseSessionBeaconOptions, a8 as RuntimeAvailability, a9 as RuntimeWakeDetail, aa as RuntimeWakeGolden, ab as RuntimeWakeReasonCode, ac as SIGNALING_PROTOCOL_VERSION, ad as STREAM_END, ah as SessionDocument, an as SessionPhaseError, aq as SessionStatsOptions, au as SessionText, av as SignalCarrier, aw as Signaling, ax as StartSessionOptions, aC as TransportEstablishedNotify, aD as TransportNegotiator, aE as TransportOfferRequest, aI as TransportSessionSignaling, aK as VideoPlayoutOptions, aL as WT_CONTROL_FRAME_MAX, aM as WT_DATA_STREAM_VERSION, aN as WatchGenerationTickOptions, aQ as WtControlDecoder, aR as WtControlMessage, aS as WtDataEnvelope, aU as WtDataStreamParser, aY as computeBackoffDelay, aZ as consumeWtDataStreams, b0 as decodeStreamEnvelope, b2 as derivedLegName, b3 as derivedLegRole, b4 as encodeStreamEnvelope, b5 as encodeWtControlFrame, b6 as isPendingRecording, b7 as isRetryableSessionError, b8 as mediaRecorderChunkSource, b9 as parseDgramHeader, ba as prewake, bb as releaseSessionBeacon, be as watchGenerationTick, bf as writeDgramHeader } from './backoff-CR4PB7JI.mjs';
1
+ import { ag as SessionDirectoryRequestOptions, al as SessionNameSource, h as AppOptions, g as App$1, am as SessionPhase, as as SessionStatus, ao as SessionPhaseName, a as AccessTokenOptions, a5 as RuntimeArtifact, a6 as RuntimeArtifactDownload, Z as Recording, aJ as TransportState, ae as Session$1, C as ChannelEndpoint, aG as TransportSession, d as ActivitySignalMode, i as AttachOptions, af as SessionDiagnostic, b as ActivationEvent, ar as SessionStatsSample, H as GenerationTick, a1 as RecordingsAccessor, a7 as RuntimeArtifactsAccessor, aj as SessionEndResult, at as SessionStream$1, aB as StreamDataTransport, ai as SessionDocumentImpl, aA as StreamChunkOptions, p as ChunkReadable, T as Presence, y as DocConnector, E as DocTokenSupplier, z as DocServerUrlResolver, a3 as RequestOptions, a4 as RequestStreamOptions, az as StoreOptions, ay as Store, n as ChannelMultiplexer, ak as SessionFailureKind, O as MediaSession, R as PathHealthReporting, aF as TransportOfferResponse, aO as WtAudioLaneSeam, aP as WtAudioUplinkSeam, aW as WtVideoUplinkSeam, aV as WtDataUplinkSender, S as PathLiveness, aT as WtDataLaneSink } from './backoff-X_6wRJIu.mjs';
2
+ export { c as ActivationState, j as AudioPlayoutOptions, B as BACKOFF_BASE_MS, k as BACKOFF_MAX_ATTEMPTS, l as BACKOFF_MAX_MS, D as DERIVED_LEG_SEP, q as DGRAM_HEADER_BYTES, u as DerivedLegRole, v as DgramHeader, x as DocConnectionState, G as GENERATION_TICK_EMIT_INTERVAL_MS, F as GENERATION_TICK_MAX_EXTRAPOLATION_MS, I as InboundStatsSample, M as MediaChunkBinding, J as MediaChunkSource, K as MediaChunkSourceFactory, N as MediaRecorderChunkSourceOptions, P as NegotiatorDataLaneSeam, Q as NegotiatorOptions, U as PresenceState, V as PrewakeOptions, W as PrewakeResult, X as PrewakeStatus, Y as QuicStreamDataTransport, _ as RecordingBucket, $ as RecordingLifecycle, a0 as RecordingStatus, a2 as ReleaseSessionBeaconOptions, a8 as RuntimeAvailability, a9 as RuntimeWakeDetail, aa as RuntimeWakeGolden, ab as RuntimeWakeReasonCode, ac as SIGNALING_PROTOCOL_VERSION, ad as STREAM_END, ah as SessionDocument, an as SessionPhaseError, aq as SessionStatsOptions, au as SessionText, av as SignalCarrier, aw as Signaling, ax as StartSessionOptions, aC as TransportEstablishedNotify, aD as TransportNegotiator, aE as TransportOfferRequest, aI as TransportSessionSignaling, aK as VideoPlayoutOptions, aL as WT_CONTROL_FRAME_MAX, aM as WT_DATA_STREAM_VERSION, aN as WatchGenerationTickOptions, aQ as WtControlDecoder, aR as WtControlMessage, aS as WtDataEnvelope, aU as WtDataStreamParser, aY as computeBackoffDelay, aZ as consumeWtDataStreams, b0 as decodeStreamEnvelope, b2 as derivedLegName, b3 as derivedLegRole, b4 as encodeStreamEnvelope, b5 as encodeWtControlFrame, b6 as isPendingRecording, b7 as isRetryableSessionError, b8 as mediaRecorderChunkSource, b9 as parseDgramHeader, ba as prewake, bb as releaseSessionBeacon, be as watchGenerationTick, bf as writeDgramHeader } from './backoff-X_6wRJIu.mjs';
3
3
  import 'yjs';
4
4
  import 'y-protocols/awareness';
5
5
 
@@ -371,6 +371,8 @@ declare class SessionStream implements SessionStream$1 {
371
371
  private _track;
372
372
 
373
373
  private _overrideTrack;
374
+
375
+ private _directOut;
374
376
  private _handlers;
375
377
  private _unsubscribeTransport;
376
378
 
@@ -401,7 +403,11 @@ declare class SessionStream implements SessionStream$1 {
401
403
  private _deliver;
402
404
  get track(): MediaStreamTrack | null;
403
405
 
404
- _setOverrideTrack(track: MediaStreamTrack | null): void;
406
+ get directOut(): boolean;
407
+
408
+ _setOverrideTrack(track: MediaStreamTrack | null, opts?: {
409
+ directOut?: boolean;
410
+ }): void;
405
411
 
406
412
  private _claimBrowserProducer;
407
413
  attach(track: MediaStreamTrack): Promise<void>;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { ag as SessionDirectoryRequestOptions, al as SessionNameSource, h as AppOptions, g as App$1, am as SessionPhase, as as SessionStatus, ao as SessionPhaseName, a as AccessTokenOptions, a5 as RuntimeArtifact, a6 as RuntimeArtifactDownload, Z as Recording, aJ as TransportState, ae as Session$1, C as ChannelEndpoint, aG as TransportSession, d as ActivitySignalMode, i as AttachOptions, af as SessionDiagnostic, b as ActivationEvent, ar as SessionStatsSample, H as GenerationTick, a1 as RecordingsAccessor, a7 as RuntimeArtifactsAccessor, aj as SessionEndResult, at as SessionStream$1, aB as StreamDataTransport, ai as SessionDocumentImpl, aA as StreamChunkOptions, p as ChunkReadable, T as Presence, y as DocConnector, E as DocTokenSupplier, z as DocServerUrlResolver, a3 as RequestOptions, a4 as RequestStreamOptions, az as StoreOptions, ay as Store, n as ChannelMultiplexer, ak as SessionFailureKind, O as MediaSession, R as PathHealthReporting, aF as TransportOfferResponse, aO as WtAudioLaneSeam, aP as WtAudioUplinkSeam, aW as WtVideoUplinkSeam, aV as WtDataUplinkSender, S as PathLiveness, aT as WtDataLaneSink } from './backoff-CR4PB7JI.js';
2
- export { c as ActivationState, j as AudioPlayoutOptions, B as BACKOFF_BASE_MS, k as BACKOFF_MAX_ATTEMPTS, l as BACKOFF_MAX_MS, D as DERIVED_LEG_SEP, q as DGRAM_HEADER_BYTES, u as DerivedLegRole, v as DgramHeader, x as DocConnectionState, G as GENERATION_TICK_EMIT_INTERVAL_MS, F as GENERATION_TICK_MAX_EXTRAPOLATION_MS, I as InboundStatsSample, M as MediaChunkBinding, J as MediaChunkSource, K as MediaChunkSourceFactory, N as MediaRecorderChunkSourceOptions, P as NegotiatorDataLaneSeam, Q as NegotiatorOptions, U as PresenceState, V as PrewakeOptions, W as PrewakeResult, X as PrewakeStatus, Y as QuicStreamDataTransport, _ as RecordingBucket, $ as RecordingLifecycle, a0 as RecordingStatus, a2 as ReleaseSessionBeaconOptions, a8 as RuntimeAvailability, a9 as RuntimeWakeDetail, aa as RuntimeWakeGolden, ab as RuntimeWakeReasonCode, ac as SIGNALING_PROTOCOL_VERSION, ad as STREAM_END, ah as SessionDocument, an as SessionPhaseError, aq as SessionStatsOptions, au as SessionText, av as SignalCarrier, aw as Signaling, ax as StartSessionOptions, aC as TransportEstablishedNotify, aD as TransportNegotiator, aE as TransportOfferRequest, aI as TransportSessionSignaling, aK as VideoPlayoutOptions, aL as WT_CONTROL_FRAME_MAX, aM as WT_DATA_STREAM_VERSION, aN as WatchGenerationTickOptions, aQ as WtControlDecoder, aR as WtControlMessage, aS as WtDataEnvelope, aU as WtDataStreamParser, aY as computeBackoffDelay, aZ as consumeWtDataStreams, b0 as decodeStreamEnvelope, b2 as derivedLegName, b3 as derivedLegRole, b4 as encodeStreamEnvelope, b5 as encodeWtControlFrame, b6 as isPendingRecording, b7 as isRetryableSessionError, b8 as mediaRecorderChunkSource, b9 as parseDgramHeader, ba as prewake, bb as releaseSessionBeacon, be as watchGenerationTick, bf as writeDgramHeader } from './backoff-CR4PB7JI.js';
1
+ import { ag as SessionDirectoryRequestOptions, al as SessionNameSource, h as AppOptions, g as App$1, am as SessionPhase, as as SessionStatus, ao as SessionPhaseName, a as AccessTokenOptions, a5 as RuntimeArtifact, a6 as RuntimeArtifactDownload, Z as Recording, aJ as TransportState, ae as Session$1, C as ChannelEndpoint, aG as TransportSession, d as ActivitySignalMode, i as AttachOptions, af as SessionDiagnostic, b as ActivationEvent, ar as SessionStatsSample, H as GenerationTick, a1 as RecordingsAccessor, a7 as RuntimeArtifactsAccessor, aj as SessionEndResult, at as SessionStream$1, aB as StreamDataTransport, ai as SessionDocumentImpl, aA as StreamChunkOptions, p as ChunkReadable, T as Presence, y as DocConnector, E as DocTokenSupplier, z as DocServerUrlResolver, a3 as RequestOptions, a4 as RequestStreamOptions, az as StoreOptions, ay as Store, n as ChannelMultiplexer, ak as SessionFailureKind, O as MediaSession, R as PathHealthReporting, aF as TransportOfferResponse, aO as WtAudioLaneSeam, aP as WtAudioUplinkSeam, aW as WtVideoUplinkSeam, aV as WtDataUplinkSender, S as PathLiveness, aT as WtDataLaneSink } from './backoff-X_6wRJIu.js';
2
+ export { c as ActivationState, j as AudioPlayoutOptions, B as BACKOFF_BASE_MS, k as BACKOFF_MAX_ATTEMPTS, l as BACKOFF_MAX_MS, D as DERIVED_LEG_SEP, q as DGRAM_HEADER_BYTES, u as DerivedLegRole, v as DgramHeader, x as DocConnectionState, G as GENERATION_TICK_EMIT_INTERVAL_MS, F as GENERATION_TICK_MAX_EXTRAPOLATION_MS, I as InboundStatsSample, M as MediaChunkBinding, J as MediaChunkSource, K as MediaChunkSourceFactory, N as MediaRecorderChunkSourceOptions, P as NegotiatorDataLaneSeam, Q as NegotiatorOptions, U as PresenceState, V as PrewakeOptions, W as PrewakeResult, X as PrewakeStatus, Y as QuicStreamDataTransport, _ as RecordingBucket, $ as RecordingLifecycle, a0 as RecordingStatus, a2 as ReleaseSessionBeaconOptions, a8 as RuntimeAvailability, a9 as RuntimeWakeDetail, aa as RuntimeWakeGolden, ab as RuntimeWakeReasonCode, ac as SIGNALING_PROTOCOL_VERSION, ad as STREAM_END, ah as SessionDocument, an as SessionPhaseError, aq as SessionStatsOptions, au as SessionText, av as SignalCarrier, aw as Signaling, ax as StartSessionOptions, aC as TransportEstablishedNotify, aD as TransportNegotiator, aE as TransportOfferRequest, aI as TransportSessionSignaling, aK as VideoPlayoutOptions, aL as WT_CONTROL_FRAME_MAX, aM as WT_DATA_STREAM_VERSION, aN as WatchGenerationTickOptions, aQ as WtControlDecoder, aR as WtControlMessage, aS as WtDataEnvelope, aU as WtDataStreamParser, aY as computeBackoffDelay, aZ as consumeWtDataStreams, b0 as decodeStreamEnvelope, b2 as derivedLegName, b3 as derivedLegRole, b4 as encodeStreamEnvelope, b5 as encodeWtControlFrame, b6 as isPendingRecording, b7 as isRetryableSessionError, b8 as mediaRecorderChunkSource, b9 as parseDgramHeader, ba as prewake, bb as releaseSessionBeacon, be as watchGenerationTick, bf as writeDgramHeader } from './backoff-X_6wRJIu.js';
3
3
  import 'yjs';
4
4
  import 'y-protocols/awareness';
5
5
 
@@ -371,6 +371,8 @@ declare class SessionStream implements SessionStream$1 {
371
371
  private _track;
372
372
 
373
373
  private _overrideTrack;
374
+
375
+ private _directOut;
374
376
  private _handlers;
375
377
  private _unsubscribeTransport;
376
378
 
@@ -401,7 +403,11 @@ declare class SessionStream implements SessionStream$1 {
401
403
  private _deliver;
402
404
  get track(): MediaStreamTrack | null;
403
405
 
404
- _setOverrideTrack(track: MediaStreamTrack | null): void;
406
+ get directOut(): boolean;
407
+
408
+ _setOverrideTrack(track: MediaStreamTrack | null, opts?: {
409
+ directOut?: boolean;
410
+ }): void;
405
411
 
406
412
  private _claimBrowserProducer;
407
413
  attach(track: MediaStreamTrack): Promise<void>;