@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.
package/dist/index.js CHANGED
@@ -32,4 +32,4 @@ self.onrtctransform = (event) => {
32
32
  }
33
33
  `;function Yd(n){let e=n.match(/a=rtpmap:(\d+) opus\/48000\/2/)?.[1];if(!e)return n;let t="usedtx=1;useinbandfec=1;maxaveragebitrate=32000",r=!1,s=n.split(`\r
34
34
  `).map(i=>i.startsWith(`a=fmtp:${e} `)&&!i.includes("usedtx=")?(r=!0,`${i};${t}`):i);if(!r){let i=s.findIndex(o=>o===`a=rtpmap:${e} opus/48000/2`);i>=0&&s.splice(i+1,0,`a=fmtp:${e} ${t}`)}return s.join(`\r
35
- `)}var As=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=Am(e)?this.bridgedTrack(e):e,!t))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(t)}catch(r){this.die(`replaceTrack: ${r instanceof Error?r.message:String(r)}`);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 r;try{r=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let s=this.sendPc.addTrack(e);this.sender=s,this.currentTrack=e,this.wireTrackLiveness(e);let i=t.RTCRtpScriptTransform;if(s.transform=new i(r,{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=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toRecv.push(r.candidate),this.flushCandidates())},this.recvPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toSend.push(r.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(r=>this.die(`loopback renegotiate: ${r instanceof Error?r.message:String(r)}`))},this.recvPc.ontrack=r=>{let s=r.transceiver?.mid??null;s!==null&&s===this.renderMidOf()&&this.renderRemoteCb?.(r.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 r=await e.createOffer();r.sdp=Yd(r.sdp??""),await e.setLocalDescription(r),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:r.sdp});let s=await t.createAnswer();s.sdp=Yd(s.sdp??""),await t.setLocalDescription(s),await e.setRemoteDescription(t.localDescription??{type:"answer",sdp:s.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 r=t.context.createMediaStreamDestination();t.connect(r);let s=r.stream.getAudioTracks()[0]??null;return s?(this.nodeBridge={node:t,dest:r},s):(this.die("AudioNode bridge produced no audio track"),null)}catch(r){return this.die(`AudioNode bridge: ${r instanceof Error?r.message:String(r)}`),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([Im],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=t=>{let r=t.data;r?.type==="enc"&&r.payload instanceof ArrayBuffer?this.onEncodedFrame(r.rtpTimestamp??0,new Uint8Array(r.payload)):r?.type==="err"&&this.die(`transform: ${r.detail??"unknown"}`)},e.onerror=t=>this.die(`transform worker: ${t.message||"error"}`),this.worker=e,e}onEncodedFrame(e,t){if(this.stopped)return;let r=ho(this.frameSeq,e,t,this.sink.maxDatagramSize()||on);if(r===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 s of r)this.sink.send(s);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 Am(n){let e=n;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var Lm=9e4,Mm="avc1.42E01F",Om=60,Um=3,Nm=1e4;function Fm(n){return Math.round(n*(Lm/1e6))%2**32>>>0}var Ls=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 r=globalThis.MediaStreamTrackProcessor;if(typeof r!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let s=++this.generation,i=new r({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,i.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&s===this.generation;){let{value:a,done:c}=await i.read();if(c)break;if(a){if(o||this.stopped||s!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&s===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 i=globalThis.VideoEncoder;if(typeof i!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new i({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)})),this.encoderDims=t,this.encoder.configure({codec:Mm,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 s=this.keyframeWanted||this.framesSinceKeyframe>=Om;this.keyframeWanted=!1,this.framesSinceKeyframe=s?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:s})}catch(i){this.onEncoderError(i instanceof Error?i:new Error(String(i)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=ho(this.frameSeq,Fm(e.timestamp),t,this.sink.maxDatagramSize()||on,{lane:zd,keyframe:e.type==="key"});if(r===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 s of r)this.sink.send(s);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(r=>t-r<Nm),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=Um){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 Wm(n){return n.byteLength>=2&&n[0]===1&&n[1]===3}var Ms=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 r=new TextEncoder().encode(e);if(r.byteLength===0||r.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${r.byteLength})`));let s=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let i=this.streams.get(e);if(!i){let a=await this.transport.openUniStream(),c=new Uint8Array(2+r.byteLength);c[0]=1,c[1]=r.byteLength,c.set(r,2),await a.write(c),i={writer:a},this.streams.set(e,i)}let o=new Uint8Array(4+t.byteLength);new DataView(o.buffer).setUint32(0,t.byteLength,!0),o.set(t,4),await i.writer.write(o),Wm(t)&&(this.streams.delete(e),await i.writer.close().catch(()=>{}))}catch(i){throw this.die(i instanceof Error?i.message:String(i)),i}});return this.chain=s.catch(()=>{}),s}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 Qd=250,$m=25,jm=2e3,qm=15e3,Bm=1e3,Hm=45e3,Vm=5e3,zm={llm:!0},Gm=500,Jd=10,Km=2,Ym=2,fo=2,mr=class n{constructor(e,t,r,s,i,o,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=s;this.audioUplink=i;this.videoUplink=o;this.dataUplink=a;this.firstMedia=new Promise((c,d)=>{this.firstFrameResolve=c,this.firstFrameReject=d}),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 fr({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,r=t!==void 0&&t!=="";this.hasVideoLane=r,r&&co(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(l=>({algorithm:"sha-256",value:Uint8Array.from(atob(l),u=>u.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let s=await this.wt.createBidirectionalStream();this.writer=s.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let i=s.readable.getReader(),o=new pr,a=[],c=await this.readControl(i,o,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");let d=c;if(this.lastInboundControlAt=performance.now(),typeof d.pingIntervalMs=="number"&&d.pingIntervalMs>0?this.advertisedPingIntervalMs=d.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")),r&&(co(d.codec,"hello-ack"),this.initDecoder(d.codec,d.width,d.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let l={setSource:p=>{this.renderSource=p,this.audioUplinkLane?.setRenderSource?.(p)},onRemote:p=>{this.renderRemoteCb=p}},u=new Is(this.offer.audio,{...this.audioLane,renderHop:l});try{u.start(),this.audioPlayout=u}catch(p){console.warn(`[urun] WT audio lane failed to start (${p instanceof Error?p.message:String(p)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),u.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 l=this.wt.createUnidirectionalStream?.bind(this.wt);if(!l)throw new Error("WebTransport uni streams are not creatable in this environment");let u=new Ms({openUniStream:async()=>(await l()).getWriter()});u.onDead(p=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(p,u)}),this.dataUplinkSender=u,this.dataUplink.onUplink(u)}catch(l){let u=l instanceof Error?l.message:String(l);console.warn(`[urun] WT data uplink failed to engage (${u}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(u)}this.controlLoop(i,o,a).catch(l=>this.die(`control loop: ${l}`)),this.datagramLoop().catch(l=>this.die(`datagram loop: ${l}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),Gm)),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(l=>{this.closedReason=`connection error: ${l}`,this.die(`connection error: ${l}`)})}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 ${Qd}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??qm},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Bm))}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,r=typeof e.ur=="number"?e.ur:null;if(t===null&&r===null)return;this.gatewayExposesCounters=!0;let s=this.audioDgramsReceived,i=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:r,recvDownlink:s,sentUplink:i},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,c=r!==null&&o.ur!==null?r-o.ur:null,d=s-o.recvDownlink,l=i-o.sentUplink,u="none";if(a!==null&&a>=Jd&&d<=0?u="downlink":c!==null&&l>=Jd&&c<=0&&(u="uplink"),u==="none"){this.severedStreak="none",this.observePlayoutProgress(d,t);return}if(this.severedStreak!==u){this.severedStreak=u;return}this.severedStreak="none";let p=u==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${l} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+p+` (gateway flow counters ds=${t} ur=${r}, client received=${s} accepted=${i}, confirmed on ${Km} 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 r=this.audioPlayout;if(!r){this.playoutScheduledSeen=null;return}let s=r.playoutProgress(),i=s.surfaced;if(this.playoutScheduledSeen!==null&&s.scheduled>this.playoutScheduledSeen&&i){this.playoutScheduledSeen=s.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=s.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<Ym)){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=${s.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{r.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=fo}return}this.playoutStallStreak<fo||(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=${s.scheduled} on ${fo} 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 r=performance.now(),s=this.audioLaneLastArrivalAt===null?null:r-this.audioLaneLastArrivalAt,i=this.lastInboundControlAt===null?null:r-this.lastInboundControlAt,o=s===null&&i===null?!0:(s===null||s>=e.stallMs)&&(i===null||i>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&i!==null&&i>=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(i/1e3)}s while the path reports alive (${t.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}let c=!!(this.offer.audio&&this.audioLane),d=this.lastInboundDataAt===null?null:r-this.lastInboundDataAt,l=s!==null?s:this.firstInboundDataAt===null?null:r-this.firstInboundDataAt,u=l!==null&&l>=e.stallMs;if(c&&u&&d!==null&&d<=Vm&&this.gatewayPings>0){this.die(`media-starved leg: no audio datagram for ${Math.round((l??0)/1e3)}s while the data lane delivered a frame ${Math.round((d??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&&i!==null&&i>=Hm&&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(i/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 s=this.audioUplinkLane;s?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e,s??void 0)}if(this.videoUplinkLane!==null||this.videoUplinkRetry!==null){let s=this.videoUplinkLane;s?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e,s??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:(r,s)=>{if(zm[r]===!0){let i=performance.now();this.firstInboundDataAt===null&&(this.firstInboundDataAt=i),this.lastInboundDataAt=i}e.onData(r,s)},onLaneError:r=>e.onLaneError(r)};this.dataLaneSink=t,xs(this.wt.incomingUnidirectionalStreams,t).catch(r=>{this.die(`data lane: ${r instanceof Error?r.message:String(r)}`)})}initDecoder(e,t,r){let s=globalThis.VideoDecoder;if(typeof s!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let i=this.canvas.getContext("2d");if(!i)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r};let o=new s({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,i.drawImage(a,0,0),a.close()},error:a=>this.onDecoderError(a)});o.configure({codec:e,...t>0&&r>0?{codedWidth:t,codedHeight:r}:{},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(r){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${r instanceof Error?r.message:String(r)}`));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,s=>this.onUplinkSendError(s))}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 r=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(s=>r-s<jm),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<$m)&&(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:r=>this.uplinkSend(r,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??on}}engageAudioUplink(){let e=new As(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 Ls(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(r){let s=r instanceof Error?r.message:String(r);console.warn(`[urun] WT ${t} uplink failed to engage (${s}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,s)}}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,r){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let s=e==="audio"?"mic":"video",i=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,a=i?.builtAt!=null&&Date.now()-i.builtAt>=n.UPLINK_LANE_HEALTHY_MS?1:(i?.count??0)+1;if(a>n.UPLINK_LANE_RETRY_MAX){console.error(`[urun] WT ${s} uplink lane dead (${t}) \u2014 ${n.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 ${n.UPLINK_LANE_RETRY_MAX} recovery attempts: ${t}`,r);return}console.warn(`[urun] WT ${s} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${a}/${n.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let c={count:a,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=c:this.videoUplinkRetry=c,c.timer=setTimeout(()=>{c.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},n.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,t,r){e==="audio"?this.audioUplink.onUplinkLost(t,r):this.videoUplink.onUplinkLost(t,r)}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:r}=await e.read();if(r)break;if(!t)continue;if(t.byteLength>=fe&&t[11]===Ps){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let s=performance.now();if(this.lastArrivalTs>0){let i=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(i-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=s,this.reassembler.push(t)}}decodeFrame(e,t,r){let s=globalThis.EncodedVideoChunk;if(typeof s=="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 s({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(Es(e)),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),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 r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async readControl(e,t,r=[]){for(;;){let s=r.shift();if(s)return s;let{value:i,done:o}=await e.read();if(o)return null;i&&r.push(...t.push(i))}}async controlLoop(e,t,r){for(;!this.stopped;){let s=await this.readControl(e,t,r);if(!s)break;let i=s;if(this.lastInboundControlAt=performance.now(),i.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(Vd(s.raw,"pong"))}catch{}}(i.t==="ping"||i.t==="pong")&&this.observeFlowCounters(i),i.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),r=(t-e)/1e3;e=t;let s=this.reassembler.drainWindow(),i=s.delivered+s.abandoned;this.lastStats={recvBps:r>0?s.bytes*8/r:0,lossPct:i>0?100*s.abandoned/i:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Qd)}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 Xd=2500,Zd=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Qm=1e4,gr=class n{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}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",r=typeof e.VideoDecoder=="function",s=this.opts.allowWebTransport??!0,i={webtransport:t&&r&&s,webcodecs:r,codecs:Zd,wtData:t&&r&&s&&this.opts.dataLane!==void 0,wtAudio:t&&r&&s&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&s&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:t&&r&&s&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&r&&s&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:i}),this.noteOfferedWtHost();let o=i.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,c=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(c||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),i.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let d=null;try{return d=this.createWebTransportSession(),await go(d.start(),this.opts.quicDeadlineMs??Xd,"quic connect deadline"),this.wtDialedHost=mo(this.offer.webtransport?.url)??this.wtDialedHost,this.engageQuicDataLane(d,i.wtData===!0),this.session=d,c&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(l){if(console.warn(`[urun] WT dial failed (${an(l)}) \u2014 dialed ${el(this.offer.webtransport?.url)}`),d?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let u=String(l instanceof Error?l.message:l);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${u}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(u),l}console.warn("[urun] webtransport failed, falling back to webrtc:",l),this.proceedWebRtcDial(`wt failed: ${String(l instanceof Error?l.message:l)}`),this.notifyEstablished("webrtc",String(l instanceof Error?l.message:l))}}if(this.opts.allowWebRtcFallback===!1){let d=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${d} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(d),new Error(`[urun] WT required but unavailable: ${d}`)}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=mo(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}`+(Jm(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 r=this.session,s=this.opts.dataLane!==void 0,i=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",c=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:Zd,wtData:s,wtAudio:i,wtAudioUp:o,wtVideoUp:a,wtDataUp:c}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let d=this.createWebTransportSession();try{await go(d.start(),this.opts.quicDeadlineMs??Xd,"quic connect deadline")}catch(l){throw console.warn(`[urun] WT dial failed (${an(l)}) \u2014 dialed ${el(this.offer.webtransport?.url)}`),d.stop().catch(()=>{}),l}if(this.wtDialedHost=mo(this.offer.webtransport?.url)??this.wtDialedHost,this.session!==r)return d.stop().catch(()=>{}),null;try{this.engageQuicDataLane(d,s)}catch(l){throw d.stop().catch(()=>{}),l}if(this.disconnected)return d.stop().catch(()=>{}),null;this.session=d;{let l=this.offer.webtransport;l&&(this.opts.audioLane===void 0||l.audio!==void 0)&&(this.opts.audioUplink===void 0||l.audioUp===!0)&&(this.opts.videoUplink===void 0||l.videoUp===!0)&&(this.opts.dataLane===void 0||l.data===!0)&&(this.opts.dataUplink===void 0||l.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),d}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let r=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:(s,i)=>r.onData(s,i),onLaneError:s=>r.onLaneError(s)}),r.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 mr(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 r=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),r){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,r)})}redialWtAfterDeath(e,t=!1){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures>=n.WT_REDIAL_MAX){if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT re-dial failed ${n.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 ${n.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 r=this.wtRedialFailures+1,s=_o(n.WT_REDIAL_BASE_MS,r,n.WT_REDIAL_CAP_MS,r===1&&t?0:void 0);console.warn(`[urun] WT re-dial attempt ${r} scheduled in ${Math.round(s)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},s)}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}/${n.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(t){let r=an(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${n.WT_REDIAL_MAX} failed (${r}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${r}`)}}}lateWebRtcFailover(e,t,r){this.disconnected||(async()=>{let s=this.createWebRtc();try{let i=await go(this.startWebRtcOn(s),this.opts.webRtcFailoverDeadlineMs??Qm,"webrtc failover produced no media transport");if(this.session!==e){i.stop().catch(()=>{});return}this.session=i,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(i){if(s.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=i instanceof Error?i.message:String(i),a=r?`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 an(n){if(n instanceof Error)return n.message;if(typeof n=="string")return n;if(n&&typeof n=="object"){try{let e=JSON.stringify(n);if(e!==void 0&&e!=="{}")return e}catch{}return n.constructor?.name??Object.prototype.toString.call(n).slice(8,-1)}return String(n)}function mo(n){if(n)try{return new URL(n).host}catch{return}}function el(n){if(!n)return"(no offer url)";try{let e=new URL(n);return e.searchParams.delete("token"),e.toString()}catch{return n.replace(/[?&]token=[^&\s]*/g,"")}}function Jm(n){if(!n)return!1;let e=n.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 _o(n,e,t,r){if(r!==void 0)return r;let s=Math.min(n*2**Math.max(0,e-2),t);return Math.round(s*(.75+Math.random()*.5))}function go(n,e,t){return new Promise((r,s)=>{let i=setTimeout(()=>s(new Error(t)),e);n.then(o=>{clearTimeout(i),r(o)},o=>{clearTimeout(i),s(o)})})}var Xm=1e4,_r=class{constructor(e,t=Xm){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let r=ar();return new Promise((s,i)=>{let o=setTimeout(()=>{a(),i(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(o),a(),c.error){i(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:d,requestId:l,...u}=c;s(u)});this.carrier.sendSignal({type:e,requestId:r,...t})||(clearTimeout(o),a(),i(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(r=>{r.type===e&&t(r)})}};var Zm="video",vr=class{constructor(e,t=Zm){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),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 r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}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 tl(n){let e=n;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var eg="video";var tg=45e3;async function rg(n,e,t){let s=e?.current()?.name??null;if(s==="live")return"live";if(s==="error")return"gone";if(s==="idle"||s==="connecting")return"live";if(!e)return"unconfirmed";let i=e,o=t.runtimeWaitCapMs??tg;return new Promise(a=>{let c=!1,d,l=null,u=null,p=!1,h=_=>{c||(c=!0,g(),u!==null&&(clearTimeout(u),u=null),d?.(),a(_))};u=setTimeout(()=>{if(p||c||t.isDisposed())return;p=!0;let _=i.current();n.emitDiagnostic({level:"info",kind:"runtime-pending",message:`waiting for a runtime to pick up session ${t.sessionId} (server status: ${_?.reason??_?.name??"unknown"}) \u2014 media negotiation starts once the runtime is live; this is not a transport failure`})},2e3);let f=()=>{l===null&&!c&&(l=setTimeout(()=>h("unconfirmed"),o))},g=()=>{l!==null&&(clearTimeout(l),l=null)};d=e.subscribe(_=>{let v=_?.name;if(v==="live")return h("live");if(v==="error")return h("gone");g(),Be(v)||f()}),Be(s)||f()})}function rl(n,e,t){let r=globalThis,s=r.document;if(!(typeof s?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=n.holdWebRtcDial?.(),a=s.createElement("canvas"),c=!1,d=null,l=!1,u=()=>{if(d){for(let P of d.getVideoTracks())try{P.stop()}catch{}d=null}l&&(l=!1,t.onOverrideTrack(null))},p=new gr(new _r(n),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new vr(n,t.streamName??eg)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(P,N)=>n.dispatchQuicStreamData(P,N),onQuicLane:()=>n.markStreamDataLaneQuic(),onQuicLaneLost:P=>n.quicStreamDataLaneLost(P),onLaneError:P=>n.raiseQuicStreamDataError(P)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,ctx:t.audioPlayout?.audioContext,onTrack:P=>{c||(P&&n.noteQuicMediaFlowing?.(),t.onOverrideAudioTrack(P))}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>w(),onMediaTransportLost:P=>{c||(u(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(P),w())},onTransportChange:(P,N)=>{c||(P==="webrtc"&&(u(),w()),t.onTransportChange?.(P,N))}}),h=n.onWtOnlyLegDeath?.(P=>p.failCurrentWtLeg(P)),m=null,f=()=>{m!==null&&(clearInterval(m),m=null)},g=t.wtRetryBaseMs??2e3,_=t.wtRetryCapMs??3e4,v=null,b=0,w=()=>{if(c||v!==null||p.activeTransport==="webtransport")return;let P=_o(g,b+2,_);v=setTimeout(()=>{v=null,b+=1,p.retryWebTransport().then(N=>{if(c){N&&p.disconnect().catch(()=>{});return}if(N)return console.debug(`[urun] webtransport upgraded in background (retry ${b})`),b=0,T(N);w()}).catch(N=>{c||(console.debug(`[urun] webtransport background retry ${b} failed: `+an(N)),w())})},P)},S=()=>{v!==null&&(clearTimeout(v),v=null)},T=async P=>{if(c||P.kind!=="webtransport")return;let N=t.pathHealthProbeMs??1e4;f();let K=!1;m=setInterval(()=>{if(c||p.activeTransport!=="webtransport")return;let W=tl(P);if(!W){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)"),f();return}let $=W.pathLiveness();if(!$.alive){let Y=p.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${$.evidence}`+(Y?" \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"),f(),W.fail(`path health: ${$.evidence}`);return}if(!K){if(K=!0,p.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${N}ms \u2014 the QUIC PATH IS HEALTHY (${$.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 ${N}ms \u2014 no media datagrams reached this client (path healthy: ${$.evidence}); webrtc track remains authoritative`)}},N);try{await P.firstMedia}catch(W){f(),console.debug("[urun] webtransport ended before any media flowed:",W);return}if(f(),c||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;d=a.captureStream();let ne=d.getVideoTracks()[0];ne&&(l=!0,t.onOverrideTrack(ne))},y=!1;return(async()=>{let P=await rg(n,t.runtimePhase,{sessionId:e,runtimeWaitCapMs:t.runtimeWaitCapMs,isDisposed:()=>c});if(c)return;if(P==="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}y=!0;let N=await p.connect();if(c){p.disconnect().catch(()=>{});return}await T(N)})().catch(P=>{if(f(),c){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",P);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",P),w();return}o?.proceed(`negotiation unavailable: ${P instanceof Error?P.message:String(P)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",P),w()}),{activeTransport:()=>p.activeTransport,mediaTransportAttempted:()=>y,watchDownlinkStall(P){p.watchDownlinkStall(P)},dispose(){c=!0,h?.(),f(),S(),u(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var ng=new Set;function yo(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var sg="rpc",ig="$presence",bo=3e4,nl=3e4,og="rpc-resp";function ag(n){return`${og}:${n}`}function vo(){return ar()}function cg(n){if(n&&typeof n=="object"){let e=n.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof n=="string"?n:JSON.stringify(n)}}function dg(n,e,t,r,s,i,o,a,c,d){let l=[],u=null,p=!1,h=null,m=!1,f,g,_=new Promise((k,F)=>{f=k,g=F});_.catch(()=>{});let v=o(),b=null,w=null,S=null,T=null,y=null,P=null,N=!0,K=()=>{S&&(clearTimeout(S),S=null),T&&(T(),T=null)},ne=()=>{y&&(clearTimeout(y),y=null),P&&(P(),P=null)},W=!1,$=()=>{W||!m||(W=!0,n.set({rpc:{[e]:null}}))},Y=()=>{N=!1,K(),ne(),b?.(),b=null,w?.(),w=null,a?.removeEventListener("abort",U),v.dispose(),$()},Z=()=>{if(u){if(l.length>0){let k=u;u=null,k.resolve({value:l.shift(),done:!1})}else if(h!==null){let k=u;u=null,k.reject(h)}else if(p){let k=u;u=null,k.resolve({value:void 0,done:!0})}}},me=k=>{p||(l.push(k),Z())},ee=k=>{p||(h=k,p=!0,g(k),Y(),Z())},D=k=>{p||(p=!0,f(k),Y(),Z())},U=()=>{let k=a?.reason;ee(k instanceof Pe?k:new ot(e))},q=k=>{if(!(p||!k||typeof k!="object"))switch(ne(),$(),k.t){case"delta":typeof k.delta=="string"&&me(k.delta);break;case"response":D(k.body);break;case"error":{let{message:F,code:Qe}=cg(k.body);ee(new Pe(F,{requestId:e,code:k.code??Qe}));break}}},te=()=>{let k=v.messages()[Symbol.asyncIterator]();b=()=>{k.return?.(void 0)};let F=()=>{N&&k.next().then(Qe=>{if(N){if(Qe.done){p||D(void 0);return}q(Qe.value),F()}},Qe=>{N&&ee(Qe)})};F()},E=()=>{if(!m){if(m=!0,a){if(a.aborted){ee(new ot(e));return}a.addEventListener("abort",U,{once:!0})}w=c?.(k=>ee(k))??null,te(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:i}}}),d&&d>0&&!n.synced&&(S=setTimeout(()=>{S=null,!p&&!n.synced&&ee(new Ct(d,e))},d),T=n.onSynced(()=>K())),P=n.onSynced(()=>{P=null,!(p||W||y)&&(y=setTimeout(()=>{y=null,!(p||W)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(nl/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).`)},nl))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(E(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(h!==null){let k=h;return h=null,Promise.reject(k)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((k,F)=>{u={resolve:k,reject:F}})},return(){return p||(p=!0,f(void 0),Y()),Promise.resolve({value:void 0,done:!0})},throw(k){return p||(p=!0,g(k),Y()),Promise.reject(k)}}}},body:_,start:E}}function sl(n){if(n&&typeof n=="object"){let{epoch:e,by:t}=n,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function lg(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:i,br:o}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let c=sl(i);c&&(a.rt=c);let d=sl(o);return d&&(a.br=d),a}var wo=class{constructor(e,t,r,s,i){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;this._onActivity=i;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],r=null,s=!1,i=null,o={push(c){if(!s)if(r){let d=r;r=null,d.resolve({value:c,done:!1})}else t.push(c)},end(){if(s=!0,r){let c=r;r=null,c.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{s=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(c=>{if(!(c===null||s)&&(i=e._streamConsumeUnavailableError(c),a(),r)){let d=r;r=null,d.reject(i)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):i?Promise.reject(i):s?Promise.resolve({value:void 0,done:!0}):new Promise((c,d)=>{r={resolve:c,reject:d}})},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,r=this._handlers.get("track");if(r)for(let s of r)s(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=lg(t,this._name),s=r?.br;if(s?.by==="runtime")throw new Et(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};r?.rt&&(i.rt=r.rt);let o=r?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}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??Rs;return Hd(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.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 r of t)r(e)}},wr=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new ms;_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,r,s,i,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=ld(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Ss(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=bs({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new ur({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(ig).awareness.setLocalState({role:"client"}),this._activation=new It({onPhase:a=>this.onPhase(a),hint:()=>this.doc(fn).get(mn)??this.doc("control").get(gn),onData:(a,c)=>this._streamData.onData(a,c)})}_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 r=await oa({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new Tt,o=new lr({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,i,o,yo(t),Ir({...t,baseUrl:r.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),o.setEndsAt(r.endsAt),et()&&await At();let c=t.getAccessToken,d=c?async()=>await c()??s:s;return a.setDocTransport({wsUrl:r.wsUrl,token:d}),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 hn(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=ws(this.doc("control"),r=>{for(let s of Array.from(this._generationTickHandlers))try{s(r)}catch(i){console.warn("[urun] generationTick handler failed:",i)}})),()=>{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 ut(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,s)=>t.retain(r,s),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new tt(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new tt(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 r of this._docs.values())r.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new wo(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 vs(e,this._sessionId,ng.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Ud(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=gs(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",s=`${t}\0${r}\0${this._sessionId}`;s!==this._docEndpointKey&&(this._docEndpointKey=s,this.connectDocs(Md({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 r=vo(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let c=t.timeout;i=setTimeout(()=>s.abort(new Rt(c,r)),c)}let o=this._consumeResponse(r,e,!1,s.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{i&&clearTimeout(i),a?.()})}_consumeResponse(e,t,r,s,i){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(sg),a=ag(e);return dg(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??bo)}requestStream(e,t={}){let r=vo();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=vo(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.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=rl(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 Ue)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new Ue);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 s of t)try{s()}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 r=Array.from(this._activeRequests);this._activeRequests.clear();for(let s of r)try{s(new Dt)}catch{}for(let s of this._docs.values())s.dispose();this._docs.clear();for(let s of this._streams.values())s.dispose();this._streams.clear(),this._transport.disconnect(e)}};function il(n){return`urun:session:v2:${n.orgId}:${n.app}:${n.functionName}`}function So(){try{return globalThis.sessionStorage??null}catch{return null}}var ko=new Map;function Os(n){if(!n)return;let e=n.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=JSON.parse(atob(t+"=".repeat((4-t.length%4)%4)));return typeof r?.sub=="string"&&r.sub.length>0?r.sub:void 0}catch{return}}function ug(n,e){return n!==void 0&&e!==void 0&&n!==e}function To(n,e){let t=So(),r=null;if(t)try{let i=t.getItem(n);if(i){let o=JSON.parse(i);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(r={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{r=null}let s=ko.get(n)??r??null;return!s||ug(s.actor,e)?null:s}function ol(n,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};ko.set(n,t);let r=So();if(r)try{r.setItem(n,JSON.stringify(t))}catch{}}function Us(n){ko.delete(n);let e=So();if(e)try{e.removeItem(n)}catch{}}var al=new Set(["paused","acquiring","live"]),pg=new Set(["24h","keep"]);function cl(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}function hg(n){if(typeof n?.id!="string"||n.id.length===0)throw new ve("[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 n.state!="string"||!al.has(n.state))throw new ve(`[urun] session ${n.id} reported an unrecognized state ${JSON.stringify(n.state)} \u2014 this @urun-sh/core build knows only ${[...al].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 n.recordings_expired=="boolean"?e=n.recordings_expired:console.warn(`[urun] session ${n.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:n.id,label:typeof n.label=="string"&&n.label.length>0?n.label:null,state:n.state,app:typeof n.app=="string"?n.app:"",functionName:typeof n.function=="string"?n.function:"",createdAt:cl(n.created_at),lastActiveAt:cl(n.last_active_at),archived:n.archived===!0,preview:typeof n.preview=="string"&&n.preview.length>0?n.preview:null,recordingsExpired:e,retention:pg.has(n.retention)?n.retention:(n.retention!==void 0&&console.warn(`[urun] session ${n.id} reported an unrecognized retention ${JSON.stringify(n.retention)} \u2014 defaulting to '24h'`),"24h")}}var yr=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:r}=await na({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(hg),nextCursor:r}}async end(e){await sa({...this._request,sessionId:e})}async archive(e){await Gs({...this._request,sessionId:e,archived:!0})}async unarchive(e){await Gs({...this._request,sessionId:e,archived:!1})}async setName(e,t,r={}){await ia({...this._request,sessionId:e,name:t,source:r.source})}};function dl(n,e,t){let r=Os(t);ol(n,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}var fg=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function ll(n,e){return new yr(n,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function ul(n,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,r){if(!(fg.has(r)||typeof r!="string"))return(s,i)=>{let o=s??{},a=il({orgId:e.orgId,app:n,functionName:r}),c=!i?.sessionId&&!e.sessionKey&&!!i?.label,d,l=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,u=l(),p=e.jwt,h=e.getAccessToken?async D=>{let U=await e.getAccessToken(D);return U&&(p=U),U}:void 0,m={...e,getAccessToken:h},f=new Tt,g=new lr({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:u,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),_=new wr(u,f,g,yo(m),Ir(m),{activity:i?.activity}),v,b=!1,w=!1,S,T,y=new Promise(D=>{T=D}),P,N=D=>{D.sessionId||S||(S="teardown",P="ticket",Pr({baseUrl:D.baseUrl,requestId:D.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider}))},K=D=>{S||D.sessionId||(S="abandon",Pr({baseUrl:D.baseUrl,requestId:D.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider,reason:"client_abandoned"}))},ne=D=>{let U=D.sessionId||!d?D:{...D,sessionId:d};v=U,T({status:"ready",handle:U}),(w||S==="teardown")&&N(U)};_.setEndHandler(async()=>{let D=v?{status:"ready",handle:v}:await y;if(D.status==="unavailable")throw new Ue("[urun] session allocation failed before a releasable request was created",{cause:D.cause});let U=v??D.handle;return Us(a),S==="teardown"?U.sessionId?{status:"paused",sessionId:U.sessionId,reason:"client_ended"}:{status:"canceled",requestId:U.requestId}:(S="end",U.sessionId?Vs({baseUrl:U.baseUrl,sessionId:U.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:h,authProvider:e.authProvider}):Hs({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:h,authProvider:e.authProvider}))}),_.setCancelHandler(async()=>{let D=v?{status:"ready",handle:v}:await y;if(D.status==="unavailable")throw new Ue("[urun] session allocation failed before a cancellable request was created",{cause:D.cause});let U=v??D.handle;if(U.sessionId)throw new ae(`[urun] cancel() is for a queued admission request, but this call already has session ${U.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:U.sessionId,code:"cancel_on_live_session"});S="end";try{let q=await Hs({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:h,authProvider:e.authProvider});return Us(a),q}catch(q){throw S==="end"&&(S=void 0),q}});let W=async D=>{let U,q=i?.sessionId??e.sessionKey??d,te,E;if(q===void 0&&!c){let Ee=To(a);if(Ee?.sessionId){if(E=Os(p),Ee.actor!==void 0&&E===void 0&&h){let Fs=await Promise.resolve(h()).catch(()=>{});E=Os(Fs??e.jwt)}te=Ee.actor!==void 0&&E!==void 0&&Ee.actor!==E?void 0:Ee.sessionId}}let j=q??te,k=(Ee,Fs)=>ra({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:h,authProvider:e.authProvider,idempotencyKey:Ee,sessionKey:Fs,label:i?.label,...i?.sharedApp?{sharedApp:!0}:{},concurrencyKey:i?.concurrencyKey,priority:e.priority,onAdmission:Je=>{g.reportAdmission(Je),Je.sessionId&&!d&&(d=Je.sessionId,U=Je.sessionId,v&&v.sessionId!==Je.sessionId&&ne({...v,sessionId:Je.sessionId}),b||(e.sessionKey||dl(a,Je.sessionId,p),_.setSessionId(Je.sessionId)))},onRequest:ne}),F;try{F=await k(D,j)}catch(Ee){if(te===void 0||!(Ee instanceof V)||Ee.code!=="session_name_not_yours")throw Ee;console.warn(`[urun] session_name_not_yours: the control plane refused session ${te} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),To(a,E)?.sessionId===te&&Us(a),F=await k(l(),void 0)}let Qe=h?await h()??void 0:e.jwt;if(U&&U!==F.sessionId)throw v&&v.sessionId!==F.sessionId&&ne({...v,sessionId:F.sessionId}),new V(`Gateway contract violation: admission minted session ${U} but allocation completed as ${F.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return d=F.sessionId,v&&v.sessionId!==F.sessionId&&ne({...v,sessionId:F.sessionId}),b||(e.sessionKey||dl(a,F.sessionId,p),_.setSessionId(F.sessionId),_.setArtifactsAuth(Ir({...m,baseUrl:F.baseUrl})),g.setEndsAt(F.endsAt),g.seedRegion(Ks(F.response))),{url:F.wsUrl,sessionId:F.sessionId,jwt:Qe,iceServers:F.response.ice_servers,endsAt:F.endsAt}},$,Y=0,Z=h?async()=>{let D=Y++>0;return await h(D?{forceRefresh:!0,reason:"background"}:void 0)??$}:()=>$,me=()=>{let D=g.connectedUrl;return D?gs(D):void 0};if(g.setConnectionResolver(async()=>{let D=await W(l());return $=D.jwt,D}),g.on("connected",()=>{g.multiplexer&&f.setTarget(g.multiplexer);let D=g.connectedUrl;D&&_.setDocTransport({wsUrl:D,token:Z,resolveServerUrl:me})}),(async D=>{let U;try{U=await W(D)}catch(q){if(b){T({status:"unavailable",cause:q});return}console.error(`[urun] Failed to create session for ${r}:`,q),v&&K(v);let te=q instanceof Error?q:new Error(String(q)),E=q instanceof V?q.httpStatus:void 0,j=q instanceof V?q.code:void 0,k=q instanceof V?q.retryAfterSeconds:void 0;g.reportAllocationFailure(te,E,j,k),T({status:"unavailable",cause:q});return}b||(g.setAuth({jwt:U.jwt,authProvider:e.authProvider,orgId:e.orgId}),g.setConnection({url:U.url,sessionId:U.sessionId,iceServers:U.iceServers}),et()&&await At(),$=U.jwt,_.setDocTransport({wsUrl:U.url,token:Z,resolveServerUrl:me}),await g.connect({app:n,functionName:r,args:o}),_.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(u).catch(D=>{console.error(`[urun] Failed to connect session for ${r}:`,D)}),e.releaseOnLeave!==!1){let D=ks(()=>{if(b=!0,g.leaveLeg())return;if(g.connectedUrl!==null){g.disconnect();return}g.disconnect();let j=v;j?N(j):w=!0});_.onDisconnect(D);let U,q,te=!1,E=()=>{te||(te=!0,U?.(),q?.())};y.then(j=>{j.status!=="ready"||te||(U=Ts(()=>v!==void 0))}),q=_.onPhase(j=>{let k=j?.name;(k==="paused"||k==="error")&&E()}),te&&q(),_.onDisconnect(E)}return _}}})}var Ro="https://api.urun.sh",Co="URUN_DEV";function mg(){if(typeof process>"u")return!1;let n=process.env?.[Co];if(typeof n!="string")return!1;let e=n.trim().toLowerCase();return e==="1"||e==="true"}var it=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function pl(n,e={}){if(!n)throw new it("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=J(e.baseUrl??Ro),s={};e.expiresIn!==void 0&&(s.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(s.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(s.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(s.max_session_s=e.maxSessionS),e.subject!==void 0&&(s.subject=e.subject),e.metadata!==void 0&&(s.metadata=e.metadata),e.sharedApp&&(s.shared_app=!0),(e.dev??mg())&&(s.dev=!0);let i;try{i=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(s)})}catch(p){throw new it(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let o={};try{o=await i.json()}catch{}if(!i.ok){let p=typeof o.message=="string"?o.message:`HTTP ${i.status}`;throw new it(`[urun] client token mint failed: ${p}`,i.status)}let a=typeof o.token=="string"?o.token:"",c=typeof o.org_id=="string"?o.org_id:"",d=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,l=typeof o.expires_in=="number"?o.expires_in:void 0;if(!a)throw new it("[urun] client token mint returned no token (control-plane contract violation)",i.status);let u=Number.isFinite(d)?new Date(d):new Date(Date.now()+(l??60)*1e3);return{token:a,expiresAt:u,orgId:c}}var hl=3e4,fl="stream:",Eo=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let i=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(i.timer),s.error?i.reject(new Error(s.error)):i.resolve(s.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 r=`${fl}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${fl}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),s(new Error(`RPC request "${e}" timed out after ${hl}ms`)))},hl);this._pendingRpc.set(i,{resolve:r,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function ml(n){let r=`${n.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(n.orgId)}`,s=new WebSocket(r);(n.jwt||n.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:n.orgId,jwt:n.jwt,authProvider:n.authProvider,apiKey:n.apiKey}))});let i=new kt(s);return new Eo(s,i)}var gg='video/mp4; codecs="avc1.42E01E"';function gl(n,e){let t=e?.codec??gg,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let s=new MediaSource,i=URL.createObjectURL(s);r.src=i,s.addEventListener("sourceopen",()=>{let p;try{p=s.addSourceBuffer(t)}catch(g){throw g instanceof DOMException&&g.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).`):g}let h=n.getReader();function m(){return p.updating?new Promise(g=>{p.addEventListener("updateend",()=>g(),{once:!0})}):Promise.resolve()}async function f(){try{for(;;){let{done:g,value:_}=await h.read();if(g){await m(),s.readyState==="open"&&s.endOfStream();return}await m();try{p.appendBuffer(_)}catch(v){if(v instanceof DOMException&&v.name==="QuotaExceededError"){let b=p.buffered;if(b.length>0){let w=b.start(b.length-1);p.remove(0,w),await m(),p.appendBuffer(_)}else throw v}else throw v}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}f()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),d=c.getTracks(),l=0,u=d.length;if(u===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let p of d)p.addEventListener("ended",()=>{l++,l>=u&&URL.revokeObjectURL(i)});return c}function _l(n){return n.status.startsWith("pending_")}var St=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)}},br=class extends St{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function _g(n,e,t){let r=t||e||`HTTP ${n}`;return n===401?new br(r,e??"unauthorized"):new St(r,{status:n,code:e??`http_${n}`})}var cn=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 St("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let r=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(r)?r:[]}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),i=await this._resolveToken(),o=await this._fetch(s,e,i);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw _g(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r){let s={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:t,headers:s})}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 br("[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 r=(await e.json()).error;if(r&&typeof r=="object"){let{code:s,message:i}=r;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function vl(n){return new cn(n)}var dn=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 wl(n){let e=[];return n.audio&&e.push("audio"),n.video&&e.push("video"),e.join("+")}function vg(n,e){return e==="audio"?n.getAudioTracks():n.getVideoTracks()}function wg(n,e){let t=n.getTracks();if(t.length===1&&t[0]===e)return n;try{return new MediaStream([e])}catch{return n}}function Po(n,e){for(let t of[...n.lostListeners])try{t(e)}catch{}}var ln=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let r=this.claims.get(e);r&&(this.claims.delete(e),r.released=!0,r.track=null,r.stream=null,Po(r,new Error(`${e} capture claim superseded by a newer claim`)));let s=this.createState(e,t);return this.claims.set(e,s),await this.converge(s),s.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 dn;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(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await t(r)}catch(o){let a=`one-capture getUserMedia(${wl(r)}) failed`,c=o instanceof Error?o.message:String(o);for(let d of[...this.claims.values()])if(this.claims.delete(d.kind),d.released=!0,d!==e){let l=new Error(`${a} \u2014 ${d.kind} capture lost: ${c||o}`);l.cause=o,Po(d,l)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of i){let a=vg(s,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${wl(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw c;Po(o,c);continue}if(o.track=a,o.stream=wg(s,a),o!==e)for(let c of[...o.trackListeners])try{c(a,o.stream)}catch{}}}createState(e,t){let r=this,s={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return s.track},get stream(){return s.stream},update(i){return r.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=i,await r.converge(s),!s.track)throw new Error(`${e} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(e)===s&&r.claims.delete(e),s.track?.stop(),s.track=null,s.stream=null)},onTrack(i){return s.trackListeners.add(i),()=>s.trackListeners.delete(i)},onLost(i){return s.lostListeners.add(i),()=>s.lostListeners.delete(i)}}};return s}},yg=null;function yl(){return yg??=new ln}var Do="input",bl=30;function Sl(n){let e=n.now??Date.now,t=n.field??Do,r=1e3/Math.max(n.hz??30,.001),s=new Set,i=0,o=0,a=0,c=0,d,l=null,u=!1,p=()=>{if(u)return;d=e(),c+=1;let m={keys:[...s],buttons:i,pointer:{x:o,y:a},seq:c,at:d};try{n.awareness.setLocalStateField(t,m)}catch{}},h=()=>{if(u)return;let m=e();if(d===void 0||m-d>=r){l&&(clearTimeout(l),l=null),p();return}if(l)return;let f=Math.max(r-(m-d),0);l=setTimeout(()=>{l=null,p()},f),l.unref?.()};return{keyDown(m){let f=String(m).toLowerCase();s.has(f)||(s.add(f),h())},keyUp(m){let f=String(m).toLowerCase();s.delete(f)&&h()},setButtons(m){let f=Number.isFinite(m)?Number(m):0;f!==i&&(i=f,h())},movePointer(m,f){let g=Number.isFinite(m)?Number(m):0,_=Number.isFinite(f)?Number(f):0;g===0&&_===0||(o+=g,a+=_,h())},heldKeys(){return[...s]},clear(){u||(s.clear(),i=0,l&&(clearTimeout(l),l=null),p())},dispose(){if(u)return;let m=s.size>0||i!==0;s.clear(),i=0,l&&(clearTimeout(l),l=null),m&&p(),u=!0}}}var Rl=1024,Cl=.92,El=262144,Pl=256e3,xo=[.9,.8,.7,.6,.5],kl=.8,bg=8;function Ns(n,e,t){if(!(n>0)||!(e>0))throw new Error(`reference image has no pixels (${n}x${e})`);let r=Math.min(1,t/Math.max(n,e));return{width:Math.max(1,Math.round(n*r)),height:Math.max(1,Math.round(e*r))}}async function Sg(n){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(n,{imageOrientation:"from-image"})}async function Dl(n,e,t){let r=await new Promise(s=>{n.toBlob(s,e,e==="image/jpeg"?t:void 0)});if(!r)throw new Error(`could not encode the reference image as ${e}`);return r}function Tl(n,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${n} -> ${e} bytes`)}async function Io(n,e,t,r,s){let i=document.createElement("canvas");i.width=e,i.height=t;let o=i.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,t)),o.drawImage(n,0,0,e,t),await Dl(i,r,s)}async function kg(n,e,t,r){let{width:s,height:i}=e,o=await Io(n,s,i,t,r);if(o.size<=256e3)return{blob:o,width:s,height:i};if(t==="image/jpeg"){for(let c of xo)if(!(c>=r)&&(o=await Io(n,s,i,t,c),o.size<=256e3))return Tl(`quality ${r} -> ${c}`,o.size),{blob:o,width:s,height:i}}let a=t==="image/jpeg"?xo[xo.length-1]:r;for(let c=0;c<bg;c++)if(s=Math.max(16,Math.round(s*kl)),i=Math.max(16,Math.round(i*kl)),o=await Io(n,s,i,t,a),o.size<=256e3)return Tl(`downscaled to ${s}x${i} @ q${a}`,o.size),{blob:o,width:s,height:i};throw new Error(`this image cannot be sent: even at ${s}x${i} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function xl(n,e){let{maxSize:t=1024,type:r="image/jpeg",quality:s=.92,source:i}=e,o=await Sg(n);try{let a=Ns(o.width,o.height,t),c=await kg(o,a,r,s);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:r,width:c.width,height:c.height,source:i}}finally{o.close()}}function Il(n){let e=n instanceof Error?n.name:"",t=n instanceof Error?n.message:String(n);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 Al(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function Ll(n,e){let t=n.videoWidth,r=n.videoHeight;if(!(t>0)||!(r>0))throw new Error("the camera has not shown a frame yet");let{maxSize:s=1024,type:i="image/jpeg",quality:o=.92}=e??{},a=Ns(t,r,s),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let d=c.getContext("2d");if(!d)throw new Error("could not prepare the reference image (no 2d canvas context)");i==="image/jpeg"&&(d.fillStyle="#fff",d.fillRect(0,0,a.width,a.height)),d.drawImage(n,0,0,a.width,a.height);let l=await Dl(c,i,o);return{bytes:new Uint8Array(await l.arrayBuffer()),type:i,width:a.width,height:a.height,source:"camera"}}var Tg=new Set(["w","a","s","d"]),Sr=(n,e)=>Math.min(e,Math.max(-e,n));function Ml(n={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:s=900,frameRelax:i=.06,maxPan:o=.12,maxLogZoom:a=.22}=n,c=0,d=0,l=0,u=null,p=new Set;return{pointerDelta(h,m){c=Sr(c-h*e,o),d=Sr(d-m*e,o)},keyDown(h){let m=h.toLowerCase();Tg.has(m)&&p.add(m)},keyUp(h){p.delete(h.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let h=1-i;c*=h,d*=h,l*=h},tick(h){if(u===null){u=h;return}let m=Math.max(0,Math.min(100,h-u))/1e3;u=h,p.has("w")&&(l=Sr(l+t*m,a)),p.has("s")&&(l=Sr(l-t*m,a)),p.has("a")&&(c=Sr(c+r*m,o)),p.has("d")&&(c=Sr(c-r*m,o));let f=Math.exp(-m*1e3/s);c*=f,d*=f,l*=f},transform(){return{translateX:c,translateY:d,scale:Math.exp(l)}},isIdentity(h=5e-4){return Math.abs(c)<h&&Math.abs(d)<h&&Math.abs(l)<h},reset(){c=0,d=0,l=0,p.clear()}}}0&&(module.exports={ACTIVATION_COLD_BOOT_AFTER_MS,ACTIVATION_DEGRADED_AFTER_MS,ACTIVATION_HINT_PATH,ACTIVATION_STILL_AFTER_MS,ACTIVITY_DOM_EVENTS,ACTIVITY_FIELD,ACTIVITY_STAMP_MIN_INTERVAL_MS,ActivationMonitor,App,BACKOFF_BASE_MS,BACKOFF_MAX_ATTEMPTS,BACKOFF_MAX_MS,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS,CaptureController,CaptureUnavailableError,ClientTokenError,CreditsClient,CreditsError,CreditsUnauthorizedError,DATA_CHANNEL_MESSAGE_CEILING,DEFAULT_DOC_SYNC_TIMEOUT_MS,DEFAULT_GATEWAY_URL,DEFAULT_PRODUCE_ACK_TIMEOUT_MS,DEFAULT_REFERENCE_JPEG_QUALITY,DEFAULT_REFERENCE_MAX_SIZE,DEFAULT_WHEN_LIVE_TIMEOUT_MS,DERIVED_LEG_SEP,DGRAM_HEADER_BYTES,FOCUS_FIELD,FOREGROUND_COALESCE_MS,FrameReassembler,GENERATION_TICK_EMIT_INTERVAL_MS,GENERATION_TICK_MAX_EXTRAPOLATION_MS,INPUT_PRESENCE_DEFAULT_HZ,INPUT_PRESENCE_FIELD,InvalidDurationError,LEGACY_ACTIVATION_HINT_PATH,PLATFORM_DOC_NAME,PermanentLockedError,PinRequiresActiveTempError,PresenceTracker,ProduceAckTimeoutError,RecordingNotFoundError,RecordingsClient,RecordingsError,RecordingsUnauthorizedError,RequestAbortError,RequestCancelledError,RequestDocSyncError,RequestError,RequestTimeoutError,RetainNotTempError,RuntimeArtifactNotFoundError,RuntimeArtifactsClient,RuntimeArtifactsError,RuntimeArtifactsUnauthorizedError,SIGNALING_PROTOCOL_VERSION,STREAM_END,Session,SessionAllocationError,SessionDirectory,SessionDirectoryError,SessionEndError,SessionEndUnavailableError,SessionFailedError,StreamDirectionConflict,TransportNegotiator,TransportSessionMismatchError,TransportSessionSignaling,URUN_DEV_ENV,USER_ACTIVITY_FIELD,USER_ACTIVITY_MIN_INTERVAL_MS,VISIBILITY_FIELD,WIRE_MESSAGE_BUDGET,WT_CONTROL_FRAME_MAX,WT_DATA_STREAM_VERSION,WebRtcSession,WebTransportSession,WtControlDecoder,WtDataStreamParser,activationHintFrom,cameraCaptureAvailable,captureStillFromVideo,computeBackoffDelay,consumeWtDataStreams,createActivityTracker,createCameraWarp,createClientToken,createCreditsClient,createInputPresencePublisher,createRecordingsClient,createRuntimeArtifactsClient,createStore,decodeStreamEnvelope,derivedLegName,derivedLegRole,describeSessionFailure,describeSessionPhase,encodeStreamEnvelope,encodeWtControlFrame,fitWithin,isDurationString,isPausedPhase,isPendingRecording,isRetryableSessionError,isWakingPhase,mediaRecorderChunkSource,normalizeReferenceImage,normalizeRetention,observeLeaveConfirm,observePageLifecycle,observePageTeardown,parseDgramHeader,prewake,referenceImageErrorMessage,releaseSessionBeacon,sessionDirectory,sessionFailureFromMediaError,sharedCaptureController,videoStream,watchGenerationTick,whenLive,writeDgramHeader});
35
+ `)}var As=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=Am(e)?this.bridgedTrack(e):e,!t))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(t)}catch(r){this.die(`replaceTrack: ${r instanceof Error?r.message:String(r)}`);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 r;try{r=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let s=this.sendPc.addTrack(e);this.sender=s,this.currentTrack=e,this.wireTrackLiveness(e);let i=t.RTCRtpScriptTransform;if(s.transform=new i(r,{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=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toRecv.push(r.candidate),this.flushCandidates())},this.recvPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toSend.push(r.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(r=>this.die(`loopback renegotiate: ${r instanceof Error?r.message:String(r)}`))},this.recvPc.ontrack=r=>{let s=r.transceiver?.mid??null;s!==null&&s===this.renderMidOf()&&this.renderRemoteCb?.(r.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 r=await e.createOffer();r.sdp=Yd(r.sdp??""),await e.setLocalDescription(r),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:r.sdp});let s=await t.createAnswer();s.sdp=Yd(s.sdp??""),await t.setLocalDescription(s),await e.setRemoteDescription(t.localDescription??{type:"answer",sdp:s.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 r=t.context.createMediaStreamDestination();t.connect(r);let s=r.stream.getAudioTracks()[0]??null;return s?(this.nodeBridge={node:t,dest:r},s):(this.die("AudioNode bridge produced no audio track"),null)}catch(r){return this.die(`AudioNode bridge: ${r instanceof Error?r.message:String(r)}`),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([Im],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=t=>{let r=t.data;r?.type==="enc"&&r.payload instanceof ArrayBuffer?this.onEncodedFrame(r.rtpTimestamp??0,new Uint8Array(r.payload)):r?.type==="err"&&this.die(`transform: ${r.detail??"unknown"}`)},e.onerror=t=>this.die(`transform worker: ${t.message||"error"}`),this.worker=e,e}onEncodedFrame(e,t){if(this.stopped)return;let r=ho(this.frameSeq,e,t,this.sink.maxDatagramSize()||on);if(r===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 s of r)this.sink.send(s);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 Am(n){let e=n;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var Lm=9e4,Mm="avc1.42E01F",Om=60,Um=3,Nm=1e4;function Fm(n){return Math.round(n*(Lm/1e6))%2**32>>>0}var Ls=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 r=globalThis.MediaStreamTrackProcessor;if(typeof r!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let s=++this.generation,i=new r({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,i.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&s===this.generation;){let{value:a,done:c}=await i.read();if(c)break;if(a){if(o||this.stopped||s!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&s===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 i=globalThis.VideoEncoder;if(typeof i!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new i({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)})),this.encoderDims=t,this.encoder.configure({codec:Mm,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 s=this.keyframeWanted||this.framesSinceKeyframe>=Om;this.keyframeWanted=!1,this.framesSinceKeyframe=s?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:s})}catch(i){this.onEncoderError(i instanceof Error?i:new Error(String(i)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=ho(this.frameSeq,Fm(e.timestamp),t,this.sink.maxDatagramSize()||on,{lane:zd,keyframe:e.type==="key"});if(r===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 s of r)this.sink.send(s);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(r=>t-r<Nm),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=Um){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 Wm(n){return n.byteLength>=2&&n[0]===1&&n[1]===3}var Ms=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 r=new TextEncoder().encode(e);if(r.byteLength===0||r.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${r.byteLength})`));let s=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let i=this.streams.get(e);if(!i){let a=await this.transport.openUniStream(),c=new Uint8Array(2+r.byteLength);c[0]=1,c[1]=r.byteLength,c.set(r,2),await a.write(c),i={writer:a},this.streams.set(e,i)}let o=new Uint8Array(4+t.byteLength);new DataView(o.buffer).setUint32(0,t.byteLength,!0),o.set(t,4),await i.writer.write(o),Wm(t)&&(this.streams.delete(e),await i.writer.close().catch(()=>{}))}catch(i){throw this.die(i instanceof Error?i.message:String(i)),i}});return this.chain=s.catch(()=>{}),s}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 Qd=250,$m=25,jm=2e3,qm=15e3,Bm=1e3,Hm=45e3,Vm=5e3,zm={llm:!0},Gm=500,Jd=10,Km=2,Ym=2,fo=2,mr=class n{constructor(e,t,r,s,i,o,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=s;this.audioUplink=i;this.videoUplink=o;this.dataUplink=a;this.firstMedia=new Promise((c,d)=>{this.firstFrameResolve=c,this.firstFrameReject=d}),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 fr({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,r=t!==void 0&&t!=="";this.hasVideoLane=r,r&&co(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(l=>({algorithm:"sha-256",value:Uint8Array.from(atob(l),u=>u.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let s=await this.wt.createBidirectionalStream();this.writer=s.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let i=s.readable.getReader(),o=new pr,a=[],c=await this.readControl(i,o,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");let d=c;if(this.lastInboundControlAt=performance.now(),typeof d.pingIntervalMs=="number"&&d.pingIntervalMs>0?this.advertisedPingIntervalMs=d.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")),r&&(co(d.codec,"hello-ack"),this.initDecoder(d.codec,d.width,d.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let l={setSource:p=>{this.renderSource=p,this.audioUplinkLane?.setRenderSource?.(p)},onRemote:p=>{this.renderRemoteCb=p}},u=new Is(this.offer.audio,{...this.audioLane,renderHop:l});try{u.start(),this.audioPlayout=u}catch(p){console.warn(`[urun] WT audio lane failed to start (${p instanceof Error?p.message:String(p)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),u.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 l=this.wt.createUnidirectionalStream?.bind(this.wt);if(!l)throw new Error("WebTransport uni streams are not creatable in this environment");let u=new Ms({openUniStream:async()=>(await l()).getWriter()});u.onDead(p=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(p,u)}),this.dataUplinkSender=u,this.dataUplink.onUplink(u)}catch(l){let u=l instanceof Error?l.message:String(l);console.warn(`[urun] WT data uplink failed to engage (${u}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(u)}this.controlLoop(i,o,a).catch(l=>this.die(`control loop: ${l}`)),this.datagramLoop().catch(l=>this.die(`datagram loop: ${l}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),Gm)),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(l=>{this.closedReason=`connection error: ${l}`,this.die(`connection error: ${l}`)})}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 ${Qd}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??qm},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Bm))}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,r=typeof e.ur=="number"?e.ur:null;if(t===null&&r===null)return;this.gatewayExposesCounters=!0;let s=this.audioDgramsReceived,i=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:r,recvDownlink:s,sentUplink:i},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,c=r!==null&&o.ur!==null?r-o.ur:null,d=s-o.recvDownlink,l=i-o.sentUplink,u="none";if(a!==null&&a>=Jd&&d<=0?u="downlink":c!==null&&l>=Jd&&c<=0&&(u="uplink"),u==="none"){this.severedStreak="none",this.observePlayoutProgress(d,t);return}if(this.severedStreak!==u){this.severedStreak=u;return}this.severedStreak="none";let p=u==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${l} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+p+` (gateway flow counters ds=${t} ur=${r}, client received=${s} accepted=${i}, confirmed on ${Km} 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 r=this.audioPlayout;if(!r){this.playoutScheduledSeen=null;return}let s=r.playoutProgress(),i=s.surfaced;if(this.playoutScheduledSeen!==null&&s.scheduled>this.playoutScheduledSeen&&i){this.playoutScheduledSeen=s.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=s.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<Ym)){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=${s.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{r.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=fo}return}this.playoutStallStreak<fo||(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=${s.scheduled} on ${fo} 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 r=performance.now(),s=this.audioLaneLastArrivalAt===null?null:r-this.audioLaneLastArrivalAt,i=this.lastInboundControlAt===null?null:r-this.lastInboundControlAt,o=s===null&&i===null?!0:(s===null||s>=e.stallMs)&&(i===null||i>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&i!==null&&i>=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(i/1e3)}s while the path reports alive (${t.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}let c=!!(this.offer.audio&&this.audioLane),d=this.lastInboundDataAt===null?null:r-this.lastInboundDataAt,l=s!==null?s:this.firstInboundDataAt===null?null:r-this.firstInboundDataAt,u=l!==null&&l>=e.stallMs;if(c&&u&&d!==null&&d<=Vm&&this.gatewayPings>0){this.die(`media-starved leg: no audio datagram for ${Math.round((l??0)/1e3)}s while the data lane delivered a frame ${Math.round((d??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&&i!==null&&i>=Hm&&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(i/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 s=this.audioUplinkLane;s?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e,s??void 0)}if(this.videoUplinkLane!==null||this.videoUplinkRetry!==null){let s=this.videoUplinkLane;s?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e,s??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:(r,s)=>{if(zm[r]===!0){let i=performance.now();this.firstInboundDataAt===null&&(this.firstInboundDataAt=i),this.lastInboundDataAt=i}e.onData(r,s)},onLaneError:r=>e.onLaneError(r)};this.dataLaneSink=t,xs(this.wt.incomingUnidirectionalStreams,t).catch(r=>{this.die(`data lane: ${r instanceof Error?r.message:String(r)}`)})}initDecoder(e,t,r){let s=globalThis.VideoDecoder;if(typeof s!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let i=this.canvas.getContext("2d");if(!i)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r};let o=new s({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,i.drawImage(a,0,0),a.close()},error:a=>this.onDecoderError(a)});o.configure({codec:e,...t>0&&r>0?{codedWidth:t,codedHeight:r}:{},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(r){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${r instanceof Error?r.message:String(r)}`));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,s=>this.onUplinkSendError(s))}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 r=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(s=>r-s<jm),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<$m)&&(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:r=>this.uplinkSend(r,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??on}}engageAudioUplink(){let e=new As(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 Ls(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(r){let s=r instanceof Error?r.message:String(r);console.warn(`[urun] WT ${t} uplink failed to engage (${s}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,s)}}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,r){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let s=e==="audio"?"mic":"video",i=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,a=i?.builtAt!=null&&Date.now()-i.builtAt>=n.UPLINK_LANE_HEALTHY_MS?1:(i?.count??0)+1;if(a>n.UPLINK_LANE_RETRY_MAX){console.error(`[urun] WT ${s} uplink lane dead (${t}) \u2014 ${n.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 ${n.UPLINK_LANE_RETRY_MAX} recovery attempts: ${t}`,r);return}console.warn(`[urun] WT ${s} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${a}/${n.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let c={count:a,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=c:this.videoUplinkRetry=c,c.timer=setTimeout(()=>{c.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},n.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,t,r){e==="audio"?this.audioUplink.onUplinkLost(t,r):this.videoUplink.onUplinkLost(t,r)}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:r}=await e.read();if(r)break;if(!t)continue;if(t.byteLength>=fe&&t[11]===Ps){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let s=performance.now();if(this.lastArrivalTs>0){let i=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(i-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=s,this.reassembler.push(t)}}decodeFrame(e,t,r){let s=globalThis.EncodedVideoChunk;if(typeof s=="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 s({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(Es(e)),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),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 r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async readControl(e,t,r=[]){for(;;){let s=r.shift();if(s)return s;let{value:i,done:o}=await e.read();if(o)return null;i&&r.push(...t.push(i))}}async controlLoop(e,t,r){for(;!this.stopped;){let s=await this.readControl(e,t,r);if(!s)break;let i=s;if(this.lastInboundControlAt=performance.now(),i.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(Vd(s.raw,"pong"))}catch{}}(i.t==="ping"||i.t==="pong")&&this.observeFlowCounters(i),i.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),r=(t-e)/1e3;e=t;let s=this.reassembler.drainWindow(),i=s.delivered+s.abandoned;this.lastStats={recvBps:r>0?s.bytes*8/r:0,lossPct:i>0?100*s.abandoned/i:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Qd)}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 Xd=2500,Zd=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Qm=1e4,gr=class n{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}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",r=typeof e.VideoDecoder=="function",s=this.opts.allowWebTransport??!0,i={webtransport:t&&r&&s,webcodecs:r,codecs:Zd,wtData:t&&r&&s&&this.opts.dataLane!==void 0,wtAudio:t&&r&&s&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&s&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:t&&r&&s&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&r&&s&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:i}),this.noteOfferedWtHost();let o=i.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,c=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(c||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),i.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let d=null;try{return d=this.createWebTransportSession(),await go(d.start(),this.opts.quicDeadlineMs??Xd,"quic connect deadline"),this.wtDialedHost=mo(this.offer.webtransport?.url)??this.wtDialedHost,this.engageQuicDataLane(d,i.wtData===!0),this.session=d,c&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(l){if(console.warn(`[urun] WT dial failed (${an(l)}) \u2014 dialed ${el(this.offer.webtransport?.url)}`),d?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let u=String(l instanceof Error?l.message:l);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${u}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(u),l}console.warn("[urun] webtransport failed, falling back to webrtc:",l),this.proceedWebRtcDial(`wt failed: ${String(l instanceof Error?l.message:l)}`),this.notifyEstablished("webrtc",String(l instanceof Error?l.message:l))}}if(this.opts.allowWebRtcFallback===!1){let d=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${d} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(d),new Error(`[urun] WT required but unavailable: ${d}`)}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=mo(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}`+(Jm(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 r=this.session,s=this.opts.dataLane!==void 0,i=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",c=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:Zd,wtData:s,wtAudio:i,wtAudioUp:o,wtVideoUp:a,wtDataUp:c}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let d=this.createWebTransportSession();try{await go(d.start(),this.opts.quicDeadlineMs??Xd,"quic connect deadline")}catch(l){throw console.warn(`[urun] WT dial failed (${an(l)}) \u2014 dialed ${el(this.offer.webtransport?.url)}`),d.stop().catch(()=>{}),l}if(this.wtDialedHost=mo(this.offer.webtransport?.url)??this.wtDialedHost,this.session!==r)return d.stop().catch(()=>{}),null;try{this.engageQuicDataLane(d,s)}catch(l){throw d.stop().catch(()=>{}),l}if(this.disconnected)return d.stop().catch(()=>{}),null;this.session=d;{let l=this.offer.webtransport;l&&(this.opts.audioLane===void 0||l.audio!==void 0)&&(this.opts.audioUplink===void 0||l.audioUp===!0)&&(this.opts.videoUplink===void 0||l.videoUp===!0)&&(this.opts.dataLane===void 0||l.data===!0)&&(this.opts.dataUplink===void 0||l.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),d}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let r=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:(s,i)=>r.onData(s,i),onLaneError:s=>r.onLaneError(s)}),r.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 mr(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 r=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),r){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,r)})}redialWtAfterDeath(e,t=!1){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures>=n.WT_REDIAL_MAX){if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT re-dial failed ${n.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 ${n.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 r=this.wtRedialFailures+1,s=_o(n.WT_REDIAL_BASE_MS,r,n.WT_REDIAL_CAP_MS,r===1&&t?0:void 0);console.warn(`[urun] WT re-dial attempt ${r} scheduled in ${Math.round(s)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},s)}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}/${n.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(t){let r=an(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${n.WT_REDIAL_MAX} failed (${r}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${r}`)}}}lateWebRtcFailover(e,t,r){this.disconnected||(async()=>{let s=this.createWebRtc();try{let i=await go(this.startWebRtcOn(s),this.opts.webRtcFailoverDeadlineMs??Qm,"webrtc failover produced no media transport");if(this.session!==e){i.stop().catch(()=>{});return}this.session=i,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(i){if(s.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=i instanceof Error?i.message:String(i),a=r?`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 an(n){if(n instanceof Error)return n.message;if(typeof n=="string")return n;if(n&&typeof n=="object"){try{let e=JSON.stringify(n);if(e!==void 0&&e!=="{}")return e}catch{}return n.constructor?.name??Object.prototype.toString.call(n).slice(8,-1)}return String(n)}function mo(n){if(n)try{return new URL(n).host}catch{return}}function el(n){if(!n)return"(no offer url)";try{let e=new URL(n);return e.searchParams.delete("token"),e.toString()}catch{return n.replace(/[?&]token=[^&\s]*/g,"")}}function Jm(n){if(!n)return!1;let e=n.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 _o(n,e,t,r){if(r!==void 0)return r;let s=Math.min(n*2**Math.max(0,e-2),t);return Math.round(s*(.75+Math.random()*.5))}function go(n,e,t){return new Promise((r,s)=>{let i=setTimeout(()=>s(new Error(t)),e);n.then(o=>{clearTimeout(i),r(o)},o=>{clearTimeout(i),s(o)})})}var Xm=1e4,_r=class{constructor(e,t=Xm){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let r=ar();return new Promise((s,i)=>{let o=setTimeout(()=>{a(),i(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(o),a(),c.error){i(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:d,requestId:l,...u}=c;s(u)});this.carrier.sendSignal({type:e,requestId:r,...t})||(clearTimeout(o),a(),i(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(r=>{r.type===e&&t(r)})}};var Zm="video",vr=class{constructor(e,t=Zm){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),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 r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}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 tl(n){let e=n;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var eg="video";var tg=45e3;async function rg(n,e,t){let s=e?.current()?.name??null;if(s==="live")return"live";if(s==="error")return"gone";if(s==="idle"||s==="connecting")return"live";if(!e)return"unconfirmed";let i=e,o=t.runtimeWaitCapMs??tg;return new Promise(a=>{let c=!1,d,l=null,u=null,p=!1,h=_=>{c||(c=!0,g(),u!==null&&(clearTimeout(u),u=null),d?.(),a(_))};u=setTimeout(()=>{if(p||c||t.isDisposed())return;p=!0;let _=i.current();n.emitDiagnostic({level:"info",kind:"runtime-pending",message:`waiting for a runtime to pick up session ${t.sessionId} (server status: ${_?.reason??_?.name??"unknown"}) \u2014 media negotiation starts once the runtime is live; this is not a transport failure`})},2e3);let f=()=>{l===null&&!c&&(l=setTimeout(()=>h("unconfirmed"),o))},g=()=>{l!==null&&(clearTimeout(l),l=null)};d=e.subscribe(_=>{let v=_?.name;if(v==="live")return h("live");if(v==="error")return h("gone");g(),Be(v)||f()}),Be(s)||f()})}function rl(n,e,t){let r=globalThis,s=r.document;if(!(typeof s?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=n.holdWebRtcDial?.(),a=s.createElement("canvas"),c=!1,d=null,l=!1,u=()=>{if(d){for(let P of d.getVideoTracks())try{P.stop()}catch{}d=null}l&&(l=!1,t.onOverrideTrack(null))},p=new gr(new _r(n),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new vr(n,t.streamName??eg)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(P,N)=>n.dispatchQuicStreamData(P,N),onQuicLane:()=>n.markStreamDataLaneQuic(),onQuicLaneLost:P=>n.quicStreamDataLaneLost(P),onLaneError:P=>n.raiseQuicStreamDataError(P)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,ctx:t.audioPlayout?.audioContext,onTrack:P=>{c||(P&&n.noteQuicMediaFlowing?.(),t.onOverrideAudioTrack(P))}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>w(),onMediaTransportLost:P=>{c||(u(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(P),w())},onTransportChange:(P,N)=>{c||(P==="webrtc"&&(u(),w()),t.onTransportChange?.(P,N))}}),h=n.onWtOnlyLegDeath?.(P=>p.failCurrentWtLeg(P)),m=null,f=()=>{m!==null&&(clearInterval(m),m=null)},g=t.wtRetryBaseMs??2e3,_=t.wtRetryCapMs??3e4,v=null,b=0,w=()=>{if(c||v!==null||p.activeTransport==="webtransport")return;let P=_o(g,b+2,_);v=setTimeout(()=>{v=null,b+=1,p.retryWebTransport().then(N=>{if(c){N&&p.disconnect().catch(()=>{});return}if(N)return console.debug(`[urun] webtransport upgraded in background (retry ${b})`),b=0,T(N);w()}).catch(N=>{c||(console.debug(`[urun] webtransport background retry ${b} failed: `+an(N)),w())})},P)},S=()=>{v!==null&&(clearTimeout(v),v=null)},T=async P=>{if(c||P.kind!=="webtransport")return;let N=t.pathHealthProbeMs??1e4;f();let K=!1;m=setInterval(()=>{if(c||p.activeTransport!=="webtransport")return;let W=tl(P);if(!W){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)"),f();return}let $=W.pathLiveness();if(!$.alive){let Y=p.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${$.evidence}`+(Y?" \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"),f(),W.fail(`path health: ${$.evidence}`);return}if(!K){if(K=!0,p.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${N}ms \u2014 the QUIC PATH IS HEALTHY (${$.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 ${N}ms \u2014 no media datagrams reached this client (path healthy: ${$.evidence}); webrtc track remains authoritative`)}},N);try{await P.firstMedia}catch(W){f(),console.debug("[urun] webtransport ended before any media flowed:",W);return}if(f(),c||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;d=a.captureStream();let ne=d.getVideoTracks()[0];ne&&(l=!0,t.onOverrideTrack(ne))},y=!1;return(async()=>{let P=await rg(n,t.runtimePhase,{sessionId:e,runtimeWaitCapMs:t.runtimeWaitCapMs,isDisposed:()=>c});if(c)return;if(P==="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}y=!0;let N=await p.connect();if(c){p.disconnect().catch(()=>{});return}await T(N)})().catch(P=>{if(f(),c){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",P);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",P),w();return}o?.proceed(`negotiation unavailable: ${P instanceof Error?P.message:String(P)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",P),w()}),{activeTransport:()=>p.activeTransport,mediaTransportAttempted:()=>y,watchDownlinkStall(P){p.watchDownlinkStall(P)},dispose(){c=!0,h?.(),f(),S(),u(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var ng=new Set;function yo(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var sg="rpc",ig="$presence",bo=3e4,nl=3e4,og="rpc-resp";function ag(n){return`${og}:${n}`}function vo(){return ar()}function cg(n){if(n&&typeof n=="object"){let e=n.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof n=="string"?n:JSON.stringify(n)}}function dg(n,e,t,r,s,i,o,a,c,d){let l=[],u=null,p=!1,h=null,m=!1,f,g,_=new Promise((k,F)=>{f=k,g=F});_.catch(()=>{});let v=o(),b=null,w=null,S=null,T=null,y=null,P=null,N=!0,K=()=>{S&&(clearTimeout(S),S=null),T&&(T(),T=null)},ne=()=>{y&&(clearTimeout(y),y=null),P&&(P(),P=null)},W=!1,$=()=>{W||!m||(W=!0,n.set({rpc:{[e]:null}}))},Y=()=>{N=!1,K(),ne(),b?.(),b=null,w?.(),w=null,a?.removeEventListener("abort",U),v.dispose(),$()},Z=()=>{if(u){if(l.length>0){let k=u;u=null,k.resolve({value:l.shift(),done:!1})}else if(h!==null){let k=u;u=null,k.reject(h)}else if(p){let k=u;u=null,k.resolve({value:void 0,done:!0})}}},me=k=>{p||(l.push(k),Z())},ee=k=>{p||(h=k,p=!0,g(k),Y(),Z())},D=k=>{p||(p=!0,f(k),Y(),Z())},U=()=>{let k=a?.reason;ee(k instanceof Pe?k:new ot(e))},q=k=>{if(!(p||!k||typeof k!="object"))switch(ne(),$(),k.t){case"delta":typeof k.delta=="string"&&me(k.delta);break;case"response":D(k.body);break;case"error":{let{message:F,code:Qe}=cg(k.body);ee(new Pe(F,{requestId:e,code:k.code??Qe}));break}}},te=()=>{let k=v.messages()[Symbol.asyncIterator]();b=()=>{k.return?.(void 0)};let F=()=>{N&&k.next().then(Qe=>{if(N){if(Qe.done){p||D(void 0);return}q(Qe.value),F()}},Qe=>{N&&ee(Qe)})};F()},E=()=>{if(!m){if(m=!0,a){if(a.aborted){ee(new ot(e));return}a.addEventListener("abort",U,{once:!0})}w=c?.(k=>ee(k))??null,te(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:i}}}),d&&d>0&&!n.synced&&(S=setTimeout(()=>{S=null,!p&&!n.synced&&ee(new Ct(d,e))},d),T=n.onSynced(()=>K())),P=n.onSynced(()=>{P=null,!(p||W||y)&&(y=setTimeout(()=>{y=null,!(p||W)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(nl/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).`)},nl))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(E(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(h!==null){let k=h;return h=null,Promise.reject(k)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((k,F)=>{u={resolve:k,reject:F}})},return(){return p||(p=!0,f(void 0),Y()),Promise.resolve({value:void 0,done:!0})},throw(k){return p||(p=!0,g(k),Y()),Promise.reject(k)}}}},body:_,start:E}}function sl(n){if(n&&typeof n=="object"){let{epoch:e,by:t}=n,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function lg(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:i,br:o}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let c=sl(i);c&&(a.rt=c);let d=sl(o);return d&&(a.br=d),a}var wo=class{constructor(e,t,r,s,i){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;this._onActivity=i;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],r=null,s=!1,i=null,o={push(c){if(!s)if(r){let d=r;r=null,d.resolve({value:c,done:!1})}else t.push(c)},end(){if(s=!0,r){let c=r;r=null,c.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{s=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(c=>{if(!(c===null||s)&&(i=e._streamConsumeUnavailableError(c),a(),r)){let d=r;r=null,d.reject(i)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):i?Promise.reject(i):s?Promise.resolve({value:void 0,done:!0}):new Promise((c,d)=>{r={resolve:c,reject:d}})},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 r=e??this._transport.getTrackByName(this._name)??this._track,s=this._handlers.get("track");if(s)for(let i of s)i(r)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=lg(t,this._name),s=r?.br;if(s?.by==="runtime")throw new Et(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};r?.rt&&(i.rt=r.rt);let o=r?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}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??Rs;return Hd(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.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 r of t)r(e)}},wr=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new ms;_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,r,s,i,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=ld(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Ss(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=bs({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new ur({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(ig).awareness.setLocalState({role:"client"}),this._activation=new It({onPhase:a=>this.onPhase(a),hint:()=>this.doc(fn).get(mn)??this.doc("control").get(gn),onData:(a,c)=>this._streamData.onData(a,c)})}_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 r=await oa({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new Tt,o=new lr({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,i,o,yo(t),Ir({...t,baseUrl:r.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),o.setEndsAt(r.endsAt),et()&&await At();let c=t.getAccessToken,d=c?async()=>await c()??s:s;return a.setDocTransport({wsUrl:r.wsUrl,token:d}),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 hn(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=ws(this.doc("control"),r=>{for(let s of Array.from(this._generationTickHandlers))try{s(r)}catch(i){console.warn("[urun] generationTick handler failed:",i)}})),()=>{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 ut(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,s)=>t.retain(r,s),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new tt(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new tt(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 r of this._docs.values())r.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new wo(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 vs(e,this._sessionId,ng.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Ud(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=gs(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",s=`${t}\0${r}\0${this._sessionId}`;s!==this._docEndpointKey&&(this._docEndpointKey=s,this.connectDocs(Md({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 r=vo(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let c=t.timeout;i=setTimeout(()=>s.abort(new Rt(c,r)),c)}let o=this._consumeResponse(r,e,!1,s.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{i&&clearTimeout(i),a?.()})}_consumeResponse(e,t,r,s,i){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(sg),a=ag(e);return dg(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??bo)}requestStream(e,t={}){let r=vo();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=vo(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.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=rl(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 Ue)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new Ue);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 s of t)try{s()}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 r=Array.from(this._activeRequests);this._activeRequests.clear();for(let s of r)try{s(new Dt)}catch{}for(let s of this._docs.values())s.dispose();this._docs.clear();for(let s of this._streams.values())s.dispose();this._streams.clear(),this._transport.disconnect(e)}};function il(n){return`urun:session:v2:${n.orgId}:${n.app}:${n.functionName}`}function So(){try{return globalThis.sessionStorage??null}catch{return null}}var ko=new Map;function Os(n){if(!n)return;let e=n.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=JSON.parse(atob(t+"=".repeat((4-t.length%4)%4)));return typeof r?.sub=="string"&&r.sub.length>0?r.sub:void 0}catch{return}}function ug(n,e){return n!==void 0&&e!==void 0&&n!==e}function To(n,e){let t=So(),r=null;if(t)try{let i=t.getItem(n);if(i){let o=JSON.parse(i);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(r={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{r=null}let s=ko.get(n)??r??null;return!s||ug(s.actor,e)?null:s}function ol(n,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};ko.set(n,t);let r=So();if(r)try{r.setItem(n,JSON.stringify(t))}catch{}}function Us(n){ko.delete(n);let e=So();if(e)try{e.removeItem(n)}catch{}}var al=new Set(["paused","acquiring","live"]),pg=new Set(["24h","keep"]);function cl(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}function hg(n){if(typeof n?.id!="string"||n.id.length===0)throw new ve("[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 n.state!="string"||!al.has(n.state))throw new ve(`[urun] session ${n.id} reported an unrecognized state ${JSON.stringify(n.state)} \u2014 this @urun-sh/core build knows only ${[...al].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 n.recordings_expired=="boolean"?e=n.recordings_expired:console.warn(`[urun] session ${n.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:n.id,label:typeof n.label=="string"&&n.label.length>0?n.label:null,state:n.state,app:typeof n.app=="string"?n.app:"",functionName:typeof n.function=="string"?n.function:"",createdAt:cl(n.created_at),lastActiveAt:cl(n.last_active_at),archived:n.archived===!0,preview:typeof n.preview=="string"&&n.preview.length>0?n.preview:null,recordingsExpired:e,retention:pg.has(n.retention)?n.retention:(n.retention!==void 0&&console.warn(`[urun] session ${n.id} reported an unrecognized retention ${JSON.stringify(n.retention)} \u2014 defaulting to '24h'`),"24h")}}var yr=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:r}=await na({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(hg),nextCursor:r}}async end(e){await sa({...this._request,sessionId:e})}async archive(e){await Gs({...this._request,sessionId:e,archived:!0})}async unarchive(e){await Gs({...this._request,sessionId:e,archived:!1})}async setName(e,t,r={}){await ia({...this._request,sessionId:e,name:t,source:r.source})}};function dl(n,e,t){let r=Os(t);ol(n,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}var fg=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function ll(n,e){return new yr(n,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function ul(n,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,r){if(!(fg.has(r)||typeof r!="string"))return(s,i)=>{let o=s??{},a=il({orgId:e.orgId,app:n,functionName:r}),c=!i?.sessionId&&!e.sessionKey&&!!i?.label,d,l=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,u=l(),p=e.jwt,h=e.getAccessToken?async D=>{let U=await e.getAccessToken(D);return U&&(p=U),U}:void 0,m={...e,getAccessToken:h},f=new Tt,g=new lr({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:u,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),_=new wr(u,f,g,yo(m),Ir(m),{activity:i?.activity}),v,b=!1,w=!1,S,T,y=new Promise(D=>{T=D}),P,N=D=>{D.sessionId||S||(S="teardown",P="ticket",Pr({baseUrl:D.baseUrl,requestId:D.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider}))},K=D=>{S||D.sessionId||(S="abandon",Pr({baseUrl:D.baseUrl,requestId:D.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider,reason:"client_abandoned"}))},ne=D=>{let U=D.sessionId||!d?D:{...D,sessionId:d};v=U,T({status:"ready",handle:U}),(w||S==="teardown")&&N(U)};_.setEndHandler(async()=>{let D=v?{status:"ready",handle:v}:await y;if(D.status==="unavailable")throw new Ue("[urun] session allocation failed before a releasable request was created",{cause:D.cause});let U=v??D.handle;return Us(a),S==="teardown"?U.sessionId?{status:"paused",sessionId:U.sessionId,reason:"client_ended"}:{status:"canceled",requestId:U.requestId}:(S="end",U.sessionId?Vs({baseUrl:U.baseUrl,sessionId:U.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:h,authProvider:e.authProvider}):Hs({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:h,authProvider:e.authProvider}))}),_.setCancelHandler(async()=>{let D=v?{status:"ready",handle:v}:await y;if(D.status==="unavailable")throw new Ue("[urun] session allocation failed before a cancellable request was created",{cause:D.cause});let U=v??D.handle;if(U.sessionId)throw new ae(`[urun] cancel() is for a queued admission request, but this call already has session ${U.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:U.sessionId,code:"cancel_on_live_session"});S="end";try{let q=await Hs({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:h,authProvider:e.authProvider});return Us(a),q}catch(q){throw S==="end"&&(S=void 0),q}});let W=async D=>{let U,q=i?.sessionId??e.sessionKey??d,te,E;if(q===void 0&&!c){let Ee=To(a);if(Ee?.sessionId){if(E=Os(p),Ee.actor!==void 0&&E===void 0&&h){let Fs=await Promise.resolve(h()).catch(()=>{});E=Os(Fs??e.jwt)}te=Ee.actor!==void 0&&E!==void 0&&Ee.actor!==E?void 0:Ee.sessionId}}let j=q??te,k=(Ee,Fs)=>ra({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:h,authProvider:e.authProvider,idempotencyKey:Ee,sessionKey:Fs,label:i?.label,...i?.sharedApp?{sharedApp:!0}:{},concurrencyKey:i?.concurrencyKey,priority:e.priority,onAdmission:Je=>{g.reportAdmission(Je),Je.sessionId&&!d&&(d=Je.sessionId,U=Je.sessionId,v&&v.sessionId!==Je.sessionId&&ne({...v,sessionId:Je.sessionId}),b||(e.sessionKey||dl(a,Je.sessionId,p),_.setSessionId(Je.sessionId)))},onRequest:ne}),F;try{F=await k(D,j)}catch(Ee){if(te===void 0||!(Ee instanceof V)||Ee.code!=="session_name_not_yours")throw Ee;console.warn(`[urun] session_name_not_yours: the control plane refused session ${te} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),To(a,E)?.sessionId===te&&Us(a),F=await k(l(),void 0)}let Qe=h?await h()??void 0:e.jwt;if(U&&U!==F.sessionId)throw v&&v.sessionId!==F.sessionId&&ne({...v,sessionId:F.sessionId}),new V(`Gateway contract violation: admission minted session ${U} but allocation completed as ${F.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return d=F.sessionId,v&&v.sessionId!==F.sessionId&&ne({...v,sessionId:F.sessionId}),b||(e.sessionKey||dl(a,F.sessionId,p),_.setSessionId(F.sessionId),_.setArtifactsAuth(Ir({...m,baseUrl:F.baseUrl})),g.setEndsAt(F.endsAt),g.seedRegion(Ks(F.response))),{url:F.wsUrl,sessionId:F.sessionId,jwt:Qe,iceServers:F.response.ice_servers,endsAt:F.endsAt}},$,Y=0,Z=h?async()=>{let D=Y++>0;return await h(D?{forceRefresh:!0,reason:"background"}:void 0)??$}:()=>$,me=()=>{let D=g.connectedUrl;return D?gs(D):void 0};if(g.setConnectionResolver(async()=>{let D=await W(l());return $=D.jwt,D}),g.on("connected",()=>{g.multiplexer&&f.setTarget(g.multiplexer);let D=g.connectedUrl;D&&_.setDocTransport({wsUrl:D,token:Z,resolveServerUrl:me})}),(async D=>{let U;try{U=await W(D)}catch(q){if(b){T({status:"unavailable",cause:q});return}console.error(`[urun] Failed to create session for ${r}:`,q),v&&K(v);let te=q instanceof Error?q:new Error(String(q)),E=q instanceof V?q.httpStatus:void 0,j=q instanceof V?q.code:void 0,k=q instanceof V?q.retryAfterSeconds:void 0;g.reportAllocationFailure(te,E,j,k),T({status:"unavailable",cause:q});return}b||(g.setAuth({jwt:U.jwt,authProvider:e.authProvider,orgId:e.orgId}),g.setConnection({url:U.url,sessionId:U.sessionId,iceServers:U.iceServers}),et()&&await At(),$=U.jwt,_.setDocTransport({wsUrl:U.url,token:Z,resolveServerUrl:me}),await g.connect({app:n,functionName:r,args:o}),_.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(u).catch(D=>{console.error(`[urun] Failed to connect session for ${r}:`,D)}),e.releaseOnLeave!==!1){let D=ks(()=>{if(b=!0,g.leaveLeg())return;if(g.connectedUrl!==null){g.disconnect();return}g.disconnect();let j=v;j?N(j):w=!0});_.onDisconnect(D);let U,q,te=!1,E=()=>{te||(te=!0,U?.(),q?.())};y.then(j=>{j.status!=="ready"||te||(U=Ts(()=>v!==void 0))}),q=_.onPhase(j=>{let k=j?.name;(k==="paused"||k==="error")&&E()}),te&&q(),_.onDisconnect(E)}return _}}})}var Ro="https://api.urun.sh",Co="URUN_DEV";function mg(){if(typeof process>"u")return!1;let n=process.env?.[Co];if(typeof n!="string")return!1;let e=n.trim().toLowerCase();return e==="1"||e==="true"}var it=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function pl(n,e={}){if(!n)throw new it("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=J(e.baseUrl??Ro),s={};e.expiresIn!==void 0&&(s.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(s.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(s.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(s.max_session_s=e.maxSessionS),e.subject!==void 0&&(s.subject=e.subject),e.metadata!==void 0&&(s.metadata=e.metadata),e.sharedApp&&(s.shared_app=!0),(e.dev??mg())&&(s.dev=!0);let i;try{i=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(s)})}catch(p){throw new it(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let o={};try{o=await i.json()}catch{}if(!i.ok){let p=typeof o.message=="string"?o.message:`HTTP ${i.status}`;throw new it(`[urun] client token mint failed: ${p}`,i.status)}let a=typeof o.token=="string"?o.token:"",c=typeof o.org_id=="string"?o.org_id:"",d=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,l=typeof o.expires_in=="number"?o.expires_in:void 0;if(!a)throw new it("[urun] client token mint returned no token (control-plane contract violation)",i.status);let u=Number.isFinite(d)?new Date(d):new Date(Date.now()+(l??60)*1e3);return{token:a,expiresAt:u,orgId:c}}var hl=3e4,fl="stream:",Eo=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let i=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(i.timer),s.error?i.reject(new Error(s.error)):i.resolve(s.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 r=`${fl}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${fl}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),s(new Error(`RPC request "${e}" timed out after ${hl}ms`)))},hl);this._pendingRpc.set(i,{resolve:r,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function ml(n){let r=`${n.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(n.orgId)}`,s=new WebSocket(r);(n.jwt||n.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:n.orgId,jwt:n.jwt,authProvider:n.authProvider,apiKey:n.apiKey}))});let i=new kt(s);return new Eo(s,i)}var gg='video/mp4; codecs="avc1.42E01E"';function gl(n,e){let t=e?.codec??gg,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let s=new MediaSource,i=URL.createObjectURL(s);r.src=i,s.addEventListener("sourceopen",()=>{let p;try{p=s.addSourceBuffer(t)}catch(g){throw g instanceof DOMException&&g.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).`):g}let h=n.getReader();function m(){return p.updating?new Promise(g=>{p.addEventListener("updateend",()=>g(),{once:!0})}):Promise.resolve()}async function f(){try{for(;;){let{done:g,value:_}=await h.read();if(g){await m(),s.readyState==="open"&&s.endOfStream();return}await m();try{p.appendBuffer(_)}catch(v){if(v instanceof DOMException&&v.name==="QuotaExceededError"){let b=p.buffered;if(b.length>0){let w=b.start(b.length-1);p.remove(0,w),await m(),p.appendBuffer(_)}else throw v}else throw v}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}f()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),d=c.getTracks(),l=0,u=d.length;if(u===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let p of d)p.addEventListener("ended",()=>{l++,l>=u&&URL.revokeObjectURL(i)});return c}function _l(n){return n.status.startsWith("pending_")}var St=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)}},br=class extends St{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function _g(n,e,t){let r=t||e||`HTTP ${n}`;return n===401?new br(r,e??"unauthorized"):new St(r,{status:n,code:e??`http_${n}`})}var cn=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 St("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let r=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(r)?r:[]}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),i=await this._resolveToken(),o=await this._fetch(s,e,i);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw _g(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r){let s={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:t,headers:s})}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 br("[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 r=(await e.json()).error;if(r&&typeof r=="object"){let{code:s,message:i}=r;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function vl(n){return new cn(n)}var dn=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 wl(n){let e=[];return n.audio&&e.push("audio"),n.video&&e.push("video"),e.join("+")}function vg(n,e){return e==="audio"?n.getAudioTracks():n.getVideoTracks()}function wg(n,e){let t=n.getTracks();if(t.length===1&&t[0]===e)return n;try{return new MediaStream([e])}catch{return n}}function Po(n,e){for(let t of[...n.lostListeners])try{t(e)}catch{}}var ln=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let r=this.claims.get(e);r&&(this.claims.delete(e),r.released=!0,r.track=null,r.stream=null,Po(r,new Error(`${e} capture claim superseded by a newer claim`)));let s=this.createState(e,t);return this.claims.set(e,s),await this.converge(s),s.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 dn;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(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await t(r)}catch(o){let a=`one-capture getUserMedia(${wl(r)}) failed`,c=o instanceof Error?o.message:String(o);for(let d of[...this.claims.values()])if(this.claims.delete(d.kind),d.released=!0,d!==e){let l=new Error(`${a} \u2014 ${d.kind} capture lost: ${c||o}`);l.cause=o,Po(d,l)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of i){let a=vg(s,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${wl(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw c;Po(o,c);continue}if(o.track=a,o.stream=wg(s,a),o!==e)for(let c of[...o.trackListeners])try{c(a,o.stream)}catch{}}}createState(e,t){let r=this,s={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return s.track},get stream(){return s.stream},update(i){return r.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=i,await r.converge(s),!s.track)throw new Error(`${e} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(e)===s&&r.claims.delete(e),s.track?.stop(),s.track=null,s.stream=null)},onTrack(i){return s.trackListeners.add(i),()=>s.trackListeners.delete(i)},onLost(i){return s.lostListeners.add(i),()=>s.lostListeners.delete(i)}}};return s}},yg=null;function yl(){return yg??=new ln}var Do="input",bl=30;function Sl(n){let e=n.now??Date.now,t=n.field??Do,r=1e3/Math.max(n.hz??30,.001),s=new Set,i=0,o=0,a=0,c=0,d,l=null,u=!1,p=()=>{if(u)return;d=e(),c+=1;let m={keys:[...s],buttons:i,pointer:{x:o,y:a},seq:c,at:d};try{n.awareness.setLocalStateField(t,m)}catch{}},h=()=>{if(u)return;let m=e();if(d===void 0||m-d>=r){l&&(clearTimeout(l),l=null),p();return}if(l)return;let f=Math.max(r-(m-d),0);l=setTimeout(()=>{l=null,p()},f),l.unref?.()};return{keyDown(m){let f=String(m).toLowerCase();s.has(f)||(s.add(f),h())},keyUp(m){let f=String(m).toLowerCase();s.delete(f)&&h()},setButtons(m){let f=Number.isFinite(m)?Number(m):0;f!==i&&(i=f,h())},movePointer(m,f){let g=Number.isFinite(m)?Number(m):0,_=Number.isFinite(f)?Number(f):0;g===0&&_===0||(o+=g,a+=_,h())},heldKeys(){return[...s]},clear(){u||(s.clear(),i=0,l&&(clearTimeout(l),l=null),p())},dispose(){if(u)return;let m=s.size>0||i!==0;s.clear(),i=0,l&&(clearTimeout(l),l=null),m&&p(),u=!0}}}var Rl=1024,Cl=.92,El=262144,Pl=256e3,xo=[.9,.8,.7,.6,.5],kl=.8,bg=8;function Ns(n,e,t){if(!(n>0)||!(e>0))throw new Error(`reference image has no pixels (${n}x${e})`);let r=Math.min(1,t/Math.max(n,e));return{width:Math.max(1,Math.round(n*r)),height:Math.max(1,Math.round(e*r))}}async function Sg(n){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(n,{imageOrientation:"from-image"})}async function Dl(n,e,t){let r=await new Promise(s=>{n.toBlob(s,e,e==="image/jpeg"?t:void 0)});if(!r)throw new Error(`could not encode the reference image as ${e}`);return r}function Tl(n,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${n} -> ${e} bytes`)}async function Io(n,e,t,r,s){let i=document.createElement("canvas");i.width=e,i.height=t;let o=i.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,t)),o.drawImage(n,0,0,e,t),await Dl(i,r,s)}async function kg(n,e,t,r){let{width:s,height:i}=e,o=await Io(n,s,i,t,r);if(o.size<=256e3)return{blob:o,width:s,height:i};if(t==="image/jpeg"){for(let c of xo)if(!(c>=r)&&(o=await Io(n,s,i,t,c),o.size<=256e3))return Tl(`quality ${r} -> ${c}`,o.size),{blob:o,width:s,height:i}}let a=t==="image/jpeg"?xo[xo.length-1]:r;for(let c=0;c<bg;c++)if(s=Math.max(16,Math.round(s*kl)),i=Math.max(16,Math.round(i*kl)),o=await Io(n,s,i,t,a),o.size<=256e3)return Tl(`downscaled to ${s}x${i} @ q${a}`,o.size),{blob:o,width:s,height:i};throw new Error(`this image cannot be sent: even at ${s}x${i} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function xl(n,e){let{maxSize:t=1024,type:r="image/jpeg",quality:s=.92,source:i}=e,o=await Sg(n);try{let a=Ns(o.width,o.height,t),c=await kg(o,a,r,s);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:r,width:c.width,height:c.height,source:i}}finally{o.close()}}function Il(n){let e=n instanceof Error?n.name:"",t=n instanceof Error?n.message:String(n);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 Al(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function Ll(n,e){let t=n.videoWidth,r=n.videoHeight;if(!(t>0)||!(r>0))throw new Error("the camera has not shown a frame yet");let{maxSize:s=1024,type:i="image/jpeg",quality:o=.92}=e??{},a=Ns(t,r,s),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let d=c.getContext("2d");if(!d)throw new Error("could not prepare the reference image (no 2d canvas context)");i==="image/jpeg"&&(d.fillStyle="#fff",d.fillRect(0,0,a.width,a.height)),d.drawImage(n,0,0,a.width,a.height);let l=await Dl(c,i,o);return{bytes:new Uint8Array(await l.arrayBuffer()),type:i,width:a.width,height:a.height,source:"camera"}}var Tg=new Set(["w","a","s","d"]),Sr=(n,e)=>Math.min(e,Math.max(-e,n));function Ml(n={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:s=900,frameRelax:i=.06,maxPan:o=.12,maxLogZoom:a=.22}=n,c=0,d=0,l=0,u=null,p=new Set;return{pointerDelta(h,m){c=Sr(c-h*e,o),d=Sr(d-m*e,o)},keyDown(h){let m=h.toLowerCase();Tg.has(m)&&p.add(m)},keyUp(h){p.delete(h.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let h=1-i;c*=h,d*=h,l*=h},tick(h){if(u===null){u=h;return}let m=Math.max(0,Math.min(100,h-u))/1e3;u=h,p.has("w")&&(l=Sr(l+t*m,a)),p.has("s")&&(l=Sr(l-t*m,a)),p.has("a")&&(c=Sr(c+r*m,o)),p.has("d")&&(c=Sr(c-r*m,o));let f=Math.exp(-m*1e3/s);c*=f,d*=f,l*=f},transform(){return{translateX:c,translateY:d,scale:Math.exp(l)}},isIdentity(h=5e-4){return Math.abs(c)<h&&Math.abs(d)<h&&Math.abs(l)<h},reset(){c=0,d=0,l=0,p.clear()}}}0&&(module.exports={ACTIVATION_COLD_BOOT_AFTER_MS,ACTIVATION_DEGRADED_AFTER_MS,ACTIVATION_HINT_PATH,ACTIVATION_STILL_AFTER_MS,ACTIVITY_DOM_EVENTS,ACTIVITY_FIELD,ACTIVITY_STAMP_MIN_INTERVAL_MS,ActivationMonitor,App,BACKOFF_BASE_MS,BACKOFF_MAX_ATTEMPTS,BACKOFF_MAX_MS,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS,CaptureController,CaptureUnavailableError,ClientTokenError,CreditsClient,CreditsError,CreditsUnauthorizedError,DATA_CHANNEL_MESSAGE_CEILING,DEFAULT_DOC_SYNC_TIMEOUT_MS,DEFAULT_GATEWAY_URL,DEFAULT_PRODUCE_ACK_TIMEOUT_MS,DEFAULT_REFERENCE_JPEG_QUALITY,DEFAULT_REFERENCE_MAX_SIZE,DEFAULT_WHEN_LIVE_TIMEOUT_MS,DERIVED_LEG_SEP,DGRAM_HEADER_BYTES,FOCUS_FIELD,FOREGROUND_COALESCE_MS,FrameReassembler,GENERATION_TICK_EMIT_INTERVAL_MS,GENERATION_TICK_MAX_EXTRAPOLATION_MS,INPUT_PRESENCE_DEFAULT_HZ,INPUT_PRESENCE_FIELD,InvalidDurationError,LEGACY_ACTIVATION_HINT_PATH,PLATFORM_DOC_NAME,PermanentLockedError,PinRequiresActiveTempError,PresenceTracker,ProduceAckTimeoutError,RecordingNotFoundError,RecordingsClient,RecordingsError,RecordingsUnauthorizedError,RequestAbortError,RequestCancelledError,RequestDocSyncError,RequestError,RequestTimeoutError,RetainNotTempError,RuntimeArtifactNotFoundError,RuntimeArtifactsClient,RuntimeArtifactsError,RuntimeArtifactsUnauthorizedError,SIGNALING_PROTOCOL_VERSION,STREAM_END,Session,SessionAllocationError,SessionDirectory,SessionDirectoryError,SessionEndError,SessionEndUnavailableError,SessionFailedError,StreamDirectionConflict,TransportNegotiator,TransportSessionMismatchError,TransportSessionSignaling,URUN_DEV_ENV,USER_ACTIVITY_FIELD,USER_ACTIVITY_MIN_INTERVAL_MS,VISIBILITY_FIELD,WIRE_MESSAGE_BUDGET,WT_CONTROL_FRAME_MAX,WT_DATA_STREAM_VERSION,WebRtcSession,WebTransportSession,WtControlDecoder,WtDataStreamParser,activationHintFrom,cameraCaptureAvailable,captureStillFromVideo,computeBackoffDelay,consumeWtDataStreams,createActivityTracker,createCameraWarp,createClientToken,createCreditsClient,createInputPresencePublisher,createRecordingsClient,createRuntimeArtifactsClient,createStore,decodeStreamEnvelope,derivedLegName,derivedLegRole,describeSessionFailure,describeSessionPhase,encodeStreamEnvelope,encodeWtControlFrame,fitWithin,isDurationString,isPausedPhase,isPendingRecording,isRetryableSessionError,isWakingPhase,mediaRecorderChunkSource,normalizeReferenceImage,normalizeRetention,observeLeaveConfirm,observePageLifecycle,observePageTeardown,parseDgramHeader,prewake,referenceImageErrorMessage,releaseSessionBeacon,sessionDirectory,sessionFailureFromMediaError,sharedCaptureController,videoStream,watchGenerationTick,whenLive,writeDgramHeader});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __urunCreateRequire } from 'node:module'; const require = globalThis.require ?? __urunCreateRequire(import.meta.url);
2
- import{$ as Tt,A as Ze,B as Qe,C as et,D as tt,E as rt,F as nt,G as it,H as ot,I as st,J as at,K as ct,L as dt,M as ut,N as lt,O as pt,P as mt,Q as gt,R as ft,S as ht,T as St,U as yt,V as bt,W as Et,X as vt,Y as wt,Z as kt,_ as _t,a as pe,aa as xt,b as me,ba as Rt,c as ge,ca as Ct,d as fe,da as At,e as he,ea as Pt,f as Se,fa as It,g as ye,h as be,i as Re,j as Ce,k as Ae,l as Pe,m as Ie,n as Me,o as Oe,p as De,q as Le,r as Ue,s as Ne,t as Fe,u as Be,v as We,w as Ge,x as je,y as Xe,z as Je}from"./chunk-SAKVBT4A.mjs";import{$ as ze,C as Ee,D as ve,E as we,F as ke,G as _e,H as O,J as Te,S as xe,V as $e,W as qe,X as Ve,a as M,aa as Ke,ba as He,c as q,ca as Ye,d as V,e as z,f as K,g as H,h as Y,i as X,j as J,k as Z,l as Q,m as ee,n as te,o as re,p as ne,q as ie,r as oe,s as se,t as ae,u as ce,v as de,w as ue,x as le}from"./chunk-LIGXGD7T.mjs";import"./chunk-NLAOQUYQ.mjs";var D="https://api.urun.sh",L="URUN_DEV";function Mt(){if(typeof process>"u")return!1;let i=process.env?.[L];if(typeof i!="string")return!1;let e=i.trim().toLowerCase();return e==="1"||e==="true"}var S=class extends Error{status;constructor(e,r){super(e),this.name="ClientTokenError",this.status=r}};async function Ot(i,e={}){if(!i)throw new S("[urun] createClientToken requires an org API key");let r=e.fetch??globalThis.fetch,o=O(e.baseUrl??D),t={};e.expiresIn!==void 0&&(t.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(t.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(t.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(t.max_session_s=e.maxSessionS),e.subject!==void 0&&(t.subject=e.subject),e.metadata!==void 0&&(t.metadata=e.metadata),e.sharedApp&&(t.shared_app=!0),(e.dev??Mt())&&(t.dev=!0);let s;try{s=await r(`${o}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(t)})}catch(p){throw new S(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let n={};try{n=await s.json()}catch{}if(!s.ok){let p=typeof n.message=="string"?n.message:`HTTP ${s.status}`;throw new S(`[urun] client token mint failed: ${p}`,s.status)}let c=typeof n.token=="string"?n.token:"",a=typeof n.org_id=="string"?n.org_id:"",l=typeof n.expires_at=="string"?Date.parse(n.expires_at):Number.NaN,d=typeof n.expires_in=="number"?n.expires_in:void 0;if(!c)throw new S("[urun] client token mint returned no token (control-plane contract violation)",s.status);let f=Number.isFinite(l)?new Date(l):new Date(Date.now()+(d??60)*1e3);return{token:c,expiresAt:f,orgId:a}}var U=3e4,N="stream:",R=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,r){this._ws=e,this._multiplexer=r,this._ws.addEventListener("message",o=>{let t;try{t=JSON.parse(typeof o.data=="string"?o.data:"")}catch{return}if(t.rpcId&&this._pendingRpc.has(t.rpcId)){let s=this._pendingRpc.get(t.rpcId);this._pendingRpc.delete(t.rpcId),clearTimeout(s.timer),t.error?s.reject(new Error(t.error)):s.resolve(t.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,r){let o=`${N}${e}`;return this._multiplexer.on(o,t=>{r(t)})}emit(e,r){let o=`${N}${e}`,t=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{data:r};this._multiplexer.emit(o,t)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,r){return new Promise((o,t)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){t(new Error("WebSocket not open"));return}let s=String(++this._rpcId),n=setTimeout(()=>{this._pendingRpc.has(s)&&(this._pendingRpc.delete(s),t(new Error(`RPC request "${e}" timed out after ${U}ms`)))},U);this._pendingRpc.set(s,{resolve:o,reject:t,timer:n}),this._ws.send(JSON.stringify({rpcId:s,type:e,...r}))})}};function Dt(i){let o=`${i.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(i.orgId)}`,t=new WebSocket(o);(i.jwt||i.apiKey)&&t.addEventListener("open",()=>{t.send(JSON.stringify({type:"auth",orgId:i.orgId,jwt:i.jwt,authProvider:i.authProvider,apiKey:i.apiKey}))});let s=new M(t);return new R(t,s)}var Lt='video/mp4; codecs="avc1.42E01E"';function Ut(i,e){let r=e?.codec??Lt,o=document.createElement("video");o.muted=!0,o.playsInline=!0;let t=new MediaSource,s=URL.createObjectURL(t);o.src=s,t.addEventListener("sourceopen",()=>{let p;try{p=t.addSourceBuffer(r)}catch(h){throw h instanceof DOMException&&h.name==="NotSupportedError"?new Error(`Codec not supported: "${r}". 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 m=i.getReader();function u(){return p.updating?new Promise(h=>{p.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function g(){try{for(;;){let{done:h,value:E}=await m.read();if(h){await u(),t.readyState==="open"&&t.endOfStream();return}await u();try{p.appendBuffer(E)}catch(w){if(w instanceof DOMException&&w.name==="QuotaExceededError"){let x=p.buffered;if(x.length>0){let $=x.start(x.length-1);p.remove(0,$),await u(),p.appendBuffer(E)}else throw w}else throw w}}}catch{if(t.readyState==="open")try{t.endOfStream("decode")}catch{}}}g()}),o.play().catch(()=>{});let n=o,c=n.captureStream??n.mozCaptureStream;if(!c)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let a=c.call(o),l=a.getTracks(),d=0,f=l.length;if(f===0)o.addEventListener("emptied",()=>{URL.revokeObjectURL(s)},{once:!0});else for(let p of l)p.addEventListener("ended",()=>{d++,d>=f&&URL.revokeObjectURL(s)});return a}function Nt(i){return i.status.startsWith("pending_")}var y=class extends Error{status;code;constructor(e,r){super(e),this.name="CreditsError",this.status=r.status,this.code=r.code,r.cause!==void 0&&(this.cause=r.cause),Object.setPrototypeOf(this,new.target.prototype)}},v=class extends y{constructor(e="[urun] credits: unauthorized",r="unauthorized"){super(e,{status:401,code:r}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function Ft(i,e,r){let o=r||e||`HTTP ${i}`;return i===401?new v(o,e??"unauthorized"):new y(o,{status:i,code:e??`http_${i}`})}var k=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 y("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let o=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(o)?o:[]}async _request(e,r,o={}){let t=this._buildUrl(r,o.params),s=await this._resolveToken(),n=await this._fetch(t,e,s);if(n.status===401&&this._options.getAccessToken){let c=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});c&&c!==s&&(s=c,n=await this._fetch(t,e,s))}if(!n.ok){let{code:c,message:a}=await this._readError(n);throw Ft(n.status,c,a)}return this._readJson(n)}_buildUrl(e,r){let o=`${this._base}${e}`,t=Object.entries(r??{}).filter(([,s])=>s!=null&&s!=="").map(([s,n])=>`${encodeURIComponent(s)}=${encodeURIComponent(n)}`).join("&");return t&&(o+=`?${t}`),o}_fetch(e,r,o){let t={Authorization:`Bearer ${o}`,apikey:o,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(t["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:r,headers:t})}async _resolveToken(){if(this._options.getAccessToken){let r=await this._options.getAccessToken();if(r)return r}let e=this._options.jwt??this._options.apiKey;if(!e)throw new v("[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 o=(await e.json()).error;if(o&&typeof o=="object"){let{code:t,message:s}=o;return{code:typeof t=="string"?t:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Bt(i){return new k(i)}var _=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 F(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function Wt(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function Gt(i,e){let r=i.getTracks();if(r.length===1&&r[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function C(i,e){for(let r of[...i.lostListeners])try{r(e)}catch{}}var T=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,r){return this.enqueue(async()=>{let o=this.claims.get(e);o&&(this.claims.delete(e),o.released=!0,o.track=null,o.stream=null,C(o,new Error(`${e} capture claim superseded by a newer claim`)));let t=this.createState(e,r);return this.claims.set(e,t),await this.converge(t),t.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let r=this.queue.then(e);return this.queue=r.then(()=>{},()=>{}),r}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new _;return r=>e.getUserMedia(r)}async converge(e){for(let n of this.claims.values())n.track&&(n.track.stop(),n.track=null,n.stream=null);if(this.claims.size===0)return;let r=this.resolveGetUserMedia(),o={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},t;try{t=await r(o)}catch(n){let c=`one-capture getUserMedia(${F(o)}) failed`,a=n instanceof Error?n.message:String(n);for(let l of[...this.claims.values()])if(this.claims.delete(l.kind),l.released=!0,l!==e){let d=new Error(`${c} \u2014 ${l.kind} capture lost: ${a||n}`);d.cause=n,C(l,d)}throw n}let s=[...this.claims.values()].sort((n,c)=>n===e?1:c===e?-1:0);for(let n of s){let c=Wt(t,n.kind)[0]??null;if(n.released){c?.stop();continue}if(!c){this.claims.delete(n.kind),n.released=!0;let a=Object.assign(new Error(`one-capture getUserMedia(${F(o)}) returned no ${n.kind} track`),{name:"NotFoundError"});if(n===e)throw a;C(n,a);continue}if(n.track=c,n.stream=Gt(t,c),n!==e)for(let a of[...n.trackListeners])try{a(c,n.stream)}catch{}}}createState(e,r){let o=this,t={kind:e,constraints:r,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return t.track},get stream(){return t.stream},update(s){return o.enqueue(async()=>{if(t.released)throw new Error(`${e} capture claim already released`);if(t.constraints=s,await o.converge(t),!t.track)throw new Error(`${e} capture update yielded no track`);return t.track})},release(){t.released||(t.released=!0,o.claims.get(e)===t&&o.claims.delete(e),t.track?.stop(),t.track=null,t.stream=null)},onTrack(s){return t.trackListeners.add(s),()=>t.trackListeners.delete(s)},onLost(s){return t.lostListeners.add(s),()=>t.lostListeners.delete(s)}}};return t}},jt=null;function $t(){return jt??=new T}var B="input",qt=30;function Vt(i){let e=i.now??Date.now,r=i.field??B,o=1e3/Math.max(i.hz??30,.001),t=new Set,s=0,n=0,c=0,a=0,l,d=null,f=!1,p=()=>{if(f)return;l=e(),a+=1;let u={keys:[...t],buttons:s,pointer:{x:n,y:c},seq:a,at:l};try{i.awareness.setLocalStateField(r,u)}catch{}},m=()=>{if(f)return;let u=e();if(l===void 0||u-l>=o){d&&(clearTimeout(d),d=null),p();return}if(d)return;let g=Math.max(o-(u-l),0);d=setTimeout(()=>{d=null,p()},g),d.unref?.()};return{keyDown(u){let g=String(u).toLowerCase();t.has(g)||(t.add(g),m())},keyUp(u){let g=String(u).toLowerCase();t.delete(g)&&m()},setButtons(u){let g=Number.isFinite(u)?Number(u):0;g!==s&&(s=g,m())},movePointer(u,g){let h=Number.isFinite(u)?Number(u):0,E=Number.isFinite(g)?Number(g):0;h===0&&E===0||(n+=h,c+=E,m())},heldKeys(){return[...t]},clear(){f||(t.clear(),s=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(f)return;let u=t.size>0||s!==0;t.clear(),s=0,d&&(clearTimeout(d),d=null),u&&p(),f=!0}}}var zt=1024,Kt=.92,Ht=262144,Yt=256e3,A=[.9,.8,.7,.6,.5],W=.8,Xt=8;function I(i,e,r){if(!(i>0)||!(e>0))throw new Error(`reference image has no pixels (${i}x${e})`);let o=Math.min(1,r/Math.max(i,e));return{width:Math.max(1,Math.round(i*o)),height:Math.max(1,Math.round(e*o))}}async function Jt(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 j(i,e,r){let o=await new Promise(t=>{i.toBlob(t,e,e==="image/jpeg"?r:void 0)});if(!o)throw new Error(`could not encode the reference image as ${e}`);return o}function G(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 P(i,e,r,o,t){let s=document.createElement("canvas");s.width=e,s.height=r;let n=s.getContext("2d");if(!n)throw new Error("could not prepare the reference image (no 2d canvas context)");return o==="image/jpeg"&&(n.fillStyle="#fff",n.fillRect(0,0,e,r)),n.drawImage(i,0,0,e,r),await j(s,o,t)}async function Zt(i,e,r,o){let{width:t,height:s}=e,n=await P(i,t,s,r,o);if(n.size<=256e3)return{blob:n,width:t,height:s};if(r==="image/jpeg"){for(let a of A)if(!(a>=o)&&(n=await P(i,t,s,r,a),n.size<=256e3))return G(`quality ${o} -> ${a}`,n.size),{blob:n,width:t,height:s}}let c=r==="image/jpeg"?A[A.length-1]:o;for(let a=0;a<Xt;a++)if(t=Math.max(16,Math.round(t*W)),s=Math.max(16,Math.round(s*W)),n=await P(i,t,s,r,c),n.size<=256e3)return G(`downscaled to ${t}x${s} @ q${c}`,n.size),{blob:n,width:t,height:s};throw new Error(`this image cannot be sent: even at ${t}x${s} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function Qt(i,e){let{maxSize:r=1024,type:o="image/jpeg",quality:t=.92,source:s}=e,n=await Jt(i);try{let c=I(n.width,n.height,r),a=await Zt(n,c,o,t);return{bytes:new Uint8Array(await a.blob.arrayBuffer()),type:o,width:a.width,height:a.height,source:s}}finally{n.close()}}function er(i){let e=i instanceof Error?i.name:"",r=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(r)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(r)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(r)?"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 tr(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function rr(i,e){let r=i.videoWidth,o=i.videoHeight;if(!(r>0)||!(o>0))throw new Error("the camera has not shown a frame yet");let{maxSize:t=1024,type:s="image/jpeg",quality:n=.92}=e??{},c=I(r,o,t),a=document.createElement("canvas");a.width=c.width,a.height=c.height;let l=a.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,c.width,c.height)),l.drawImage(i,0,0,c.width,c.height);let d=await j(a,s,n);return{bytes:new Uint8Array(await d.arrayBuffer()),type:s,width:c.width,height:c.height,source:"camera"}}var nr=new Set(["w","a","s","d"]),b=(i,e)=>Math.min(e,Math.max(-e,i));function ir(i={}){let{panPerPixel:e=9e-4,zoomPerSecond:r=.35,strafePerSecond:o=.18,decayTauMs:t=900,frameRelax:s=.06,maxPan:n=.12,maxLogZoom:c=.22}=i,a=0,l=0,d=0,f=null,p=new Set;return{pointerDelta(m,u){a=b(a-m*e,n),l=b(l-u*e,n)},keyDown(m){let u=m.toLowerCase();nr.has(u)&&p.add(u)},keyUp(m){p.delete(m.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let m=1-s;a*=m,l*=m,d*=m},tick(m){if(f===null){f=m;return}let u=Math.max(0,Math.min(100,m-f))/1e3;f=m,p.has("w")&&(d=b(d+r*u,c)),p.has("s")&&(d=b(d-r*u,c)),p.has("a")&&(a=b(a+o*u,n)),p.has("d")&&(a=b(a-o*u,n));let g=Math.exp(-u*1e3/t);a*=g,l*=g,d*=g},transform(){return{translateX:a,translateY:l,scale:Math.exp(d)}},isIdentity(m=5e-4){return Math.abs(a)<m&&Math.abs(l)<m&&Math.abs(d)<m},reset(){a=0,l=0,d=0,p.clear()}}}export{me as ACTIVATION_COLD_BOOT_AFTER_MS,ge as ACTIVATION_DEGRADED_AFTER_MS,he as ACTIVATION_HINT_PATH,pe as ACTIVATION_STILL_AFTER_MS,rt as ACTIVITY_DOM_EVENTS,Qe as ACTIVITY_FIELD,tt as ACTIVITY_STAMP_MIN_INTERVAL_MS,be as ActivationMonitor,It as App,Ee as BACKOFF_BASE_MS,we as BACKOFF_MAX_ATTEMPTS,ve as BACKOFF_MAX_MS,de as COLD_BOOT_WHEN_LIVE_TIMEOUT_MS,T as CaptureController,_ as CaptureUnavailableError,S as ClientTokenError,k as CreditsClient,y as CreditsError,v as CreditsUnauthorizedError,Ht as DATA_CHANNEL_MESSAGE_CEILING,Rt as DEFAULT_DOC_SYNC_TIMEOUT_MS,D as DEFAULT_GATEWAY_URL,J as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Kt as DEFAULT_REFERENCE_JPEG_QUALITY,zt as DEFAULT_REFERENCE_MAX_SIZE,ce as DEFAULT_WHEN_LIVE_TIMEOUT_MS,ze as DERIVED_LEG_SEP,ht as DGRAM_HEADER_BYTES,ot as FOCUS_FIELD,ct as FOREGROUND_COALESCE_MS,bt as FrameReassembler,Xe as GENERATION_TICK_EMIT_INTERVAL_MS,Je as GENERATION_TICK_MAX_EXTRAPOLATION_MS,qt as INPUT_PRESENCE_DEFAULT_HZ,B as INPUT_PRESENCE_FIELD,Fe as InvalidDurationError,Se as LEGACY_ACTIVATION_HINT_PATH,fe as PLATFORM_DOC_NAME,Ne as PermanentLockedError,Ue as PinRequiresActiveTempError,at as PresenceTracker,Z as ProduceAckTimeoutError,De as RecordingNotFoundError,Ge as RecordingsClient,Me as RecordingsError,Oe as RecordingsUnauthorizedError,Q as RequestAbortError,ee as RequestCancelledError,Y as RequestDocSyncError,K as RequestError,H as RequestTimeoutError,Le as RetainNotTempError,Ae as RuntimeArtifactNotFoundError,Ie as RuntimeArtifactsClient,Re as RuntimeArtifactsError,Ce as RuntimeArtifactsUnauthorizedError,Ye as SIGNALING_PROTOCOL_VERSION,$e as STREAM_END,Ct as Session,oe as SessionAllocationError,At as SessionDirectory,z as SessionDirectoryError,V as SessionEndError,q as SessionEndUnavailableError,re as SessionFailedError,X as StreamDirectionConflict,_t as TransportNegotiator,ie as TransportSessionMismatchError,Tt as TransportSessionSignaling,L as URUN_DEV_ENV,it as USER_ACTIVITY_FIELD,st as USER_ACTIVITY_MIN_INTERVAL_MS,et as VISIBILITY_FIELD,Yt as WIRE_MESSAGE_BUDGET,mt as WT_CONTROL_FRAME_MAX,Et as WT_DATA_STREAM_VERSION,xt as WebRtcSession,kt as WebTransportSession,ft as WtControlDecoder,vt as WtDataStreamParser,ye as activationHintFrom,tr as cameraCaptureAvailable,rr as captureStillFromVideo,ke as computeBackoffDelay,wt as consumeWtDataStreams,nt as createActivityTracker,ir as createCameraWarp,Ot as createClientToken,Bt as createCreditsClient,Vt as createInputPresencePublisher,je as createRecordingsClient,Pe as createRuntimeArtifactsClient,Dt as createStore,Ve as decodeStreamEnvelope,He as derivedLegName,Ke as derivedLegRole,te as describeSessionFailure,le as describeSessionPhase,qe as encodeStreamEnvelope,gt as encodeWtControlFrame,I as fitWithin,Be as isDurationString,ae as isPausedPhase,Nt as isPendingRecording,_e as isRetryableSessionError,se as isWakingPhase,pt as mediaRecorderChunkSource,Qt as normalizeReferenceImage,We as normalizeRetention,lt as observeLeaveConfirm,dt as observePageLifecycle,ut as observePageTeardown,St as parseDgramHeader,xe as prewake,er as referenceImageErrorMessage,Te as releaseSessionBeacon,Pt as sessionDirectory,ne as sessionFailureFromMediaError,$t as sharedCaptureController,Ut as videoStream,Ze as watchGenerationTick,ue as whenLive,yt as writeDgramHeader};
2
+ import{$ as Tt,A as Ze,B as Qe,C as et,D as tt,E as rt,F as nt,G as it,H as ot,I as st,J as at,K as ct,L as dt,M as ut,N as lt,O as pt,P as mt,Q as gt,R as ft,S as ht,T as St,U as yt,V as bt,W as Et,X as vt,Y as wt,Z as kt,_ as _t,a as pe,aa as xt,b as me,ba as Rt,c as ge,ca as Ct,d as fe,da as At,e as he,ea as Pt,f as Se,fa as It,g as ye,h as be,i as Re,j as Ce,k as Ae,l as Pe,m as Ie,n as Me,o as Oe,p as De,q as Le,r as Ue,s as Ne,t as Fe,u as Be,v as We,w as Ge,x as je,y as Xe,z as Je}from"./chunk-2HOATHCZ.mjs";import{$ as ze,C as Ee,D as ve,E as we,F as ke,G as _e,H as O,J as Te,S as xe,V as $e,W as qe,X as Ve,a as M,aa as Ke,ba as He,c as q,ca as Ye,d as V,e as z,f as K,g as H,h as Y,i as X,j as J,k as Z,l as Q,m as ee,n as te,o as re,p as ne,q as ie,r as oe,s as se,t as ae,u as ce,v as de,w as ue,x as le}from"./chunk-LIGXGD7T.mjs";import"./chunk-NLAOQUYQ.mjs";var D="https://api.urun.sh",L="URUN_DEV";function Mt(){if(typeof process>"u")return!1;let i=process.env?.[L];if(typeof i!="string")return!1;let e=i.trim().toLowerCase();return e==="1"||e==="true"}var S=class extends Error{status;constructor(e,r){super(e),this.name="ClientTokenError",this.status=r}};async function Ot(i,e={}){if(!i)throw new S("[urun] createClientToken requires an org API key");let r=e.fetch??globalThis.fetch,o=O(e.baseUrl??D),t={};e.expiresIn!==void 0&&(t.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(t.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(t.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(t.max_session_s=e.maxSessionS),e.subject!==void 0&&(t.subject=e.subject),e.metadata!==void 0&&(t.metadata=e.metadata),e.sharedApp&&(t.shared_app=!0),(e.dev??Mt())&&(t.dev=!0);let s;try{s=await r(`${o}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(t)})}catch(p){throw new S(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let n={};try{n=await s.json()}catch{}if(!s.ok){let p=typeof n.message=="string"?n.message:`HTTP ${s.status}`;throw new S(`[urun] client token mint failed: ${p}`,s.status)}let c=typeof n.token=="string"?n.token:"",a=typeof n.org_id=="string"?n.org_id:"",l=typeof n.expires_at=="string"?Date.parse(n.expires_at):Number.NaN,d=typeof n.expires_in=="number"?n.expires_in:void 0;if(!c)throw new S("[urun] client token mint returned no token (control-plane contract violation)",s.status);let f=Number.isFinite(l)?new Date(l):new Date(Date.now()+(d??60)*1e3);return{token:c,expiresAt:f,orgId:a}}var U=3e4,N="stream:",R=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,r){this._ws=e,this._multiplexer=r,this._ws.addEventListener("message",o=>{let t;try{t=JSON.parse(typeof o.data=="string"?o.data:"")}catch{return}if(t.rpcId&&this._pendingRpc.has(t.rpcId)){let s=this._pendingRpc.get(t.rpcId);this._pendingRpc.delete(t.rpcId),clearTimeout(s.timer),t.error?s.reject(new Error(t.error)):s.resolve(t.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,r){let o=`${N}${e}`;return this._multiplexer.on(o,t=>{r(t)})}emit(e,r){let o=`${N}${e}`,t=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{data:r};this._multiplexer.emit(o,t)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,r){return new Promise((o,t)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){t(new Error("WebSocket not open"));return}let s=String(++this._rpcId),n=setTimeout(()=>{this._pendingRpc.has(s)&&(this._pendingRpc.delete(s),t(new Error(`RPC request "${e}" timed out after ${U}ms`)))},U);this._pendingRpc.set(s,{resolve:o,reject:t,timer:n}),this._ws.send(JSON.stringify({rpcId:s,type:e,...r}))})}};function Dt(i){let o=`${i.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(i.orgId)}`,t=new WebSocket(o);(i.jwt||i.apiKey)&&t.addEventListener("open",()=>{t.send(JSON.stringify({type:"auth",orgId:i.orgId,jwt:i.jwt,authProvider:i.authProvider,apiKey:i.apiKey}))});let s=new M(t);return new R(t,s)}var Lt='video/mp4; codecs="avc1.42E01E"';function Ut(i,e){let r=e?.codec??Lt,o=document.createElement("video");o.muted=!0,o.playsInline=!0;let t=new MediaSource,s=URL.createObjectURL(t);o.src=s,t.addEventListener("sourceopen",()=>{let p;try{p=t.addSourceBuffer(r)}catch(h){throw h instanceof DOMException&&h.name==="NotSupportedError"?new Error(`Codec not supported: "${r}". 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 m=i.getReader();function u(){return p.updating?new Promise(h=>{p.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function g(){try{for(;;){let{done:h,value:E}=await m.read();if(h){await u(),t.readyState==="open"&&t.endOfStream();return}await u();try{p.appendBuffer(E)}catch(w){if(w instanceof DOMException&&w.name==="QuotaExceededError"){let x=p.buffered;if(x.length>0){let $=x.start(x.length-1);p.remove(0,$),await u(),p.appendBuffer(E)}else throw w}else throw w}}}catch{if(t.readyState==="open")try{t.endOfStream("decode")}catch{}}}g()}),o.play().catch(()=>{});let n=o,c=n.captureStream??n.mozCaptureStream;if(!c)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let a=c.call(o),l=a.getTracks(),d=0,f=l.length;if(f===0)o.addEventListener("emptied",()=>{URL.revokeObjectURL(s)},{once:!0});else for(let p of l)p.addEventListener("ended",()=>{d++,d>=f&&URL.revokeObjectURL(s)});return a}function Nt(i){return i.status.startsWith("pending_")}var y=class extends Error{status;code;constructor(e,r){super(e),this.name="CreditsError",this.status=r.status,this.code=r.code,r.cause!==void 0&&(this.cause=r.cause),Object.setPrototypeOf(this,new.target.prototype)}},v=class extends y{constructor(e="[urun] credits: unauthorized",r="unauthorized"){super(e,{status:401,code:r}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function Ft(i,e,r){let o=r||e||`HTTP ${i}`;return i===401?new v(o,e??"unauthorized"):new y(o,{status:i,code:e??`http_${i}`})}var k=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 y("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let o=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(o)?o:[]}async _request(e,r,o={}){let t=this._buildUrl(r,o.params),s=await this._resolveToken(),n=await this._fetch(t,e,s);if(n.status===401&&this._options.getAccessToken){let c=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});c&&c!==s&&(s=c,n=await this._fetch(t,e,s))}if(!n.ok){let{code:c,message:a}=await this._readError(n);throw Ft(n.status,c,a)}return this._readJson(n)}_buildUrl(e,r){let o=`${this._base}${e}`,t=Object.entries(r??{}).filter(([,s])=>s!=null&&s!=="").map(([s,n])=>`${encodeURIComponent(s)}=${encodeURIComponent(n)}`).join("&");return t&&(o+=`?${t}`),o}_fetch(e,r,o){let t={Authorization:`Bearer ${o}`,apikey:o,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(t["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:r,headers:t})}async _resolveToken(){if(this._options.getAccessToken){let r=await this._options.getAccessToken();if(r)return r}let e=this._options.jwt??this._options.apiKey;if(!e)throw new v("[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 o=(await e.json()).error;if(o&&typeof o=="object"){let{code:t,message:s}=o;return{code:typeof t=="string"?t:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Bt(i){return new k(i)}var _=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 F(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function Wt(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function Gt(i,e){let r=i.getTracks();if(r.length===1&&r[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function C(i,e){for(let r of[...i.lostListeners])try{r(e)}catch{}}var T=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,r){return this.enqueue(async()=>{let o=this.claims.get(e);o&&(this.claims.delete(e),o.released=!0,o.track=null,o.stream=null,C(o,new Error(`${e} capture claim superseded by a newer claim`)));let t=this.createState(e,r);return this.claims.set(e,t),await this.converge(t),t.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let r=this.queue.then(e);return this.queue=r.then(()=>{},()=>{}),r}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new _;return r=>e.getUserMedia(r)}async converge(e){for(let n of this.claims.values())n.track&&(n.track.stop(),n.track=null,n.stream=null);if(this.claims.size===0)return;let r=this.resolveGetUserMedia(),o={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},t;try{t=await r(o)}catch(n){let c=`one-capture getUserMedia(${F(o)}) failed`,a=n instanceof Error?n.message:String(n);for(let l of[...this.claims.values()])if(this.claims.delete(l.kind),l.released=!0,l!==e){let d=new Error(`${c} \u2014 ${l.kind} capture lost: ${a||n}`);d.cause=n,C(l,d)}throw n}let s=[...this.claims.values()].sort((n,c)=>n===e?1:c===e?-1:0);for(let n of s){let c=Wt(t,n.kind)[0]??null;if(n.released){c?.stop();continue}if(!c){this.claims.delete(n.kind),n.released=!0;let a=Object.assign(new Error(`one-capture getUserMedia(${F(o)}) returned no ${n.kind} track`),{name:"NotFoundError"});if(n===e)throw a;C(n,a);continue}if(n.track=c,n.stream=Gt(t,c),n!==e)for(let a of[...n.trackListeners])try{a(c,n.stream)}catch{}}}createState(e,r){let o=this,t={kind:e,constraints:r,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return t.track},get stream(){return t.stream},update(s){return o.enqueue(async()=>{if(t.released)throw new Error(`${e} capture claim already released`);if(t.constraints=s,await o.converge(t),!t.track)throw new Error(`${e} capture update yielded no track`);return t.track})},release(){t.released||(t.released=!0,o.claims.get(e)===t&&o.claims.delete(e),t.track?.stop(),t.track=null,t.stream=null)},onTrack(s){return t.trackListeners.add(s),()=>t.trackListeners.delete(s)},onLost(s){return t.lostListeners.add(s),()=>t.lostListeners.delete(s)}}};return t}},jt=null;function $t(){return jt??=new T}var B="input",qt=30;function Vt(i){let e=i.now??Date.now,r=i.field??B,o=1e3/Math.max(i.hz??30,.001),t=new Set,s=0,n=0,c=0,a=0,l,d=null,f=!1,p=()=>{if(f)return;l=e(),a+=1;let u={keys:[...t],buttons:s,pointer:{x:n,y:c},seq:a,at:l};try{i.awareness.setLocalStateField(r,u)}catch{}},m=()=>{if(f)return;let u=e();if(l===void 0||u-l>=o){d&&(clearTimeout(d),d=null),p();return}if(d)return;let g=Math.max(o-(u-l),0);d=setTimeout(()=>{d=null,p()},g),d.unref?.()};return{keyDown(u){let g=String(u).toLowerCase();t.has(g)||(t.add(g),m())},keyUp(u){let g=String(u).toLowerCase();t.delete(g)&&m()},setButtons(u){let g=Number.isFinite(u)?Number(u):0;g!==s&&(s=g,m())},movePointer(u,g){let h=Number.isFinite(u)?Number(u):0,E=Number.isFinite(g)?Number(g):0;h===0&&E===0||(n+=h,c+=E,m())},heldKeys(){return[...t]},clear(){f||(t.clear(),s=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(f)return;let u=t.size>0||s!==0;t.clear(),s=0,d&&(clearTimeout(d),d=null),u&&p(),f=!0}}}var zt=1024,Kt=.92,Ht=262144,Yt=256e3,A=[.9,.8,.7,.6,.5],W=.8,Xt=8;function I(i,e,r){if(!(i>0)||!(e>0))throw new Error(`reference image has no pixels (${i}x${e})`);let o=Math.min(1,r/Math.max(i,e));return{width:Math.max(1,Math.round(i*o)),height:Math.max(1,Math.round(e*o))}}async function Jt(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 j(i,e,r){let o=await new Promise(t=>{i.toBlob(t,e,e==="image/jpeg"?r:void 0)});if(!o)throw new Error(`could not encode the reference image as ${e}`);return o}function G(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 P(i,e,r,o,t){let s=document.createElement("canvas");s.width=e,s.height=r;let n=s.getContext("2d");if(!n)throw new Error("could not prepare the reference image (no 2d canvas context)");return o==="image/jpeg"&&(n.fillStyle="#fff",n.fillRect(0,0,e,r)),n.drawImage(i,0,0,e,r),await j(s,o,t)}async function Zt(i,e,r,o){let{width:t,height:s}=e,n=await P(i,t,s,r,o);if(n.size<=256e3)return{blob:n,width:t,height:s};if(r==="image/jpeg"){for(let a of A)if(!(a>=o)&&(n=await P(i,t,s,r,a),n.size<=256e3))return G(`quality ${o} -> ${a}`,n.size),{blob:n,width:t,height:s}}let c=r==="image/jpeg"?A[A.length-1]:o;for(let a=0;a<Xt;a++)if(t=Math.max(16,Math.round(t*W)),s=Math.max(16,Math.round(s*W)),n=await P(i,t,s,r,c),n.size<=256e3)return G(`downscaled to ${t}x${s} @ q${c}`,n.size),{blob:n,width:t,height:s};throw new Error(`this image cannot be sent: even at ${t}x${s} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function Qt(i,e){let{maxSize:r=1024,type:o="image/jpeg",quality:t=.92,source:s}=e,n=await Jt(i);try{let c=I(n.width,n.height,r),a=await Zt(n,c,o,t);return{bytes:new Uint8Array(await a.blob.arrayBuffer()),type:o,width:a.width,height:a.height,source:s}}finally{n.close()}}function er(i){let e=i instanceof Error?i.name:"",r=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(r)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(r)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(r)?"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 tr(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function rr(i,e){let r=i.videoWidth,o=i.videoHeight;if(!(r>0)||!(o>0))throw new Error("the camera has not shown a frame yet");let{maxSize:t=1024,type:s="image/jpeg",quality:n=.92}=e??{},c=I(r,o,t),a=document.createElement("canvas");a.width=c.width,a.height=c.height;let l=a.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,c.width,c.height)),l.drawImage(i,0,0,c.width,c.height);let d=await j(a,s,n);return{bytes:new Uint8Array(await d.arrayBuffer()),type:s,width:c.width,height:c.height,source:"camera"}}var nr=new Set(["w","a","s","d"]),b=(i,e)=>Math.min(e,Math.max(-e,i));function ir(i={}){let{panPerPixel:e=9e-4,zoomPerSecond:r=.35,strafePerSecond:o=.18,decayTauMs:t=900,frameRelax:s=.06,maxPan:n=.12,maxLogZoom:c=.22}=i,a=0,l=0,d=0,f=null,p=new Set;return{pointerDelta(m,u){a=b(a-m*e,n),l=b(l-u*e,n)},keyDown(m){let u=m.toLowerCase();nr.has(u)&&p.add(u)},keyUp(m){p.delete(m.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let m=1-s;a*=m,l*=m,d*=m},tick(m){if(f===null){f=m;return}let u=Math.max(0,Math.min(100,m-f))/1e3;f=m,p.has("w")&&(d=b(d+r*u,c)),p.has("s")&&(d=b(d-r*u,c)),p.has("a")&&(a=b(a+o*u,n)),p.has("d")&&(a=b(a-o*u,n));let g=Math.exp(-u*1e3/t);a*=g,l*=g,d*=g},transform(){return{translateX:a,translateY:l,scale:Math.exp(d)}},isIdentity(m=5e-4){return Math.abs(a)<m&&Math.abs(l)<m&&Math.abs(d)<m},reset(){a=0,l=0,d=0,p.clear()}}}export{me as ACTIVATION_COLD_BOOT_AFTER_MS,ge as ACTIVATION_DEGRADED_AFTER_MS,he as ACTIVATION_HINT_PATH,pe as ACTIVATION_STILL_AFTER_MS,rt as ACTIVITY_DOM_EVENTS,Qe as ACTIVITY_FIELD,tt as ACTIVITY_STAMP_MIN_INTERVAL_MS,be as ActivationMonitor,It as App,Ee as BACKOFF_BASE_MS,we as BACKOFF_MAX_ATTEMPTS,ve as BACKOFF_MAX_MS,de as COLD_BOOT_WHEN_LIVE_TIMEOUT_MS,T as CaptureController,_ as CaptureUnavailableError,S as ClientTokenError,k as CreditsClient,y as CreditsError,v as CreditsUnauthorizedError,Ht as DATA_CHANNEL_MESSAGE_CEILING,Rt as DEFAULT_DOC_SYNC_TIMEOUT_MS,D as DEFAULT_GATEWAY_URL,J as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Kt as DEFAULT_REFERENCE_JPEG_QUALITY,zt as DEFAULT_REFERENCE_MAX_SIZE,ce as DEFAULT_WHEN_LIVE_TIMEOUT_MS,ze as DERIVED_LEG_SEP,ht as DGRAM_HEADER_BYTES,ot as FOCUS_FIELD,ct as FOREGROUND_COALESCE_MS,bt as FrameReassembler,Xe as GENERATION_TICK_EMIT_INTERVAL_MS,Je as GENERATION_TICK_MAX_EXTRAPOLATION_MS,qt as INPUT_PRESENCE_DEFAULT_HZ,B as INPUT_PRESENCE_FIELD,Fe as InvalidDurationError,Se as LEGACY_ACTIVATION_HINT_PATH,fe as PLATFORM_DOC_NAME,Ne as PermanentLockedError,Ue as PinRequiresActiveTempError,at as PresenceTracker,Z as ProduceAckTimeoutError,De as RecordingNotFoundError,Ge as RecordingsClient,Me as RecordingsError,Oe as RecordingsUnauthorizedError,Q as RequestAbortError,ee as RequestCancelledError,Y as RequestDocSyncError,K as RequestError,H as RequestTimeoutError,Le as RetainNotTempError,Ae as RuntimeArtifactNotFoundError,Ie as RuntimeArtifactsClient,Re as RuntimeArtifactsError,Ce as RuntimeArtifactsUnauthorizedError,Ye as SIGNALING_PROTOCOL_VERSION,$e as STREAM_END,Ct as Session,oe as SessionAllocationError,At as SessionDirectory,z as SessionDirectoryError,V as SessionEndError,q as SessionEndUnavailableError,re as SessionFailedError,X as StreamDirectionConflict,_t as TransportNegotiator,ie as TransportSessionMismatchError,Tt as TransportSessionSignaling,L as URUN_DEV_ENV,it as USER_ACTIVITY_FIELD,st as USER_ACTIVITY_MIN_INTERVAL_MS,et as VISIBILITY_FIELD,Yt as WIRE_MESSAGE_BUDGET,mt as WT_CONTROL_FRAME_MAX,Et as WT_DATA_STREAM_VERSION,xt as WebRtcSession,kt as WebTransportSession,ft as WtControlDecoder,vt as WtDataStreamParser,ye as activationHintFrom,tr as cameraCaptureAvailable,rr as captureStillFromVideo,ke as computeBackoffDelay,wt as consumeWtDataStreams,nt as createActivityTracker,ir as createCameraWarp,Ot as createClientToken,Bt as createCreditsClient,Vt as createInputPresencePublisher,je as createRecordingsClient,Pe as createRuntimeArtifactsClient,Dt as createStore,Ve as decodeStreamEnvelope,He as derivedLegName,Ke as derivedLegRole,te as describeSessionFailure,le as describeSessionPhase,qe as encodeStreamEnvelope,gt as encodeWtControlFrame,I as fitWithin,Be as isDurationString,ae as isPausedPhase,Nt as isPendingRecording,_e as isRetryableSessionError,se as isWakingPhase,pt as mediaRecorderChunkSource,Qt as normalizeReferenceImage,We as normalizeRetention,lt as observeLeaveConfirm,dt as observePageLifecycle,ut as observePageTeardown,St as parseDgramHeader,xe as prewake,er as referenceImageErrorMessage,Te as releaseSessionBeacon,Pt as sessionDirectory,ne as sessionFailureFromMediaError,$t as sharedCaptureController,Ut as videoStream,Ze as watchGenerationTick,ue as whenLive,yt as writeDgramHeader};