@urun-sh/core 0.6.46 → 0.6.48

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/internal.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 I,A as j,B as L,F as B,N as H,Y as E,a as $,aa as T,b as q,ba as G,ca as Q,da as Y,ia as F,ja as z,ka as v,la as R,ma as J,na as w,oa as K,y as P,z as N}from"./chunk-AWZWSK77.mjs";import"./chunk-NLAOQUYQ.mjs";var A=["inflight","progress","responses","tokens"],V=6e4;function O(n,e){if(n===null||typeof n!="object"||!(e in n))return!1;let t=Reflect.get(n,e);return t===null||typeof t!="object"||!("status"in t)?!1:t.status==="done"||t.status==="error"}function p(n,e,t=6e4){n.delete(["requests",e]);let r=()=>{for(let i of A)n.delete([i,e])};if(O(n.get("inflight"),e)){r();return}let s=()=>{},o=n.on("change",i=>{O(i.inflight,e)&&(o(),s(),r())}),l=setTimeout(o,t);s=()=>clearTimeout(l),typeof l=="object"&&"unref"in l&&l.unref()}var X="llm",Z="llm-resp",k=class{items=[];waiters=[];closed=!1;push(e){this.items.push(e),e===null&&(this.closed=!0);for(let t of this.waiters.splice(0))t()}async*drain(){for(;;){for(;this.items.length>0;){let e=this.items.shift();if(e==null)return;yield e}if(this.closed)return;await new Promise(e=>this.waiters.push(e))}}};function U(n,e){if(n){let t=n.message;if(typeof t=="string"&&t.length>0)return t;let r=n.code??n.type??n.error;if(typeof r=="string"&&r.length>0)return`serve error: ${r}`;let s=JSON.stringify(n);if(s&&s!=="{}")return`serve error: ${s.slice(0,300)}`}return e??"serve error"}var C=class{constructor(e){this.opts=e;if(this.wsCtor=e.WebSocketPolyfill??globalThis.WebSocket,!this.wsCtor)throw new Error("[hub-serve] no WebSocket implementation (pass ws in Node)");this.consumerId=e.consumerId??`serve-client-${Math.random().toString(36).slice(2,10)}`,this.grantQuery=`token=${encodeURIComponent(e.attach.token)}&gen=${e.attach.gen}`;let t=R({serverUrl:v(this.sfuWsUrl()),sessionId:e.sessionId,attach:{url:e.sfuUrl,token:e.attach.token,gen:e.attach.gen},WebSocketPolyfill:this.wsCtor}),r=(s,o,l)=>(this.docConnection=t(s,o,l),this.docConnection);this.doc=new w(X,e.sessionId,r)}opts;doc;docConnection;wsCtor;grantQuery;consumerId;streamSockets=new Set;async ready(e=3e4){this.doc.synced||await new Promise((t,r)=>{let s=setTimeout(()=>r(new Error("[hub-serve] doc sync timeout")),e);this.doc.onSynced(()=>{clearTimeout(s),t()})})}request(e){let t=`req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,r=`${Z}:${t}`,s=e.stream!==!1,o={request_id:t,consumer_id:this.consumerId,respond_on:r,stream:s};e.model&&(o.model=e.model),e.messages!==void 0?(o.kind="chat",o.messages=e.messages):(o.kind="responses",o.input=e.input),e.instructions!==void 0&&(o.instructions=e.instructions),e.temperature!==void 0&&(o.temperature=e.temperature),e.max_output_tokens!==void 0&&(o.max_output_tokens=e.max_output_tokens);let l=`${this.sfuWsUrl()}/stream/${encodeURIComponent(this.opts.sessionId)}/${encodeURIComponent(r)}?${this.grantQuery}`,i=new this.wsCtor(l);this.streamSockets.add(i),i.addEventListener?.("close",()=>this.streamSockets.delete(i));let h=new k,b,f,_=new Promise((S,c)=>{b=S,f=c});_.catch(()=>{});let W=new T,g,m,d,D=!1,M=()=>{try{p(this.doc,t)}catch{}},y=()=>{D||(D=!0,h.push(null),M(),g!==void 0?b(g):f(m!==void 0?new Error(U(m,d)):d!==void 0?new Error(d):new Error("[hub-serve] the response lane ended without a terminal response")))};return this.doc.set({requests:{[t]:{payload:o,consumer_id:this.consumerId,stream:s}}}),i.onmessage=S=>{let c=S.data,x=c instanceof ArrayBuffer?new Uint8Array(c):c instanceof Uint8Array?c:new Uint8Array(c.buffer,c.byteOffset,c.byteLength),u;try{u=I(x)}catch{if(u=W.feed(x),u===void 0)return}if(u===E){y();return}let a=u;a&&typeof a=="object"&&typeof a.t=="string"&&(a.t==="delta"&&typeof a.delta=="string"?h.push(a.delta):a.t==="response"?g=a.body??{}:a.t==="error"&&(m=a,d=U(m,void 0)))},i.onerror=()=>{d??="response lane socket error",y()},i.onclose=()=>{d??="response lane closed before the terminal",y()},{requestId:t,lane:r,deltas:h.drain(),result:_,cancel:()=>{p(this.doc,t)}}}async destroy(){for(let e of this.streamSockets)try{e.close()}catch{}this.streamSockets.clear();try{this.doc.disconnect()}catch{}this.docConnection?.destroy()}sfuWsUrl(){return this.opts.sfuUrl.replace(/^http/,"ws").replace(/\/+$/,"")}};export{$ as ChannelMultiplexer,z as DOC_SYNC_WIRE_CONTRACT_VERSION,q as DeferredChannelMultiplexer,J as DeferredDocConnector,C as HubServeClient,G as LoopbackStreamData,V as RECORD_GC_WAIT_MS,A as REQUEST_RECORD_ROOTS,w as SessionDocumentImpl,F as TransportSession,H as allocateSession,B as computeBackoffDelay,K as createPresence,R as createWebsocketDocConnector,v as deriveYjsServerUrl,L as ensureNodeWebRTC,p as gcRequest,P as isNodeRuntime,N as nodeMediasoupHandlerName,j as nodeWebRTCUnavailableReason,Y as streamDataLabel,Q as transportStreamData};
2
+ import{$ as I,A as j,B as L,F as B,N as H,Y as E,a as $,aa as T,b as q,ba as G,ca as Q,da as Y,ia as F,ja as z,ka as v,la as R,ma as J,na as w,oa as K,y as P,z as N}from"./chunk-C76RGBCP.mjs";import"./chunk-NLAOQUYQ.mjs";var A=["inflight","progress","responses","tokens"],V=6e4;function O(n,e){if(n===null||typeof n!="object"||!(e in n))return!1;let t=Reflect.get(n,e);return t===null||typeof t!="object"||!("status"in t)?!1:t.status==="done"||t.status==="error"}function p(n,e,t=6e4){n.delete(["requests",e]);let r=()=>{for(let i of A)n.delete([i,e])};if(O(n.get("inflight"),e)){r();return}let s=()=>{},o=n.on("change",i=>{O(i.inflight,e)&&(o(),s(),r())}),l=setTimeout(o,t);s=()=>clearTimeout(l),typeof l=="object"&&"unref"in l&&l.unref()}var X="llm",Z="llm-resp",k=class{items=[];waiters=[];closed=!1;push(e){this.items.push(e),e===null&&(this.closed=!0);for(let t of this.waiters.splice(0))t()}async*drain(){for(;;){for(;this.items.length>0;){let e=this.items.shift();if(e==null)return;yield e}if(this.closed)return;await new Promise(e=>this.waiters.push(e))}}};function U(n,e){if(n){let t=n.message;if(typeof t=="string"&&t.length>0)return t;let r=n.code??n.type??n.error;if(typeof r=="string"&&r.length>0)return`serve error: ${r}`;let s=JSON.stringify(n);if(s&&s!=="{}")return`serve error: ${s.slice(0,300)}`}return e??"serve error"}var C=class{constructor(e){this.opts=e;if(this.wsCtor=e.WebSocketPolyfill??globalThis.WebSocket,!this.wsCtor)throw new Error("[hub-serve] no WebSocket implementation (pass ws in Node)");this.consumerId=e.consumerId??`serve-client-${Math.random().toString(36).slice(2,10)}`,this.grantQuery=`token=${encodeURIComponent(e.attach.token)}&gen=${e.attach.gen}`;let t=R({serverUrl:v(this.sfuWsUrl()),sessionId:e.sessionId,attach:{url:e.sfuUrl,token:e.attach.token,gen:e.attach.gen},WebSocketPolyfill:this.wsCtor}),r=(s,o,l)=>(this.docConnection=t(s,o,l),this.docConnection);this.doc=new w(X,e.sessionId,r)}opts;doc;docConnection;wsCtor;grantQuery;consumerId;streamSockets=new Set;async ready(e=3e4){this.doc.synced||await new Promise((t,r)=>{let s=setTimeout(()=>r(new Error("[hub-serve] doc sync timeout")),e);this.doc.onSynced(()=>{clearTimeout(s),t()})})}request(e){let t=`req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,r=`${Z}:${t}`,s=e.stream!==!1,o={request_id:t,consumer_id:this.consumerId,respond_on:r,stream:s};e.model&&(o.model=e.model),e.messages!==void 0?(o.kind="chat",o.messages=e.messages):(o.kind="responses",o.input=e.input),e.instructions!==void 0&&(o.instructions=e.instructions),e.temperature!==void 0&&(o.temperature=e.temperature),e.max_output_tokens!==void 0&&(o.max_output_tokens=e.max_output_tokens);let l=`${this.sfuWsUrl()}/stream/${encodeURIComponent(this.opts.sessionId)}/${encodeURIComponent(r)}?${this.grantQuery}`,i=new this.wsCtor(l);this.streamSockets.add(i),i.addEventListener?.("close",()=>this.streamSockets.delete(i));let h=new k,b,f,_=new Promise((S,c)=>{b=S,f=c});_.catch(()=>{});let W=new T,g,m,d,D=!1,M=()=>{try{p(this.doc,t)}catch{}},y=()=>{D||(D=!0,h.push(null),M(),g!==void 0?b(g):f(m!==void 0?new Error(U(m,d)):d!==void 0?new Error(d):new Error("[hub-serve] the response lane ended without a terminal response")))};return this.doc.set({requests:{[t]:{payload:o,consumer_id:this.consumerId,stream:s}}}),i.onmessage=S=>{let c=S.data,x=c instanceof ArrayBuffer?new Uint8Array(c):c instanceof Uint8Array?c:new Uint8Array(c.buffer,c.byteOffset,c.byteLength),u;try{u=I(x)}catch{if(u=W.feed(x),u===void 0)return}if(u===E){y();return}let a=u;a&&typeof a=="object"&&typeof a.t=="string"&&(a.t==="delta"&&typeof a.delta=="string"?h.push(a.delta):a.t==="response"?g=a.body??{}:a.t==="error"&&(m=a,d=U(m,void 0)))},i.onerror=()=>{d??="response lane socket error",y()},i.onclose=()=>{d??="response lane closed before the terminal",y()},{requestId:t,lane:r,deltas:h.drain(),result:_,cancel:()=>{p(this.doc,t)}}}async destroy(){for(let e of this.streamSockets)try{e.close()}catch{}this.streamSockets.clear();try{this.doc.disconnect()}catch{}this.docConnection?.destroy()}sfuWsUrl(){return this.opts.sfuUrl.replace(/^http/,"ws").replace(/\/+$/,"")}};export{$ as ChannelMultiplexer,z as DOC_SYNC_WIRE_CONTRACT_VERSION,q as DeferredChannelMultiplexer,J as DeferredDocConnector,C as HubServeClient,G as LoopbackStreamData,V as RECORD_GC_WAIT_MS,A as REQUEST_RECORD_ROOTS,w as SessionDocumentImpl,F as TransportSession,H as allocateSession,B as computeBackoffDelay,K as createPresence,R as createWebsocketDocConnector,v as deriveYjsServerUrl,L as ensureNodeWebRTC,p as gcRequest,P as isNodeRuntime,N as nodeMediasoupHandlerName,j as nodeWebRTCUnavailableReason,Y as streamDataLabel,Q as transportStreamData};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urun-sh/core",
3
- "version": "0.6.46",
3
+ "version": "0.6.48",
4
4
  "description": "Core transport and channel primitives for the urun TypeScript SDK",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,30 +0,0 @@
1
- import { createRequire as __urunCreateRequire } from 'node:module'; const require = globalThis.require ?? __urunCreateRequire(import.meta.url);
2
- import{$ as Lt,B as de,H as le,I as wt,J as bt,K as Ne,L as Fe,M as yt,N as kt,O as St,P as _t,Q as $e,R as Tt,S as At,T as Rt,V as Et,W as ce,Y as Dt,b as oe,c as X,ca as Wt,d as ht,e as Pe,f as Me,g as pt,h as ft,i as mt,ia as ue,ka as he,l as xe,la as Ut,m as gt,ma as It,na as Ct,oa as Pt,r as Y,s as Oe,w as vt,y as ae}from"./chunk-AWZWSK77.mjs";var Nr=15e3,Fr=45e3,$r=12e4,qe="platform",Mt="activation",xt="desired.activation";function Sn(i){if(typeof i=="string"&&i.length>0)return i;if(i&&typeof i=="object"){let e=i.note;if(typeof e=="string"&&e.length>0)return e}}var _n=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],pe=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let n of this._watches.values())this._arm(n)}}else(t?.name==="error"||t?.name==="paused")&&this._park()})}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;_park(){this._liveAt=null;for(let e of this._watches.values())if(!e.done){for(let t of e.timers)clearTimeout(t);e.timers=[],e.startedAt=null,e.lastEvent=null}}watch(e,t){if(this._stopped||this._watches.has(e))return;let n={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,n),this._hookFirstMediaSignals(n),!n.done&&this._liveAt!==null&&this._arm(n)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=n=>{if(!(!n||e.done)){if(n.muted===!0&&typeof n.addEventListener=="function"){let r=()=>this._firstMedia(e);n.addEventListener("unmute",r,{once:!0}),e.cleanups.push(()=>n.removeEventListener?.("unmute",r));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",n=>t(n))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of _n){let n=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);n.unref?.(),e.timers.push(n)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,n){let r={state:t,elapsedMs:n,stream:e.name},s=Sn(this._options.hint());s!==void 0&&(r.hint=s),e.lastEvent=r;for(let o of Array.from(this._handlers))o(r)}};var O=class extends Error{status;code;constructor(e,t,n=t>0?`http_${t}`:"runtime_artifacts_error",r){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=n,r!==void 0&&(this.cause=r),Object.setPrototypeOf(this,new.target.prototype)}},He=class extends O{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Be=class extends O{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function ee(i){return{baseUrl:i.baseUrl,fallbackUrls:i.fallbackUrls,orgId:i.orgId,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}function Br(i){return new J(i)}var J=class{_options;constructor(e){this._options=e}async list(e){let n=Nt(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new O("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map(Ot)}async getDownloadUrl(e,t){let n=Nt(await this._request(t,`/${encodeURIComponent(e)}/download`)),r=n.download_url;if(typeof r!="string"||!An(r))throw new O("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Ot(n.artifact),downloadUrl:r}}async _request(e,t){let n=wt(this._options.baseUrl,this._options.fallbackUrls),r=null;for(let s of n)try{return await this._requestFromBase(s,e,t)}catch(o){if(r=o instanceof Error?o:new Error(String(o)),r instanceof O&&Rn(r.status))throw r}throw r??new O("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let r=`${le(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${n}`,s=await this._resolveToken(),o=await fetch(r,{method:"GET",headers:this._headers(s)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await fetch(r,{method:"GET",headers:this._headers(s)}))}if(!o.ok){let{code:a,message:d}=await this._readError(o,e);throw En(o.status,a,d)}try{return await o.json()}catch(a){throw new O(`[urun] runtime artifacts: invalid JSON response from ${le(e)}`,0,"bad_response",a)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let n=le(t);try{let s=(await e.json()).error;if(s&&typeof s=="object"){let{code:o,message:a}=s;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${n}: ${a}`:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}};function Ot(i){if(!i||typeof i!="object")throw new O("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=i,t=j(e,"artifact_id")||j(e,"id"),n=j(e,"filename"),r=j(e,"kind"),s=j(e,"status")||"ready",o=Tn(e,"size_bytes"),a=j(e,"sha256");if(!t||!n||!r||o==null||!a)throw new O("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:r,filename:n,contentType:j(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:s,createdAt:j(e,"created_at"),expiresAt:j(e,"expires_at")}}function j(i,e){let t=i[e];return typeof t=="string"&&t.length>0?t:void 0}function Tn(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function An(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function Rn(i){return i===401||i===403}function En(i,e,t){return i===401?new He(t,e):i===404?new Be(t,e):new O(t,i,e)}function Nt(i){if(!i||typeof i!="object"||Array.isArray(i))throw new O("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var q=class extends Error{status;code;constructor(e,t){super(e),this.name="RecordingsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},fe=class extends q{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},je=class extends q{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Ve=class extends q{constructor(e="[urun] recordings: retain requires a temp recording",t="retain_not_temp"){super(e,{status:409,code:t}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},Ke=class extends q{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},Ge=class extends q{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},te=class extends q{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",n=400){super(e,{status:n,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function Ft(i){return/^(\d+[smhdw])+$/.test(i)}function Vr(i){if(i==="pin")return{action:"pin"};if(Ft(i))return{action:"retain",duration:i};throw new te(`[urun] recordings: "${i}" is not a duration or "pin"`)}function Dn(i,e,t){let n=t||e||`HTTP ${i}`;if(i===401)return new fe(n,e??"unauthorized");if(i===404)return new je(n,e??"not_found");if(i===400)return new te(n,e??"bad_request",400);if(i===409)switch(e){case"retain_not_temp":return new Ve(n,e);case"pin_requires_active_temp":return new Ke(n,e);case"permanent_locked":return new Ge(n,e)}return new q(n,{status:i,code:e??`http_${i}`})}var ne=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let n=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(n)?n:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!Ft(t))throw new te(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new q("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let r=this._buildUrl(t,n.params),s=await this._resolveToken(),o=await this._fetch(r,e,s,n.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await this._fetch(r,e,s,n.body))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw Dn(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let n=`${this._base}${e}`,r=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return r&&(n+=`?${r}`),n}_fetch(e,t,n,r){let s={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:s};return r!==void 0&&(s["Content-Type"]="application/json",o.body=JSON.stringify(r)),fetch(e,o)}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 fe("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let n=(await e.json()).error;if(n&&typeof n=="object"){let{code:r,message:s}=n;return{code:typeof r=="string"?r:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Kr(i){return new ne(i)}var Qr=1e3,Yr=12e3;function $t(i,e,t={}){let n=null,r=0,s=0,o=null,a=-1,d=()=>{let p=i.get("desired.billing.generationSeconds");if(typeof p!="number"||!Number.isFinite(p)||p<=0)return null;let v=i.get("desired.billing.epoch"),w=i.get("desired.billing.updatedAtMs");return{seconds:p,epoch:typeof v=="number"&&Number.isFinite(v)?v:0,updatedAtMs:typeof w=="number"&&Number.isFinite(w)?w:null}},l=()=>{if(n===null)return null;let p=Math.min(Math.max(0,Date.now()-r),s);return n+p/1e3},c=()=>{let p=t.creditsPerSecond;if(typeof p=="number"&&Number.isFinite(p)&&p>0)return p;let v=i.get("desired.billing.creditsPerSecond");return typeof v=="number"&&Number.isFinite(v)&&v>0?v:null},u=()=>{let p=l();if(p===null)return;let v=Math.floor(p);if(v<=a)return;a=v;let w={seconds:v},R=c();R!==null&&(w.estimatedCredits=v*R),e(w)},h=p=>{r=Date.now();let v=p===null?0:Math.max(0,r-p);s=Math.max(0,12e3-v)},m=()=>{let p=d();if(p!==null){if(o!==null&&p.epoch!==o){o=p.epoch,n=p.seconds,a=-1,h(p.updatedAtMs),u();return}n!==null&&p.seconds<=n||(o=p.epoch,n=p.seconds,h(p.updatedAtMs),u())}};m();let g=i.on("change",m),S=setInterval(u,1e3);return S.unref?.(),()=>{clearInterval(S),g()}}var Ln="activity",Wn="visibility",Xr=15e3,qt=["pointerdown","pointermove","keydown","wheel","touchstart"];function Ht(i){let e=i.now??Date.now,t=i.mode==="explicit",n=t?null:i.windowTarget!==void 0?i.windowTarget:typeof window<"u"?window:null,r=t?null:i.documentTarget!==void 0?i.documentTarget:typeof document<"u"?document:null,s=!1,o,a=()=>{if(s)return;let h=e();if(!(o!==void 0&&h-o<15e3)){o=h;try{i.awareness.setLocalStateField(Ln,{at:h})}catch{}}},d=()=>{if(!(s||!r||r.visibilityState===void 0))try{i.awareness.setLocalStateField(Wn,r.visibilityState)}catch{}},l=()=>a(),c=()=>{d(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&a()};if(n)for(let h of qt)n.addEventListener(h,l,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",c);let u=null;return!t&&i.isProducing&&(u=setInterval(()=>{if(!s)try{i.isProducing?.()&&a()}catch{}},15e3),u.unref?.()),a(),d(),{touch:a,dispose(){if(!s){if(s=!0,n)for(let h of qt)n.removeEventListener(h,l,{capture:!0});r&&r.removeEventListener("visibilitychange",c),u&&(clearInterval(u),u=null)}}}}var Un="user_activity",In="focus",Zr=3e4;function Bt(i){switch(i){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var me=class{_awareness;_now;_win;_state="idle";_stateHandlers=new Set;_transportUnsubs=new Set;_disposed=!1;_counts={typing:0,pointer:0,tty:0,consumer_reads:0};_inflight=0;_visibility;_focus;_lastSignalAt;_lastPublishedAt;_trailing=null;_onWindowFocus=null;_onWindowBlur=null;constructor(e={}){this._awareness=e.awareness??null,this._now=e.now??Date.now,this._win=e.windowTarget!==void 0?e.windowTarget:typeof window<"u"?window:null;let t=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null;this._win&&t&&typeof t.hasFocus=="function"&&(this._onWindowFocus=()=>this.setFocus("focused"),this._onWindowBlur=()=>this.setFocus("unfocused"),this._win.addEventListener("focus",this._onWindowFocus),this._win.addEventListener("blur",this._onWindowBlur),this.setFocus(t.hasFocus()?"focused":"unfocused"))}get state(){return this._state}onState(e){return this._stateHandlers.add(e),()=>this._stateHandlers.delete(e)}transportConnecting(){this._setState("connecting")}transportReady(){this._setState("ready")}transportClosed(){this._setState("transient_failure")}attachTransport(e){if(this._disposed)return()=>{};this._setState(Bt(e.state));let t=e.on("stateChange",r=>{this._setState(Bt(r))}),n=()=>{t(),this._transportUnsubs.delete(n)};return this._transportUnsubs.add(n),n}_setState(e){if(!(this._disposed||e===this._state)){this._state=e;for(let t of this._stateHandlers)try{t(e)}catch{}}}interaction(e,t=1){this._disposed||!Number.isFinite(t)||t<=0||e==="pointer"&&this._focus==="unfocused"||(this._counts[e]+=t,this._signal())}consumerRead(e=1){this._disposed||!Number.isFinite(e)||e<=0||(this._counts.consumer_reads+=e,this._signal())}get inflight(){return this._inflight}workBegin(){if(this._disposed)return()=>{};this._inflight+=1,this._inflight===1&&this._publishNow();let e=!1;return()=>{e||this._disposed||(e=!0,this._inflight-=1,this._inflight===0&&this._publishNow())}}setVisibility(e){this._disposed||(this._visibility=e)}setFocus(e){if(!(this._disposed||e===this._focus)){this._focus=e;try{this._awareness?.setLocalStateField(In,e)}catch{}}}_signal(){this._lastSignalAt=this._now();let e=this._lastPublishedAt===void 0?1/0:this._lastSignalAt-this._lastPublishedAt;if(e>=3e4){this._publishNow();return}if(this._trailing)return;let t=Math.max(3e4-e,0);this._trailing=setTimeout(()=>{this._trailing=null,this._disposed||this._publishNow()},t),this._trailing.unref?.()}_publishNow(){this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._lastPublishedAt=this._now();let e={at:this._lastSignalAt??this._lastPublishedAt,counts:{...this._counts},inflight:this._inflight};this._visibility!==void 0&&(e.visibility=this._visibility),this._focus!==void 0&&(e.focus=this._focus);try{this._awareness?.setLocalStateField(Un,e)}catch{}}dispose(){if(!this._disposed){for(let e of Array.from(this._transportUnsubs))e();this._transportUnsubs.clear(),this._win&&(this._onWindowFocus&&this._win.removeEventListener("focus",this._onWindowFocus),this._onWindowBlur&&this._win.removeEventListener("blur",this._onWindowBlur)),this._onWindowFocus=null,this._onWindowBlur=null,this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._state="idle",this._stateHandlers.clear(),this._disposed=!0}}};var ti=250;function jt(i){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let n=Date.now();n-e<250||(e=n,i())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function Vt(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=n=>{n.persisted||e||(e=!0,i())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function Kt(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{i()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var Gt="video/mp4";function Qt(i,e={}){let t=e.timesliceMs??1e3,n=null,r=null,s=!1,o=(a,d,l)=>{let c=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!c)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let u=e.mimeType??(typeof c.isTypeSupported=="function"&&c.isTypeSupported(Gt)?Gt:void 0),h=new MediaStream([a]),m=new c(h,u?{mimeType:u}:void 0);n=m;let g=Promise.resolve();m.ondataavailable=S=>{let p=S.data;s||!p||p.size===0||(g=g.then(async()=>{let v=new Uint8Array(await p.arrayBuffer());s||d(v)}))},m.onstop=()=>{g.then(()=>{s||l()})},m.onerror=()=>{g.then(()=>{s||l()})},m.start(t)};return{start(a,d){if(n||s)return;let l=i.track();if(l){o(l,a,d);return}r=i.onTrack(c=>{!c||n||s||(r?.(),r=null,o(c,a,d))})},stop(){if(s)return;s=!0,r?.(),r=null;let a=n;if(n=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Cn(i){let e=i;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=i.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function Yt(i,e){let t=null,n=!1,r=!1,s=new ReadableStream({pull(o){n||(n=!0,t=i(e),t.start(a=>{if(!r)try{o.enqueue(a)}catch{}},()=>{if(!r){r=!0;try{o.close()}catch{}}}))},cancel(){r=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Cn(s)}import{encode as Pn,decode as Mn}from"@msgpack/msgpack";var xn=65536;function zt(i){let e=Pn(i),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var ge=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(n>xn)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+n)break;let r=this.buf.subarray(4,4+n);this.buf=this.buf.subarray(4+n),t.push(Object.assign(Mn(r),{raw:r}))}return t}};function Xt(i,e){let t=new DataView(i.buffer,i.byteOffset,i.byteLength),n=t.getUint8(0),r=(n&240)===128,s=n===222;if(!r&&!s&&!(n===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let a=r?n&15:s?t.getUint16(1,!1):t.getUint32(1,!1),d=r?1:s?3:5,l=[];l.push(i.subarray(0,d));for(let m=0;m<a;m++){let g=d,S=re(i,t,d);d=S.end;let v=re(i,t,d).end;if(On(t.getUint8(g))){let w=t.getUint8(g),R=(w&224)===160?1:w===217?2:w===218?3:5;if(new TextDecoder().decode(i.subarray(g+R,S.end))==="t"){l.push(i.subarray(g,S.end));let U=new TextEncoder().encode(e);if(U.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");l.push(new Uint8Array([160|U.byteLength]),U)}else l.push(i.subarray(g,v))}else l.push(i.subarray(g,v));d=v}let c=l.reduce((m,g)=>m+g.byteLength,0),u=new Uint8Array(c),h=0;for(let m of l)u.set(m,h),h+=m.byteLength;return u}function On(i){return(i&224)===160?!0:i===217||i===218||i===219}function re(i,e,t){let n=e.getUint8(t),r=t;if(n<=127||n>=224)return{start:r,end:t+1};if((n&224)===160)return{start:r,end:t+1+(n&31)};if((n&240)===128||(n&240)===144){let o=n&15;t+=1;let a=(n&240)===128?o*2:o;for(let d=0;d<a;d++)t=re(i,e,t).end;return{start:r,end:t}}let s={192:0,194:0,195:0,204:1,205:2,206:4,207:8,208:1,209:2,210:4,211:8,202:4,203:8};if(s[n]!==void 0)return{start:r,end:t+1+s[n]};if(n===217||n===196)return{start:r,end:t+2+e.getUint8(t+1)};if(n===218||n===197)return{start:r,end:t+3+e.getUint16(t+1,!1)};if(n===219||n===198)return{start:r,end:t+5+e.getUint32(t+1,!1)};if(n===220||n===221){let o=n===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===220?3:5;for(let a=0;a<o;a++)t=re(i,e,t).end;return{start:r,end:t}}if(n===222||n===223){let o=n===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===222?3:5;for(let a=0;a<o*2;a++)t=re(i,e,t).end;return{start:r,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${n.toString(16)} at byte ${r}`)}var N=12,Qe=1,Nn=0,ve=1,Jt=2;function we(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&Qe)===Qe,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function Zt(i){let e=new Uint8Array(N),t=new DataView(e.buffer);return t.setUint32(0,i.groupId,!0),t.setUint32(4,i.frameSeq,!0),t.setUint8(8,i.keyframe?Qe:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??Nn),e}var Fn=100,en=100,be=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??Fn}cb;pending=new Map;newestGroupSeen=-1;newestFrameDelivered=-1;needKeyframe=!0;kfRequestedAt=-1/0;now;debounceMs;bytesInWindow=0;framesDelivered=0;framesAbandoned=0;push(e){if(e.byteLength<N)return;let t=we(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.isSourceRestart(t.groupId,t.frameSeq))this.resync(t.groupId);else if(t.groupId<this.newestGroupSeen||(t.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t.groupId,this.needKeyframe=!0),t.frameSeq<=this.newestFrameDelivered))return;let n=this.pending.get(t.frameSeq);if(n||(n={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n)),!n.chunks[t.fragIndex]){n.chunks[t.fragIndex]=e.subarray(N),n.received++,n.received===n.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,n));for(let r of this.pending.keys())r<t.frameSeq-1&&(this.pending.delete(r),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-en?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-en}resync(e){this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e,this.newestFrameDelivered=-1,this.needKeyframe=!0,this.requestKeyframe()}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let n=t.chunks.reduce((o,a)=>o+a.byteLength,0),r=new Uint8Array(n),s=0;for(let o of t.chunks)r.set(o,s),s+=o.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:r})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var $n=/^avc[13]\.[0-9a-fA-F]{6}$/;function qn(i){return $n.test(i)?null:`codec ${JSON.stringify(i)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function Ye(i,e){let t=qn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var Hn=1,ze=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}if(this.name===null){if(this.buf.byteLength<2)return[];let n=this.buf[0];if(n!==Hn)throw new Error(`[urun] wt data stream: unknown header version 0x${n.toString(16)} \u2014 rejecting stream`);let r=this.buf[1];if(r===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+r)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+r)),this.buf=this.buf.subarray(2+r)}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+n)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let r=Lt(this.buf.subarray(4,4+n));this.buf=this.buf.subarray(4+n),r===Dt&&(this.ended=!0),t.push({name:this.name,payload:r})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return t}finish(){if(this.ended&&this.buf.byteLength===0)return;let e=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN without an END envelope`)}};async function tn(i,e){let t=i.getReader();for(;;){let{value:n,done:r}=await t.read();if(r)return;n&&Bn(n,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function Bn(i,e){let t=i.getReader(),n=new ze;try{for(;;){let{value:r,done:s}=await t.read();if(s)break;if(!(!r||r.byteLength===0))for(let{name:o,payload:a}of n.push(r))e.onData(o,a)}n.finish()}catch(r){try{await t.cancel?.(r)}catch{}throw r}}var Xe="wt-playout",jn=class extends(globalThis.AudioWorkletProcessor??Object){holdN=96;fadeN=192;cap=24e3;primeSamples=0;primeWall=12e3;rings=[];held=new Float32Array(0);read=0;depth=0;started=!1;starve=1e9;hadContent=!1;born=!0;xfadeLeft=0;xfadeFrom=new Float32Array(0);constructor(){super(),this.wire()}wire(){let i=this.port;i&&(i.onmessage=e=>this.onMessage(e.data))}post(i){this.port?.postMessage(i)}ensure(i){if(!(this.rings.length===i&&this.held.length===i&&this.rings[0]?.length===this.cap)){this.rings=[];for(let e=0;e<i;e++)this.rings.push(new Float32Array(this.cap));this.held=new Float32Array(i),this.xfadeFrom=new Float32Array(i)}}onMessage(i){if(i.type==="init"){this.holdN=Math.max(1,Math.round(2*i.rate/1e3)),this.fadeN=Math.max(1,Math.round(4*i.rate/1e3)),this.cap=Math.max(1,Math.round(500*i.rate/1e3)),this.primeSamples=Math.max(0,Math.round(i.primeSamples)),this.primeWall=Math.round(250*i.rate/1e3),this.ensure(1);return}if(i.type==="reset"){this.ensure(1),this.read=0,this.depth=0,this.held.fill(0),this.starve=this.holdN+this.fadeN+1,this.hadContent=!1,this.xfadeLeft=0;return}if(i.type!=="pcm")return;let e=i.bufs.map(r=>new Float32Array(r)),t=i.frames;if(this.ensure(e.length),this.depth+t>this.cap){let r=this.depth+t-this.cap;this.read=(this.read+r)%this.cap,this.depth-=r,this.post({type:"overflow",dropped:r})}let n=(this.read+this.depth)%this.cap;for(let r=0;r<t;r++){for(let s=0;s<e.length;s++)this.rings[s][n]=e[s][r];n=n+1===this.cap?0:n+1}this.depth+=t}process(i,e){let t=e[0];if(!t||t.length===0)return!0;this.ensure(t.length);let n=t[0].length;if(!this.started)if(this.depth>=this.primeSamples||this.primeWall<=0)this.started=!0;else{this.primeWall-=n;for(let o of t)o.fill(0);return!0}let r=t.length,s=this.fadeN;for(let o=0;o<n;o++)if(this.depth>0){if(this.starve>0){this.xfadeFrom.set(this.held);for(let a=0;a<r;a++)this.xfadeFrom[a]*=this.holdGain(this.starve);this.xfadeLeft=s,this.born?this.born=!1:this.post({type:"resume"}),this.starve=0}if(this.xfadeLeft>0){let a=1-this.xfadeLeft/s;for(let d=0;d<r;d++){let l=this.rings[d][this.read];this.held[d]=l,t[d][o]=this.xfadeFrom[d]*(1-a)+l*a}this.xfadeLeft--}else for(let a=0;a<r;a++){let d=this.rings[a][this.read];this.held[a]=d,t[a][o]=d}this.read=this.read+1===this.cap?0:this.read+1,this.depth--,this.hadContent=!0}else{this.hadContent&&(this.hadContent=!1,this.post({type:"underrun"})),this.starve++;let a=this.holdGain(this.starve);for(let d=0;d<r;d++)t[d][o]=this.held[d]*a}return!0}holdGain(i){return i<=this.holdN?1:i<=this.holdN+this.fadeN?1-(i-this.holdN)/this.fadeN:0}};function Vn(){return`registerProcessor(${JSON.stringify(Xe)}, ${jn.toString()})`}function nn(){let i=globalThis;return typeof i.Blob!="function"||typeof i.URL?.createObjectURL!="function"?null:i.URL.createObjectURL(new Blob([Vn()],{type:"text/javascript"}))}var Je=40,rn=2,H=48e3,Kn=12,Gn=64,Qn=100,Ze=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<N)return;let t=we(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-Qn)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let n=this.pending.get(t.frameSeq);if(!n)for(n={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n);this.pending.size>Gn;){let a=1/0;for(let d of this.pending.keys())d<a&&(a=d);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=n.fragCount||n.chunks[t.fragIndex]||(n.chunks[t.fragIndex]=e.subarray(N),n.received++,n.received<n.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let r=n.chunks.reduce((a,d)=>a+(d?.byteLength??0),0),s=new Uint8Array(r),o=0;for(let a of n.chunks)s.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:n.timestamp,data:s})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},ye=class{constructor(e,t){this.config=e;this.seam=t;let n=this.seam.jitterBufferTargetMs??Je;Number.isFinite(n)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${n} is not finite \u2014 using default ${Je}ms`),n=Je),this.targetS=Math.max(0,n)/1e3}config;seam;decoder=null;ctx=null;ownsCtx=!1;resumeAttempts=0;resumeInFlight=!1;notRunningFrames=0;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;contentBaseS=null;wallBaseS=0;reanchorLogged=!1;lastTsS=null;pendingTs=[];liveSources=new Set;bridgeTrack=null;consumerTrack=null;consumerTrackOf=null;scheduledCount=0;lastScheduledAt=0;lastFrameArrivalAt=0;lastReplyStart=null;rebuildTimes=[];rebuildBudgetLoggedAt=-1e4;lastRemote=null;assembler=new Ze(e=>this.decodeFrame(e));workletNode=null;workletState="legacy";pendingPcm=[];workletStale=!1;underruns=0;resumeFades=0;ringOverflow=0;rateMismatchDropped=0;pendingDropped=0;start(){let e=globalThis.AudioDecoder,t=globalThis.AudioContext;if(typeof e!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");if(this.seam.ctx)this.ctx=this.seam.ctx,this.ownsCtx=!1;else{if(typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new t({sampleRate:this.config.sampleRate}),this.ownsCtx=!0}this.dest=this.ctx.createMediaStreamDestination(),this.armCtxRearm();try{this.initDecoder(e)}catch(r){throw this.ownsCtx&&this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,r}this.trackSurfaced=!0,this.resumeLoudly("start");let n=this.dest.stream.getAudioTracks()[0];if(!n)throw new Error("[urun] playout start produced no bridge track");this.startWorkletLoad(),this.surfaceTrack(n)}startWorkletLoad(){let e=this.ctx;if(!e||!e.audioWorklet)return;if(e.sampleRate!==this.config.sampleRate){console.warn(`[urun] WT audio playout: caller context runs at ${e.sampleRate} Hz but the lane decodes at ${this.config.sampleRate} Hz \u2014 the worklet ring player cannot resample, riding the legacy per-frame scheduler (which resamples in-graph)`);return}let t=globalThis.AudioWorkletNode;if(typeof t!="function")return;let n=nn();n!==null&&(this.workletState="loading",e.audioWorklet.addModule(n).then(()=>{if(this.stopped||this.ctx!==e||this.workletState!=="loading")return;let r=new t(e,Xe,{numberOfInputs:0,outputChannelCount:[this.config.channels]});r.connect(this.dest),r.connect(e.destination),r.port.onmessage=s=>this.onWorkletEvent(s.data),this.workletNode=r,this.workletState="ready",r.port.postMessage({type:"init",rate:e.sampleRate,primeSamples:Math.round(this.targetS*e.sampleRate)}),this.flushPendingPcm("ready"),console.info(`[urun] WT audio playout: worklet ring engaged (underrun hold+fade shaping, lead=${(this.targetS*1e3).toFixed(0)}ms, channels=${this.config.channels})`)}).catch(r=>{this.stopped||this.ctx!==e||this.workletState!=="loading"||(this.workletState="legacy",console.warn(`[urun] WT audio worklet module FAILED to load (${r instanceof Error?r.message:String(r)}) \u2014 falling back to the per-frame buffer scheduler: underruns will re-anchor (the crackle the ring player removes)`),this.flushPendingPcm("legacy"))}))}flushPendingPcm(e){let t=this.pendingPcm;this.pendingPcm=[];for(let n of t)e==="ready"?this.pushWorklet(n.planes,n.frames,n.sampleRate,n.timestamp):this.scheduleLegacy(n.planes,n.frames,n.sampleRate,n.timestamp)}onWorkletEvent(e){e.type==="underrun"?this.underruns++:e.type==="resume"?this.resumeFades++:e.type==="overflow"&&(this.ringOverflow+=e.dropped)}armCtxRearm(){let e=this.ctx;if(!e)return;let t=()=>{this.ctx&&this.ctx.state!=="running"&&this.resumeLoudly("statechange")},n=e;typeof n.addEventListener=="function"?n.addEventListener("statechange",t):e.onstatechange=t}resumeLoudly(e){let t=this.ctx;if(!t||!t.resume||this.resumeInFlight)return;let r=t.state!=="running"?++this.resumeAttempts:0;this.resumeInFlight=!0,t.resume().catch(s=>{console.warn(`[urun] WT audio playout context ${e}: resume FAILED (state=${t.state}, attempt=${r||"n/a"}): ${s instanceof Error?s.message:String(s)} \u2014 decoded reply audio would be scheduled into a graph that never renders; retrying per frame`)}).finally(()=>{this.resumeInFlight=!1})}stop(){if(this.stopped)return;this.stopped=!0,this.stopScheduledSources();let e=this.workletNode;if(e){this.workletNode=null,this.workletState="legacy";try{e.port.postMessage({type:"reset"})}catch{}try{e.disconnect()}catch{}}this.pendingPcm=[];try{this.seam.renderHop?.setSource(null)}catch{}this.trackSurfaced&&(this.trackSurfaced=!1,this.deliverSurface(null));try{this.decoder?.close()}catch{}this.ownsCtx&&this.ctx?.close().catch(()=>{})}initDecoder(e){let t=new e({output:n=>this.schedule(n,this.pendingTs.shift()),error:n=>this.onDecoderError(n)});t.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels}),this.decoder=t}decodeFrame(e){let t=globalThis.EncodedAudioChunk;if(typeof t!="function"||this.stopped)return;if(!this.decoder){let r=globalThis.AudioDecoder;if(typeof r!="function")return;try{this.initDecoder(r)}catch{return}}let n=this.decoder;n&&(this.lastFrameArrivalAt=performance.now(),this.pendingTs.push(e.timestamp),n.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/H)),data:e.data})))}schedule(e,t){let n=this.ctx,r=this.dest;if(!n||!r||this.stopped){e.close();return}if(n.state!=="running"){e.close(),this.contentBaseS=null,this.lastTsS=null,this.notRunningFrames++,(this.notRunningFrames===1||this.notRunningFrames%50===0)&&console.warn(`[urun] WT audio playout context not RUNNING (state=${n.state}): dropping decoded frames instead of scheduling into a graph that never renders \u2014 resume re-armed per frame (attempts=${this.resumeAttempts}, dropped=${this.notRunningFrames})`),this.resumeLoudly("per-frame"),this.workletNode&&!this.workletStale&&(this.workletStale=!0,this.workletNode.port.postMessage({type:"reset"}));return}let s=e.numberOfFrames,o=Math.max(1,e.numberOfChannels),a=e.sampleRate,d=[];for(let l=0;l<o;l++){let c=new Float32Array(s);e.copyTo(c,{planeIndex:l,format:"f32-planar"}),d.push(c)}if(e.close(),this.workletState==="ready"&&this.workletNode){this.pushWorklet(d,s,a,t);return}if(this.workletState==="loading"){this.stashPendingPcm(d,s,a,t);return}this.scheduleLegacy(d,s,a,t)}pushWorklet(e,t,n,r){let s=this.workletNode,o=this.ctx;if(!s||!o||this.stopped)return;if(n!==o.sampleRate||e.length!==Math.max(1,this.config.channels)){this.rateMismatchDropped++,this.rateMismatchDropped===1&&console.warn(`[urun] WT audio decoded frame shape mismatch (rate=${n} vs ctx=${o.sampleRate}, channels=${e.length} vs configured=${this.config.channels}) \u2014 dropped for the ring player`);return}let a=this.lastTsS;if(r!==void 0){let c=r/H;a!==null&&c<a&&(s.port.postMessage({type:"reset"}),this.workletStale=!1,this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout: producer timeline RESTART (${(a-c).toFixed(3)}s backward) \u2014 worklet ring flushed, new content fades in`))),this.lastTsS=c}let d=e.map(c=>c.buffer);s.port.postMessage({type:"pcm",frames:t,bufs:d},d),this.workletStale=!1,this.scheduledCount++;let l=performance.now();if(this.lastScheduledAt===0||l-this.lastScheduledAt>500){let c=this.lastScheduledAt===0?-1:l-this.lastScheduledAt,u=r!==void 0&&a!==null?(r/H-a)*1e3:null;this.lastReplyStart={at:l,idleMs:c,tsJumpMs:u,anchor:"worklet",leadMs:this.targetS*1e3,arrivalToScheduledMs:l-this.lastFrameArrivalAt},console.info(`[urun] WT audio reply-start (ring): idle=${c.toFixed(0)}ms tsJump=${u===null?"n/a":u.toFixed(0)+"ms"} anchor=worklet lead=${(this.targetS*1e3).toFixed(0)}ms arrival\u2192scheduled=${(l-this.lastFrameArrivalAt).toFixed(1)}ms target=${(this.targetS*1e3).toFixed(0)}ms droppedNotRunning=${this.notRunningFrames}`)}this.lastScheduledAt=l}stashPendingPcm(e,t,n,r){for(this.pendingPcm.push({planes:e,frames:t,sampleRate:n,timestamp:r});this.pendingPcm.length>Kn;)this.pendingPcm.shift(),this.pendingDropped===0&&console.warn("[urun] WT audio worklet module still loading past the stash cap \u2014 dropping the oldest stashed frames (the reply opening may clip)"),this.pendingDropped++}scheduleLegacy(e,t,n,r){let s=this.ctx,o=this.dest;if(!s||!o||this.stopped)return;let a=e.length,d=s.createBuffer(a,t,n);for(let g=0;g<a;g++)d.copyToChannel(e[g],g);let l=t/n,c=s.createBufferSource();c.buffer=d,c.connect(o),c.connect(s.destination);let u,h="ride";if(r===void 0)u=Math.max(this.playhead,s.currentTime+this.targetS),h="arrival-fallback";else{this.contentBaseS===null&&(this.contentBaseS=r/H,this.wallBaseS=s.currentTime+this.targetS,h="fresh-anchor"),u=this.wallBaseS+r/H-this.contentBaseS;let g=null;this.lastTsS!==null&&(r<this.lastTsS?(u=s.currentTime+this.targetS,g=`backward ts step ${(this.lastTsS-r/H).toFixed(3)}s (producer clock reset)`):u>s.currentTime+this.targetS+Math.max(l,this.targetS)&&(g=`forward jump ${(u-s.currentTime).toFixed(3)}s out (lead + ${l.toFixed(3)}s tolerance exceeded \u2014 barge flush / producer re-anchor)`),g&&(h=g.startsWith("backward")?"backward":"surplus",this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored on a content-timeline discontinuity: ${g} \u2014 the gap is honest silence at rate 1.0, never a stretch`)),this.contentBaseS=r/H,this.wallBaseS=s.currentTime+this.targetS,u=this.wallBaseS)),u<s.currentTime&&(h="deficit",this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored ${(s.currentTime-u).toFixed(3)}s past its content position (arrival deficit exceeded the lead) \u2014 the gap is honest silence at rate 1.0, never a catch-up stretch`)),this.contentBaseS=r/H,this.wallBaseS=s.currentTime+this.targetS,u=this.wallBaseS)}c.start(u),this.liveSources.add(c),c.onended=()=>{this.liveSources.delete(c)},this.scheduledCount++;let m=performance.now();if(this.lastScheduledAt===0||m-this.lastScheduledAt>500){let g=this.lastScheduledAt===0?-1:m-this.lastScheduledAt,S=r!==void 0&&this.lastTsS!==null?(r/H-this.lastTsS)*1e3:null;this.lastReplyStart={at:m,idleMs:g,tsJumpMs:S,anchor:h,leadMs:(u-s.currentTime)*1e3,arrivalToScheduledMs:m-this.lastFrameArrivalAt},console.info(`[urun] WT audio reply-start: idle=${g.toFixed(0)}ms tsJump=${S===null?"n/a":S.toFixed(0)+"ms"} anchor=${h} lead=${((u-s.currentTime)*1e3).toFixed(0)}ms arrival\u2192scheduled=${(m-this.lastFrameArrivalAt).toFixed(1)}ms target=${(this.targetS*1e3).toFixed(0)}ms droppedNotRunning=${this.notRunningFrames}`)}this.lastScheduledAt=m,r!==void 0&&(this.lastTsS=r/H),this.playhead=u+l}armBridgeEndedWatch(e){e.addEventListener?.("ended",()=>{this.stopped||this.bridgeTrack!==e||console.warn("[urun] WT audio bridge track ended \u2014 inert: playout rides the AudioContext destination (direct-out); the bridge track was the AEC render-hop reference and the element routing surface only. Echo cancellation degrades until the next rebuild re-delivers, the reply does not.")},{once:!0})}playoutProgress(){return{scheduled:this.scheduledCount,lastScheduledAt:this.lastScheduledAt,surfaced:this.trackSurfaced&&this.ctx?.state==="running",droppedNotRunning:this.notRunningFrames,ctxState:this.ctx?.state??"closed",lastReplyStart:this.lastReplyStart,underruns:this.underruns,resumeFades:this.resumeFades,ringOverflow:this.ringOverflow}}rebuildSurface(){if(this.stopped)return;let e=performance.now();if(this.rebuildTimes=this.rebuildTimes.filter(r=>e-r<1e4),this.rebuildTimes.length>=rn){e-this.rebuildBudgetLoggedAt>1e4&&(this.rebuildBudgetLoggedAt=e,console.error(`[urun] WT audio bridge rebuild budget spent (${rn} in 10s) \u2014 standing down; the media-dead playout-progress verdict escalates to a re-dial if the surface stays dead`));return}this.rebuildTimes.push(e),this.stopScheduledSources();let t=this.ctx;if(t?.state==="closed"&&(console.warn("[urun] WT audio playout rebuild: the retained context is CLOSED (closed behind the lane's back) \u2014 constructing a fresh lane-owned context instead of minting a destination on a dead graph"),t=null,this.ctx=null),!t){let r=globalThis.AudioContext;if(typeof r!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");t=new r({sampleRate:this.config.sampleRate}),this.ctx=t,this.ownsCtx=!0,this.armCtxRearm()}if(t.state!=="running"&&this.resumeLoudly("rebuild"),this.dest=t.createMediaStreamDestination(),this.playhead=0,this.contentBaseS!==null&&this.ctx!==t&&(this.contentBaseS=null,this.lastTsS=null),this.ctx!==t){if(this.workletNode){try{this.workletNode.disconnect()}catch{}this.workletNode=null}this.workletState="legacy",this.workletStale=!1,this.pendingPcm=[],this.startWorkletLoad()}else if(this.workletNode){try{this.workletNode.disconnect()}catch{}this.workletNode.connect(this.dest),this.workletNode.connect(t.destination)}this.trackSurfaced=!0;let n=this.dest.stream.getAudioTracks()[0];if(!n)throw new Error("[urun] rebuilt playout produced no bridge track");this.surfaceTrack(n)}deliverSurface(e){if(!e){try{this.consumerTrack?.stop()}catch{}this.consumerTrack=null,this.consumerTrackOf=null,this.seam.onTrack(null);return}if(this.consumerTrackOf===e&&this.consumerTrack&&this.consumerTrack.readyState!=="ended"){this.seam.onTrack(this.consumerTrack);return}try{this.consumerTrack?.stop()}catch{}this.consumerTrack=e.clone(),this.consumerTrackOf=e,this.seam.onTrack(this.consumerTrack)}stopScheduledSources(){for(let e of this.liveSources)try{e.stop()}catch{}this.liveSources.clear()}surfaceTrack(e){this.bridgeTrack=e,this.armBridgeEndedWatch(e),this.lastRemote&&this.lastRemote.readyState==="live"?this.deliverSurface(this.lastRemote):this.deliverSurface(e);let t=this.seam.renderHop;t&&(t.onRemote(n=>{if(this.stopped)return;if(n?this.lastRemote=n:this.lastRemote&&this.lastRemote.readyState!=="live"&&(this.lastRemote=null),n){this.deliverSurface(n);return}if(this.lastRemote&&this.lastRemote.readyState==="live"){this.deliverSurface(this.lastRemote);return}let r=this.bridgeTrack&&this.bridgeTrack.readyState==="live"?this.bridgeTrack:null;this.deliverSurface(r)}),t.setSource(e))}onDecoderError(e){if(this.stopped)return;console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=globalThis.AudioDecoder;if(typeof t=="function")try{this.initDecoder(t)}catch(n){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${n instanceof Error?n.message:String(n)}`)}}};var ie=1200;function et(i,e,t,n,r){let s=n-N;if(s<=0)return null;let o=Math.max(1,Math.ceil(t.byteLength/s));if(o>255)return null;let a=[];for(let d=0;d<o;d++){let l=t.subarray(d*s,Math.min((d+1)*s,t.byteLength)),c=Zt({groupId:e>>>0,frameSeq:i>>>0,keyframe:r?.keyframe??!0,fragIndex:d,fragCount:o,lane:r?.lane??ve}),u=new Uint8Array(N+l.byteLength);u.set(c,0),u.set(l,N),a.push(u)}return a}var Yn=`
3
- self.onrtctransform = (event) => {
4
- const transformer = event.transformer
5
- if (transformer.options?.role === 'sender') {
6
- const stream = new TransformStream({
7
- transform(frame, controller) {
8
- // Read the payload through the SPEC data buffer \u2014 copyTo was a
9
- // Chrome-only extension that current Chrome REMOVED (the prototype is
10
- // just timestamp/data/getMetadata). Copy once (<= ~200 B/frame) so the
11
- // transferred buffer never detaches the frame's own data.
12
- const payload = new Uint8Array(frame.data).slice()
13
- const rtpTimestamp = frame.getMetadata().rtpTimestamp
14
- // Post the BUFFER (the lane expects an ArrayBuffer \u2014 a transferred
15
- // view arrives as a Uint8Array and would be silently dropped).
16
- self.postMessage({ type: 'enc', rtpTimestamp, payload: payload.buffer }, [payload.buffer])
17
- controller.enqueue(frame)
18
- },
19
- })
20
- transformer.readable.pipeThrough(stream).pipeTo(transformer.writable).catch((e) =>
21
- self.postMessage({ type: 'err', detail: String(e) }))
22
- } else {
23
- const stream = new TransformStream({ transform() {} })
24
- transformer.readable.pipeThrough(stream).pipeTo(transformer.writable).catch((e) =>
25
- self.postMessage({ type: 'err', detail: String(e) }))
26
- }
27
- }
28
- `;function sn(i){let e=i.match(/a=rtpmap:(\d+) opus\/48000\/2/)?.[1];if(!e)return i;let t="usedtx=1;useinbandfec=1;maxaveragebitrate=32000",n=!1,r=i.split(`\r
29
- `).map(s=>s.startsWith(`a=fmtp:${e} `)&&!s.includes("usedtx=")?(n=!0,`${s};${t}`):s);if(!n){let s=r.findIndex(o=>o===`a=rtpmap:${e} opus/48000/2`);s>=0&&r.splice(s+1,0,`a=fmtp:${e} ${t}`)}return r.join(`\r
30
- `)}var ke=class i{constructor(e,t){this.sink=e;this.seqState=t??{seq:0}}sink;stopped=!1;deadCb=null;seqState;static FLOW_WINDOW_MS=5e3;static FLOW_MIN_SENT_PER_WINDOW=25;sentCount=0;flowTimer=null;flowLastSent=0;flowLastDelivered=0;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()}sentDatagrams(){return this.sentCount}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=zn(e)?this.bridgedTrack(e):e,!t))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(t)}catch(n){this.die(`replaceTrack: ${n instanceof Error?n.message:String(n)}`);return}this.currentTrack=t,t&&this.wireTrackLiveness(t);return}t!==null&&(this.engage(t),this.startFlowWatch())}}startFlowWatch(){this.flowTimer||this.stopped||(this.flowLastSent=this.sentCount,this.flowLastDelivered=this.sink.delivered(),this.flowTimer=setInterval(()=>{if(this.stopped)return;let e=this.sentCount-this.flowLastSent,t=this.sink.delivered()-this.flowLastDelivered;this.flowLastSent=this.sentCount,this.flowLastDelivered=this.sink.delivered(),e>0&&console.log(`[urun] WT mic uplink flow: wrote=${(e/(i.FLOW_WINDOW_MS/1e3)).toFixed(0)}/s accepted=${(t/(i.FLOW_WINDOW_MS/1e3)).toFixed(0)}/s`),!(e<i.FLOW_MIN_SENT_PER_WINDOW)&&(t*2>=e||console.error(`[urun] WT mic uplink flow STARVED: wrote ${e} datagrams in ${i.FLOW_WINDOW_MS/1e3}s but QUIC accepted only ${t}`))},i.FLOW_WINDOW_MS))}stop(){if(!this.stopped){this.stopped=!0,this.flowTimer!==null&&(clearInterval(this.flowTimer),this.flowTimer=null),this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(e){let t=globalThis;if(typeof t.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof t.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let n;try{n=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let r=this.sendPc.addTrack(e);this.sender=r,this.currentTrack=e,this.wireTrackLiveness(e);let s=t.RTCRtpScriptTransform;if(r.transform=new s(n,{role:"sender"}),this.negotiatedOnce){this.negotiate().catch(o=>this.die(`loopback renegotiate: ${o instanceof Error?o.message:String(o)}`));return}this.negotiate().catch(o=>this.die(`loopback negotiate: ${o instanceof Error?o.message:String(o)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let t=e.RTCPeerConnection;this.sendPc=new t({iceServers:[]}),this.recvPc=new t({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=n=>{if(!n.candidate)return;let r=this.candQueue;r!==null&&(r.toRecv.push(n.candidate),this.flushCandidates())},this.recvPc.onicecandidate=n=>{if(!n.candidate)return;let r=this.candQueue;r!==null&&(r.toSend.push(n.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(n=>this.die(`loopback renegotiate: ${n instanceof Error?n.message:String(n)}`))},this.recvPc.ontrack=n=>{let r=n.transceiver?.mid??null;r!==null&&r===this.renderMidOf()&&this.renderRemoteCb?.(n.track)}}setRenderSource(e){if(!this.stopped){if(e===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(e);else try{this.renderSender.replaceTrack(e)}catch(t){this.die(`render replaceTrack: ${t instanceof Error?t.message:String(t)}`);return}this.wireRenderRemote(e),!this.negotiatedOnce&&this.sender&&this.negotiate().catch(t=>this.die(`loopback negotiate: ${t instanceof Error?t.message:String(t)}`))}}}onRenderTrack(e){this.renderRemoteCb=e}renderMidOf(){if(!this.renderSender)return null;let e=this.sendPc;try{return e.getTransceivers?.().find(t=>t.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(e){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},e.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let e=this.sendPc,t=this.recvPc;if(!(!e||!t||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let n=await e.createOffer();n.sdp=sn(n.sdp??""),await e.setLocalDescription(n),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:n.sdp});let r=await t.createAnswer();r.sdp=sn(r.sdp??""),await t.setLocalDescription(r),await e.setRemoteDescription(t.localDescription??{type:"answer",sdp:r.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let e=this.candQueue;if(e){for(;e.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(e.toSend.shift())).catch(()=>{});for(;e.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(e.toRecv.shift())).catch(()=>{})}}bridgedTrack(e){let t=e;try{let n=t.context.createMediaStreamDestination();t.connect(n);let r=n.stream.getAudioTracks()[0]??null;return r?(this.nodeBridge={node:t,dest:n},r):(this.die("AudioNode bridge produced no audio track"),null)}catch(n){return this.die(`AudioNode bridge: ${n instanceof Error?n.message:String(n)}`),null}}wireTrackLiveness(e){this.endedListener=()=>this.die("mic track ended"),e.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([Yn],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=t=>{let n=t.data;n?.type==="enc"&&n.payload instanceof ArrayBuffer?this.onEncodedFrame(n.rtpTimestamp??0,new Uint8Array(n.payload)):n?.type==="err"&&this.die(`transform: ${n.detail??"unknown"}`)},e.onerror=t=>this.die(`transform worker: ${t.message||"error"}`),this.worker=e,e}onEncodedFrame(e,t){if(this.stopped)return;let n=et(this.seqState.seq,e,t,this.sink.maxDatagramSize()||ie);if(n===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.seqState.seq=this.seqState.seq+1>>>0;return}for(let r of n)this.sink.send(r),this.sentCount++;this.seqState.seq=this.seqState.seq+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 zn(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var Xn=9e4,Jn="avc1.42E01F",Zn=60,er=3,tr=1e4;function nr(i){return Math.round(i*(Xn/1e6))%2**32>>>0}var Se=class{constructor(e){this.sink=e}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}requestKeyframe(){this.keyframeWanted=!0}setSource(e){if(this.stopped||(this.teardownCapture(),e===null))return;let n=globalThis.MediaStreamTrackProcessor;if(typeof n!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let r=++this.generation,s=new n({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,s.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&r===this.generation;){let{value:a,done:d}=await s.read();if(d)break;if(a){if(o||this.stopped||r!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&r===this.generation&&this.die(`capture: ${a instanceof Error?a.message:String(a)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){this.cancelCapture?.(),this.cancelCapture=null,this.generation++}encodeFrame(e){let t={width:e.codedWidth,height:e.codedHeight};if(!this.encoder||!this.encoderDims||this.encoderDims.width!==t.width||this.encoderDims.height!==t.height){let s=globalThis.VideoEncoder;if(typeof s!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new s({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)})),this.encoderDims=t,this.encoder.configure({codec:Jn,avc:{format:"annexb"},width:t.width,height:t.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(o){e.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${o instanceof Error?o.message:String(o)}`);return}}let r=this.keyframeWanted||this.framesSinceKeyframe>=Zn;this.keyframeWanted=!1,this.framesSinceKeyframe=r?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:r})}catch(s){this.onEncoderError(s instanceof Error?s:new Error(String(s)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let n=et(this.frameSeq,nr(e.timestamp),t,this.sink.maxDatagramSize()||ie,{lane:Jt,keyframe:e.type==="key"});if(n===null){console.warn(`[urun] WT video uplink: AU of ${t.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let r of n)this.sink.send(r);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(n=>t-n<tr),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=er){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 rr(i){return i.byteLength>=2&&i[0]===1&&i[1]===3}var _e=class{constructor(e){this.transport=e}transport;streams=new Map;dead=null;deadCb=null;chain=Promise.resolve();onDead(e){this.deadCb=e}send(e,t){let n=new TextEncoder().encode(e);if(n.byteLength===0||n.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${n.byteLength})`));let r=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let s=this.streams.get(e);if(!s){let a=await this.transport.openUniStream(),d=new Uint8Array(2+n.byteLength);d[0]=1,d[1]=n.byteLength,d.set(n,2),await a.write(d),s={writer:a},this.streams.set(e,s)}let o=new Uint8Array(4+t.byteLength);new DataView(o.buffer).setUint32(0,t.byteLength,!0),o.set(t,4),await s.writer.write(o),rr(t)&&(this.streams.delete(e),await s.writer.close().catch(()=>{}))}catch(s){throw this.die(s instanceof Error?s.message:String(s)),s}});return this.chain=r.catch(()=>{}),r}stop(e="stopped"){if(this.dead===null){this.dead=e;for(let t of this.streams.values())t.writer.close().catch(()=>{});this.streams.clear()}}die(e){this.dead===null&&(console.warn(`[urun] WT data uplink lane dead (${e})`),this.stop(e),this.deadCb?.(e))}};var on=250,ir=25,sr=2e3,or=15e3,ar=1e3,dr=45e3,lr=5e3,cr={llm:!0},ur=500,an=10,hr=2,pr=2,tt=2,Te=class i{constructor(e,t,n,r,s,o,a){this.offer=e;this.sessionId=t;this.canvas=n;this.audioLane=r;this.audioUplink=s;this.videoUplink=o;this.dataUplink=a;this.firstMedia=new Promise((d,l)=>{this.firstFrameResolve=d,this.firstFrameReject=l}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorLogged=!1;writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;stallWatch=null;stallTimer=null;audioLaneLastArrivalAt=null;lastInboundControlAt=null;lastInboundDataAt=null;firstInboundDataAt=null;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new be({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=this.offer.codec,n=t!==void 0&&t!=="";this.hasVideoLane=n,n&&Ye(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(c=>({algorithm:"sha-256",value:Uint8Array.from(atob(c),u=>u.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let r=await this.wt.createBidirectionalStream();this.writer=r.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let s=r.readable.getReader(),o=new ge,a=[],d=await this.readControl(s,o,a);if(d?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");let l=d;if(this.lastInboundControlAt=performance.now(),typeof l.pingIntervalMs=="number"&&l.pingIntervalMs>0?this.advertisedPingIntervalMs=l.pingIntervalMs:this.noCadenceLogged||(this.noCadenceLogged=!0,console.warn("[urun] gateway advertises no liveness cadence (pre-#2826 or mid-roll gateway) \u2014 the downlink-stall watch will never judge this leg dead on silence alone")),n&&(Ye(l.codec,"hello-ack"),this.initDecoder(l.codec,l.width,l.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let c={setSource:h=>{this.renderSource=h,this.audioUplinkLane?.setRenderSource?.(h)},onRemote:h=>{this.renderRemoteCb=h}},u=new ye(this.offer.audio,{...this.audioLane,renderHop:c});try{u.start(),this.audioPlayout=u}catch(h){console.warn(`[urun] WT audio lane failed to start (${h instanceof Error?h.message:String(h)}) \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 c=this.wt.createUnidirectionalStream?.bind(this.wt);if(!c)throw new Error("WebTransport uni streams are not creatable in this environment");let u=new _e({openUniStream:async()=>(await c()).getWriter()});u.onDead(h=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(h,u)}),this.dataUplinkSender=u,this.dataUplink.onUplink(u)}catch(c){let u=c instanceof Error?c.message:String(c);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(s,o,a).catch(c=>this.die(`control loop: ${c}`)),this.datagramLoop().catch(c=>this.die(`datagram loop: ${c}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),ur)),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(c=>{this.closedReason=`connection error: ${c}`,this.die(`connection error: ${c}`)})}pathLiveness(){return this.closedReason?{alive:!1,evidence:`quic session closed (${this.closedReason})`}:this.controlWriteError?{alive:!1,evidence:`quic control stream refused a write (${this.controlWriteError}) \u2014 the send path is gone`}:this.stopped?{alive:!1,evidence:"webtransport session stopped"}:{alive:!0,evidence:`quic session open; ${this.controlWritesAccepted} control frames accepted by the QUIC stack (one per ${on}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??or},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),ar))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let t=typeof e.ds=="number"?e.ds:null,n=typeof e.ur=="number"?e.ur:null;if(t===null&&n===null)return;this.gatewayExposesCounters=!0;let r=this.audioDgramsReceived,s=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:n,recvDownlink:r,sentUplink:s},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,d=n!==null&&o.ur!==null?n-o.ur:null,l=r-o.recvDownlink,c=s-o.sentUplink,u="none";if(a!==null&&a>=an&&l<=0?u="downlink":d!==null&&c>=an&&d<=0&&(u="uplink"),u==="none"){this.severedStreak="none",this.observePlayoutProgress(l,t);return}if(this.severedStreak!==u){this.severedStreak=u;return}this.severedStreak="none";let h=u==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${c} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+h+` (gateway flow counters ds=${t} ur=${n}, client received=${r} accepted=${s}, confirmed on ${hr} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,t){let n=this.audioPlayout;if(!n){this.playoutScheduledSeen=null;return}let r=n.playoutProgress(),s=r.surfaced;if(this.playoutScheduledSeen!==null&&r.scheduled>this.playoutScheduledSeen&&s){this.playoutScheduledSeen=r.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=r.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<pr)){if(!this.playoutStallRebuilt){this.playoutStallRebuilt=!0,this.playoutStallStreak=0,console.warn(`[urun] WT playout stalled while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${r.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{n.rebuildSurface()}catch(o){console.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=tt}return}this.playoutStallStreak<tt||(this.playoutStallStreak=0,this.playoutStallRebuilt=!1,this.die(`playout stalled past its in-place surface rebuild while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${r.scheduled} on ${tt} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let t=this.pathLiveness();if(!t.alive)return;let n=performance.now(),r=this.audioLaneLastArrivalAt===null?null:n-this.audioLaneLastArrivalAt,s=this.lastInboundControlAt===null?null:n-this.lastInboundControlAt,o=r===null&&s===null?!0:(r===null||r>=e.stallMs)&&(s===null||s>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&s!==null&&s>=2*a){this.die(`downlink stall: the gateway advertised a ${Math.round(a/1e3)}s liveness cadence but delivered no inbound frame of any kind for ${Math.round(s/1e3)}s while the path reports alive (${t.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}let d=!!(this.offer.audio&&this.audioLane),l=this.lastInboundDataAt===null?null:n-this.lastInboundDataAt,c=r!==null?r:this.firstInboundDataAt===null?null:n-this.firstInboundDataAt,u=c!==null&&c>=e.stallMs;if(d&&u&&l!==null&&l<=lr&&this.gatewayPings>0){this.die(`media-starved leg: no audio datagram for ${Math.round((c??0)/1e3)}s while the data lane delivered a frame ${Math.round((l??0)/1e3)}s ago (${this.gatewayPings} gateway pings; ${t.evidence}) \u2014 the reliable lanes are alive so the application is mid-conversation, and a dark audio lane under it is severed media fanout, never an idle application; re-dialing`);return}o&&s!==null&&s>=dr&&this.gatewayPings>0&&this.die(`one-way downlink stall: the gateway pinged this leg before (its downlink pipe demonstrably worked) but NOTHING has arrived \u2014 no audio datagram, no inbound control frame \u2014 for ${Math.round(s/1e3)}s while the path reports alive (${t.evidence}) and client control writes keep resolving \u2014 the downlink is severed in one direction; re-dialing (owner ruling 2026-09-26)`)}async stop(){this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks("webtransport session stopped"),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}datagramWriter(){if(!this.dgramWriter){let e=this.wt.datagrams.writable;if(!e)throw new Error("WebTransport datagrams are not writable in this environment");this.dgramWriter=e.getWriter()}return this.dgramWriter}releaseDatagramWriter(){let e=this.dgramWriter;if(e){this.dgramWriter=null;try{e.releaseLock?.()}catch{}}}dropUplinks(e){this.dropDatagramUplinks(e);let t=this.dataUplinkSender;t&&(this.dataUplinkSender=null,t.stop(e),this.dataUplink?.onUplinkLost(e,t))}dropDatagramUplinks(e){if(this.clearUplinkRetryTimers(),this.audioUplinkLane!==null||this.audioUplinkRetry!==null){let r=this.audioUplinkLane;r?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e,r??void 0)}if(this.videoUplinkLane!==null||this.videoUplinkRetry!==null){let r=this.videoUplinkLane;r?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e,r??void 0)}}onDead(e){this.deadCb=e}stats(){return this.lastStats}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");let t={onData:(n,r)=>{if(cr[n]===!0){let s=performance.now();this.firstInboundDataAt===null&&(this.firstInboundDataAt=s),this.lastInboundDataAt=s}e.onData(n,r)},onLaneError:n=>e.onLaneError(n)};this.dataLaneSink=t,tn(this.wt.incomingUnidirectionalStreams,t).catch(n=>{this.die(`data lane: ${n instanceof Error?n.message:String(n)}`)})}initDecoder(e,t,n){let r=globalThis.VideoDecoder;if(typeof r!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let s=this.canvas.getContext("2d");if(!s)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:n};let o=new r({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,s.drawImage(a,0,0),a.close()},error:a=>this.onDecoderError(a)});o.configure({codec:e,...t>0&&n>0?{codedWidth:t,codedHeight:n}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"}),this.decoder=o}onDecoderError(e){if(this.stopped||this.deadFired)return;console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=this.decoderConfig;if(!t){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder error with no retained config to re-init from \u2014 video stays down: ${e.message}`));return}try{this.initDecoder(t.codec,t.width,t.height),this.decoderErrorLogged=!1}catch(n){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${n instanceof Error?n.message:String(n)}`));return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}uplinkSend(e,t){if(this.stopped||this.deadFired)return;this.datagramWriter().write(e).then(t,r=>this.onUplinkSendError(r))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let t=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,console.error(`[urun] WT uplink datagram send FAILED (${t}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let n=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(r=>n-r<sr),this.uplinkSendErrorsAt.push(n),!(this.uplinkSendErrorsAt.length<ir)&&(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;uplinkSeqState={seq:0};uplinkSink(e){this.datagramWriter();let t=0;return{send:n=>this.uplinkSend(n,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??ie}}engageAudioUplink(){let e=new ke(this.uplinkSink("audio"),this.uplinkSeqState);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 Se(this.uplinkSink("video"));e.onDead(t=>this.onUplinkLaneDead("video",t,e)),this.videoUplinkLane=e,this.videoUplinkRetry=this.freshLaneBuilt(this.videoUplinkRetry),this.videoUplink.onUplink(e)}engageUplinkLane(e){let t=e==="audio"?"mic":"video";try{e==="audio"?this.engageAudioUplink():this.engageVideoUplink()}catch(n){let r=n instanceof Error?n.message:String(n);console.warn(`[urun] WT ${t} uplink failed to engage (${r}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,r)}}freshLaneBuilt(e){let t={count:e?.count??0,builtAt:Date.now(),timer:void 0};return e&&(clearTimeout(e.timer),e.timer=void 0),t}onUplinkLaneDead(e,t,n){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let r=e==="audio"?"mic":"video",s=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,a=s?.builtAt!=null&&Date.now()-s.builtAt>=i.UPLINK_LANE_HEALTHY_MS?1:(s?.count??0)+1;if(a>i.UPLINK_LANE_RETRY_MAX){console.error(`[urun] WT ${r} uplink lane dead (${t}) \u2014 ${i.UPLINK_LANE_RETRY_MAX} recovery attempts exhausted; the lane is down until the transport's own revert runs (onUplinkLost)`),e==="audio"?this.audioUplinkRetry=null:this.videoUplinkRetry=null,this.seamUplinkLost(e,`lane dead after ${i.UPLINK_LANE_RETRY_MAX} recovery attempts: ${t}`,n);return}console.warn(`[urun] WT ${r} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${a}/${i.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let d={count:a,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=d:this.videoUplinkRetry=d,d.timer=setTimeout(()=>{d.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},i.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,t,n){e==="audio"?this.audioUplink.onUplinkLost(t,n):this.videoUplink.onUplinkLost(t,n)}clearUplinkRetryTimers(){for(let e of[this.audioUplinkRetry,this.videoUplinkRetry])e&&(clearTimeout(e.timer),e.timer=void 0)}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:n}=await e.read();if(n)break;if(!t)continue;if(t.byteLength>=N&&t[11]===ve){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let r=performance.now();if(this.lastArrivalTs>0){let s=r-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(s-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=r,this.reassembler.push(t)}}decodeFrame(e,t,n){let r=globalThis.EncodedVideoChunk;if(typeof r=="function"){if(!this.decoder&&this.decoderConfig)try{this.initDecoder(this.decoderConfig.codec,this.decoderConfig.width,this.decoderConfig.height),this.decoderErrorLogged=!1}catch{return}this.decoder&&(this.decoder.decode(new r({type:t?"key":"delta",timestamp:e*(1e6/24),data:n})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(zt(e)),this.controlWritesAccepted++}catch(t){let n=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=n),this.die(`control stream write refused: ${n}`),t}}async sendControlRaw(e){try{let t=new Uint8Array(4+e.byteLength);new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),await this.writer.write(t),this.controlWritesAccepted++}catch(t){let n=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=n),this.die(`control stream write refused: ${n}`),t}}async readControl(e,t,n=[]){for(;;){let r=n.shift();if(r)return r;let{value:s,done:o}=await e.read();if(o)return null;s&&n.push(...t.push(s))}}async controlLoop(e,t,n){for(;!this.stopped;){let r=await this.readControl(e,t,n);if(!r)break;let s=r;if(this.lastInboundControlAt=performance.now(),s.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(Xt(r.raw,"pong"))}catch{}}(s.t==="ping"||s.t==="pong")&&this.observeFlowCounters(s),s.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),n=(t-e)/1e3;e=t;let r=this.reassembler.drainWindow(),s=r.delivered+r.abandoned;this.lastStats={recvBps:n>0?r.bytes*8/n:0,lossPct:s>0?100*r.abandoned/s:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},on)}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 dn=2500,ln=["av01.0.08M.08","avc1.42E01F","avc1.640028"],fr=1e4,Ae=class i{constructor(e,t,n){this.signaling=e;this.sessionId=t;this.opts=n}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;static WT_REDIAL_BASE_MS=2e3;static WT_REDIAL_MAX=3;static WT_REDIAL_CAP_MS=3e4;wtRedialFailures=0;wtRedialTimer=null;wtDialedHost;wtHostMismatchCount=0;disconnected=!1;downlinkStallWatch=null;watchDownlinkStall(e={}){this.downlinkStallWatch={stallMs:e.stallMs??15e3},this.applyStallWatch()}applyStallWatch(){let e=this.session;!e||e.kind!=="webtransport"||!this.downlinkStallWatch||e.watchDownlinkStall?.(this.downlinkStallWatch)}failCurrentWtLeg(e){if(this.disconnected)return;let t=this.session;!t||t.kind!=="webtransport"||t.fail?.(e)}get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis;this.disconnected=!1;let t=typeof e.WebTransport=="function",n=typeof e.VideoDecoder=="function",r=this.opts.allowWebTransport??!0,s={webtransport:t&&n&&r,webcodecs:n,codecs:ln,wtData:t&&n&&r&&this.opts.dataLane!==void 0,wtAudio:t&&n&&r&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&r&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:t&&n&&r&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&n&&r&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:s}),this.noteOfferedWtHost();let o=s.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,d=o&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(d||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),s.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let l=null;try{return l=this.createWebTransportSession(),await rt(l.start(),this.opts.quicDeadlineMs??dn,"quic connect deadline"),this.wtDialedHost=nt(this.offer.webtransport?.url)??this.wtDialedHost,this.engageQuicDataLane(l,s.wtData===!0),this.session=l,d&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(c){if(console.warn(`[urun] WT dial failed (${se(c)}) \u2014 dialed ${cn(this.offer.webtransport?.url)}`),l?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let u=String(c instanceof Error?c.message:c);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${u}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(u),c}console.warn("[urun] webtransport failed, falling back to webrtc:",c),this.proceedWebRtcDial(`wt failed: ${String(c instanceof Error?c.message:c)}`),this.notifyEstablished("webrtc",String(c instanceof Error?c.message:c))}}if(this.opts.allowWebRtcFallback===!1){let l=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${l} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(l),new Error(`[urun] WT required but unavailable: ${l}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.disconnected=!0,this.wtRedialTimer!==null&&(clearTimeout(this.wtRedialTimer),this.wtRedialTimer=null),this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,await e?.stop()}noteOfferedWtHost(){let e=nt(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}`+(mr(e)?" \u2014 the offered host looks INTERNAL (RFC1918/.internal): an external browser cannot dial it":"")+` (mismatch #${this.wtHostMismatchCount}) \u2014 evidence only, no policy change`))}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let n=this.session,r=this.opts.dataLane!==void 0,s=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",o=this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",a=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",d=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:ln,wtData:r,wtAudio:s,wtAudioUp:o,wtVideoUp:a,wtDataUp:d}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let l=this.createWebTransportSession();try{await rt(l.start(),this.opts.quicDeadlineMs??dn,"quic connect deadline")}catch(c){throw console.warn(`[urun] WT dial failed (${se(c)}) \u2014 dialed ${cn(this.offer.webtransport?.url)}`),l.stop().catch(()=>{}),c}if(this.wtDialedHost=nt(this.offer.webtransport?.url)??this.wtDialedHost,this.session!==n)return l.stop().catch(()=>{}),null;try{this.engageQuicDataLane(l,r)}catch(c){throw l.stop().catch(()=>{}),c}if(this.disconnected)return l.stop().catch(()=>{}),null;this.session=l;{let c=this.offer.webtransport;c&&(this.opts.audioLane===void 0||c.audio!==void 0)&&(this.opts.audioUplink===void 0||c.audioUp===!0)&&(this.opts.videoUplink===void 0||c.videoUp===!0)&&(this.opts.dataLane===void 0||c.data===!0)&&(this.opts.dataUplink===void 0||c.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),n?.stop().catch(()=>{}),l}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let n=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(r,s)=>n.onData(r,s),onLaneError:r=>n.onLaneError(r)}),n.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e,this.opts.audioLane);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new Te(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.onWtLegDeath?.(t),this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; re-dialing WT (attempt 1 immediate, then the bounded ladder)`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.redialWtAfterDeath(t,!0);return}let n=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),n){this.session=null,this.wtOnlyLeg=!1,console.warn("[urun] quic died mid-session on a WT-only leg \u2014 RE-DIALING WebTransport first (same session id; the late WebRTC dial is the fallback):",t),this.redialWtAfterDeath(t,!0);return}console.warn("[urun] quic died mid-session, failing over to webrtc:",t),this.lateWebRtcFailover(e,t,n)})}redialWtAfterDeath(e,t=!1){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures>=i.WT_REDIAL_MAX){if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT re-dial failed ${i.WT_REDIAL_MAX} times (${e}) \u2014 WT-REQUIRED policy: no WebRTC floor exists to escalate to; the forever-retry continues in the background`),this.opts.onWtRequiredOutage?.(e);return}console.error(`[urun] WT re-dial failed ${i.WT_REDIAL_MAX} times (${e}) \u2014 standing up the deferred WebRTC dial as the floor; WT keeps retrying in the background`),this.proceedWebRtcDial(`wt re-dial spent: ${e}`),this.lateWebRtcFailover(null,e,!0);return}let n=this.wtRedialFailures+1,r=it(i.WT_REDIAL_BASE_MS,n,i.WT_REDIAL_CAP_MS,n===1&&t?0:void 0);console.warn(`[urun] WT re-dial attempt ${n} scheduled in ${Math.round(r)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},r)}async attemptWtRedial(e){if(!(this.disconnected||this.session!==null)){if(this.signaling.isOpen?.()===!1){this.redialWtAfterDeath(`${e}; signaling socket closed \u2014 waiting for the reconnect`);return}this.wtRedialFailures+=1;try{if(await this.retryWebTransport()!==null){console.warn(`[urun] WT leg re-established on the live session (re-dial attempt ${this.wtRedialFailures}/${i.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(t){let n=se(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${i.WT_REDIAL_MAX} failed (${n}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${n}`)}}}lateWebRtcFailover(e,t,n){this.disconnected||(async()=>{let r=this.createWebRtc();try{let s=await rt(this.startWebRtcOn(r),this.opts.webRtcFailoverDeadlineMs??fr,"webrtc failover produced no media transport");if(this.session!==e){s.stop().catch(()=>{});return}this.session=s,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(s){if(r.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=s instanceof Error?s.message:String(s),a=n?`media transport lost \u2014 the WebTransport connection dropped (${t}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${t}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;console.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function se(i){if(i instanceof Error)return i.message;if(typeof i=="string")return i;if(i&&typeof i=="object"){try{let e=JSON.stringify(i);if(e!==void 0&&e!=="{}")return e}catch{}return i.constructor?.name??Object.prototype.toString.call(i).slice(8,-1)}return String(i)}function nt(i){if(i)try{return new URL(i).host}catch{return}}function cn(i){if(!i)return"(no offer url)";try{let e=new URL(i);return e.searchParams.delete("token"),e.toString()}catch{return i.replace(/[?&]token=[^&\s]*/g,"")}}function mr(i){if(!i)return!1;let e=i.replace(/^\[/,"").split("]")[0]?.split(":")[0]??"";return/^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(e)?!0:e.endsWith(".internal")||e.endsWith(".svc.cluster.local")||/^ip-\d+(-\d+)+/.test(e)}function it(i,e,t,n){if(n!==void 0)return n;let r=Math.min(i*2**Math.max(0,e-2),t);return Math.round(r*(.75+Math.random()*.5))}function rt(i,e,t){return new Promise((n,r)=>{let s=setTimeout(()=>r(new Error(t)),e);i.then(o=>{clearTimeout(s),n(o)},o=>{clearTimeout(s),r(o)})})}var gr=1e4,Re=class{constructor(e,t=gr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let n=ce();return new Promise((r,s)=>{let o=setTimeout(()=>{a(),s(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(d=>{if(d.type!==`${e}.response`||d.requestId!==n)return;if(clearTimeout(o),a(),d.error){s(new Error(`[urun] ${e} failed: ${String(d.error)}`));return}let{type:l,requestId:c,...u}=d;r(u)});this.carrier.sendSignal({type:e,requestId:n,...t})||(clearTimeout(o),a(),s(new Error(`[urun] signaling request not sent: ${e} \u2014 the signaling socket is not open`)))})}notify(e,t){this.carrier.sendSignal({type:e,...t})||this.carrier.emitDiagnostic({level:"warning",kind:"signaling-notify-undelivered",message:`signaling notify not sent: ${e} \u2014 the signaling socket is not open`,detail:{method:e}})}on(e,t){return this.carrier.onSignal(n=>{n.type===e&&t(n)})}};var vr="video",Ee=class{constructor(e,t=vr){this.transport=e;this.streamName=t;this.firstMedia=new Promise((n,r)=>{this.firstMediaResolve=n,this.firstMediaReject=r}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let n=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(n(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(n)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};function un(i){let e=i;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var wr="video";var br=45e3;async function yr(i,e,t){let r=e?.current()?.name??null;if(r==="live")return"live";if(r==="error")return"gone";if(r==="idle"||r==="connecting")return"live";if(!e)return"unconfirmed";let s=e,o=t.runtimeWaitCapMs??br;return new Promise(a=>{let d=!1,l,c=null,u=null,h=!1,m=v=>{d||(d=!0,p(),u!==null&&(clearTimeout(u),u=null),l?.(),a(v))};u=setTimeout(()=>{if(h||d||t.isDisposed())return;h=!0;let v=s.current();i.emitDiagnostic({level:"info",kind:"runtime-pending",message:`waiting for a runtime to pick up session ${t.sessionId} (server status: ${v?.reason??v?.name??"unknown"}) \u2014 media negotiation starts once the runtime is live; this is not a transport failure`})},2e3);let S=()=>{c===null&&!d&&(c=setTimeout(()=>m("unconfirmed"),o))},p=()=>{c!==null&&(clearTimeout(c),c=null)};l=e.subscribe(v=>{let w=v?.name;if(w==="live")return m("live");if(w==="error")return m("gone");p(),Oe(w)||S()}),Oe(r)||S()})}function hn(i,e,t){let n=globalThis,r=n.document;if(!(typeof r?.createElement=="function"&&typeof n.WebTransport=="function"&&typeof n.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=i.holdWebRtcDial?.(),a=r.createElement("canvas"),d=!1,l=null,c=!1,u=()=>{if(l){for(let y of l.getVideoTracks())try{y.stop()}catch{}l=null}c&&(c=!1,t.onOverrideTrack(null))},h=new Ae(new Re(i),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new Ee(i,t.streamName??wr)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(y,T)=>i.dispatchQuicStreamData(y,T),onQuicLane:()=>i.markStreamDataLaneQuic(),onQuicLaneLost:y=>i.quicStreamDataLaneLost(y),onLaneError:y=>i.raiseQuicStreamDataError(y)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,ctx:t.audioPlayout?.audioContext,onTrack:y=>{d||(y&&i.noteQuicMediaFlowing?.(),t.onOverrideAudioTrack(y))}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>D(),onMediaTransportLost:y=>{d||(u(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(y),D())},onWtLegDeath:()=>{i.noteMediaLegDeath?.()},onTransportChange:(y,T)=>{d||(y==="webrtc"&&(u(),D()),t.onTransportChange?.(y,T))}}),m=i.onWtOnlyLegDeath?.(y=>h.failCurrentWtLeg(y)),g=null,S=()=>{g!==null&&(clearInterval(g),g=null)},p=t.wtRetryBaseMs??2e3,v=t.wtRetryCapMs??3e4,w=null,R=0,D=()=>{if(d||w!==null||h.activeTransport==="webtransport")return;let y=it(p,R+2,v);w=setTimeout(()=>{w=null,R+=1,h.retryWebTransport().then(T=>{if(d){T&&h.disconnect().catch(()=>{});return}if(T)return console.debug(`[urun] webtransport upgraded in background (retry ${R})`),R=0,E(T);D()}).catch(T=>{d||(console.debug(`[urun] webtransport background retry ${R} failed: `+se(T)),D())})},y)},U=()=>{w!==null&&(clearTimeout(w),w=null)},E=async y=>{if(d||y.kind!=="webtransport")return;let T=t.pathHealthProbeMs??1e4;S();let V=!1;g=setInterval(()=>{if(d||h.activeTransport!=="webtransport")return;let W=un(y);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)"),S();return}let $=W.pathLiveness();if(!$.alive){let C=h.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${$.evidence}`+(C?" \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"),S(),W.fail(`path health: ${$.evidence}`);return}if(!V){if(V=!0,h.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${T}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 ${T}ms \u2014 no media datagrams reached this client (path healthy: ${$.evidence}); webrtc track remains authoritative`)}},T);try{await y.firstMedia}catch(W){S(),console.debug("[urun] webtransport ended before any media flowed:",W);return}if(S(),d||h.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;l=a.captureStream();let G=l.getVideoTracks()[0];G&&(c=!0,t.onOverrideTrack(G))},I=!1;return(async()=>{let y=await yr(i,t.runtimePhase,{sessionId:e,runtimeWaitCapMs:t.runtimeWaitCapMs,isDisposed:()=>d});if(d)return;if(y==="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}I=!0;let T=await h.connect();if(d){h.disconnect().catch(()=>{});return}await E(T)})().catch(y=>{if(S(),d){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",y);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",y),D();return}o?.proceed(`negotiation unavailable: ${y instanceof Error?y.message:String(y)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",y),D()}),{activeTransport:()=>h.activeTransport,mediaTransportAttempted:()=>I,watchDownlinkStall(y){h.watchDownlinkStall(y)},dispose(){d=!0,m?.(),S(),U(),u(),t.onOverrideAudioTrack?.(null),h.disconnect().catch(()=>{})}}}var kr=new Set;function dt(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var Sr="rpc",_r="$presence",st=["control",qe],pn=2e4,Tr=3e4,fn=3e4,Ar="rpc-resp";function Rr(i){return`${Ar}:${i}`}function ot(){return ce()}function Er(i){if(i&&typeof i=="object"){let e=i.error;if(e&&typeof e=="object"){let{message:t,code:n}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof n=="string"?n:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof i=="string"?i:JSON.stringify(i)}}function Dr(i,e,t,n,r,s,o,a,d,l){let c=[],u=null,h=!1,m=null,g=!1,S,p,v=new Promise((f,A)=>{S=f,p=A});v.catch(()=>{});let w=o(),R=null,D=null,U=null,E=null,I=null,y=null,T=!0,V=()=>{U&&(clearTimeout(U),U=null),E&&(E(),E=null)},G=()=>{I&&(clearTimeout(I),I=null),y&&(y(),y=null)},W=!1,$=()=>{W||!g||(W=!0,i.delete(["rpc",e]))},C=()=>{T=!1,V(),G(),R?.(),R=null,D?.(),D=null,a?.removeEventListener("abort",Ie),w.dispose(),$()},K=()=>{if(u){if(c.length>0){let f=u;u=null,f.resolve({value:c.shift(),done:!1})}else if(m!==null){let f=u;u=null,f.reject(m)}else if(h){let f=u;u=null,f.resolve({value:void 0,done:!0})}}},Q=f=>{h||(c.push(f),K())},B=f=>{h||(m=f,h=!0,p(f),C(),K())},Z=f=>{h||(h=!0,S(f),C(),K())},Ie=()=>{let f=a?.reason;B(f instanceof Me?f:new xe(e))},b=f=>{if(!(h||!f||typeof f!="object"))switch(G(),$(),f.t){case"delta":typeof f.delta=="string"&&Q(f.delta);break;case"response":Z(f.body);break;case"error":{let{message:A,code:P}=Er(f.body);B(new Me(A,{requestId:e,code:f.code??P}));break}}},k=()=>{let f=w.messages()[Symbol.asyncIterator]();R=()=>{f.return?.(void 0)};let A=()=>{T&&f.next().then(P=>{if(T){if(P.done){h||Z(void 0);return}b(P.value),A()}},P=>{T&&B(P)})};A()},L=()=>{if(!g){if(g=!0,a){if(a.aborted){B(new xe(e));return}a.addEventListener("abort",Ie,{once:!0})}D=d?.(f=>B(f))??null,k(),i.set({rpc:{[e]:{args:t,respond_on:n,consumer_id:r,stream:s}}}),l&&l>0&&!i.synced&&(U=setTimeout(()=>{U=null,!h&&!i.synced&&B(new ft(l,e))},l),E=i.onSynced(()=>V())),y=i.onSynced(()=>{y=null,!(h||W||I)&&(I=setTimeout(()=>{I=null,!(h||W)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(fn/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).`)},fn))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(L(),c.length>0)return Promise.resolve({value:c.shift(),done:!1});if(m!==null){let f=m;return m=null,Promise.reject(f)}return h?Promise.resolve({value:void 0,done:!0}):new Promise((f,A)=>{u={resolve:f,reject:A}})},return(){return h||(h=!0,S(void 0),C()),Promise.resolve({value:void 0,done:!0})},throw(f){return h||(h=!0,p(f),C()),Promise.reject(f)}}}},body:v,start:L}}function mn(i){if(i&&typeof i=="object"){let{epoch:e,by:t}=i,n={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(n.by=t),n}}function Lr(i,e){let n=i.get("streams")?.[e];if(!n||typeof n!="object")return null;let{kind:r,rt:s,br:o}=n,a={};(r==="audio"||r==="video"||r==="data")&&(a.kind=r);let d=mn(s);d&&(a.rt=d);let l=mn(o);return l&&(a.br=l),a}var at=class{constructor(e,t,n,r,s){this._name=e;this._transport=t;this._streamData=n;this._controlDoc=r;this._onActivity=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_directOut=!1;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],n=null,r=!1,s=null,o={push(d){if(!r)if(n){let l=n;n=null,l.resolve({value:d,done:!1})}else t.push(d)},end(){if(r=!0,n){let d=n;n=null,d.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{r=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(d=>{if(!(d===null||r)&&(s=e._streamConsumeUnavailableError(d),a(),n)){let l=n;n=null,l.reject(s)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.reject(s):r?Promise.resolve({value:void 0,done:!0}):new Promise((d,l)=>{n={resolve:d,reject:l}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}get directOut(){return this._directOut}_setOverrideTrack(e,t){if(this._overrideTrack===e&&this._directOut===(t?.directOut??!1))return;this._overrideTrack=e,this._directOut=e?t?.directOut??!1:!1,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let n=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let s of r)s(n)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),n=Lr(t,this._name),r=n?.br;if(r?.by==="runtime")throw new mt(this._name,"runtime","browser");if(r)return;let s={br:{epoch:1}};n?.rt&&(s.rt=n.rt);let o=n?.kind??e;o&&(s.kind=o),t.set({streams:{[this._name]:s}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??Qt;return Yt(t,{track:()=>this.track,onTrack:r=>this.on("track",r)})}onSeeked(e){return this._transport.on("seeked",(t,n)=>{t===this._name&&e(n)})}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n?.delete(t),n?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let n of t)n(e)}},De=class i{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new It;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_gateDocUp={};_gate="open";_gateTimer=null;_gateDocUnsubs=[];_gateOff=!1;_gatedFrom;_gatedWith;_publicPhase;_phaseHandlers=new Set;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_namedSessionIdProbe;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,n,r,s,o){this._sessionId=e,this._multiplexer=t,this._transport=n,this._recordingsAuth=r,this._artifactsAuth=s,this._streamData=Wt(n),this._wireControlDocIncarnation(),this._lifecycleUnsub=jt(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=Ht({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new me({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(_r).awareness.setLocalState({role:"client"}),this._activation=new pe({onPhase:a=>this.onPhase(a),hint:()=>this.doc(qe).get(Mt)??this.doc("control").get(xt),onData:(a,d)=>this._streamData.onData(a,d)}),this._transport.on("phase",()=>this._applyLiveGate());for(let a of st)this._gateDocUnsubs.push(this.doc(a).onConnectionState(d=>{this._gateDocUp[a]=d.connected,this._applyLiveGate()}))}_applyLiveGate(){let e=this._transport.phase;if(!e)return;let t=this._gateOff||!this._docConnector.connected||st.every(s=>this._gateDocUp[s]);if(e.name!=="live"||t?(clearTimeout(this._gateTimer??void 0),this._gateTimer=null,this._gate="open"):this._gate==="open"&&(this._gate="connecting",this._gateTimer=setTimeout(()=>{this._gateTimer=null,this._gate="failed",this._applyLiveGate()},pn)),e===this._gatedFrom&&this._gate===this._gatedWith)return;this._gatedFrom=e,this._gatedWith=this._gate;let n=st.filter(s=>!this._gateDocUp[s]).join("/"),r=this._gate==="open"?e:this._gate==="connecting"?{...e,name:"connecting",reason:"docs_connecting"}:{...e,name:"error",reason:"doc_plane_unreachable",error:{kind:"transport-failed",code:"doc_plane_unreachable",reason:`the session's ${n} doc connection did not open within ${pn/1e3}s (still retrying)`}};if(r!==this._publicPhase){this._publicPhase=r;for(let s of[...this._phaseHandlers])s(r)}}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let n=await Rt({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),r=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,s=new oe,o=new ue({url:n.wsUrl,orgId:t.orgId,jwt:r,authProvider:t.authProvider,sessionId:e,iceServers:n.response.ice_servers}),a=new i(e,s,o,dt(t),ee({...t,baseUrl:n.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&s.setTarget(o.multiplexer)}),o.setConnection({url:n.wsUrl,sessionId:e,iceServers:n.response.ice_servers}),o.setEndsAt(n.endsAt),ae()&&await de();let d=t.getAccessToken,l=d?c=>!c?.redial&&r?r:Promise.resolve(d()).then(u=>u??r):r;return a.setDocTransport({wsUrl:n.wsUrl,token:l}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase!==this._gatedFrom&&this._applyLiveGate(),this._publicPhase??this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){let e=this._transport.status,t=this.phase;return!e||!t||t===this._transport.phase?e:{...e,phase:t.name,...t.error?{error:t.error}:{}}}get region(){return this._transport.region}onPhase(e){return e(this.phase),this._phaseHandlers.add(e),()=>{this._phaseHandlers.delete(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 vt(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=$t(this.doc("control"),n=>{for(let r of Array.from(this._generationTickHandlers))try{r(n)}catch(s){console.warn("[urun] generationTick handler failed:",s)}})),()=>{this._generationTickHandlers.delete(t),this._generationTickHandlers.size===0&&(this._generationTickStop?.(),this._generationTickStop=null)}}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new ne(e);return this._recordingsAccessor={list:n=>t.list(n??this._sessionId),get:n=>t.get(n),retain:(n,r)=>t.retain(n,r),pin:n=>t.pin(n),unpin:n=>t.unpin(n),permanent:n=>t.permanent(n),delete:n=>t.delete(n)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new J(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new J(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let n of this._docs.values())n.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}setNamedSessionIdProbe(e){this._namedSessionIdProbe=e}namedSessionId(){return this._namedSessionIdProbe?.()}stream(e){let t=this._streams.get(e);return t||(t=new at(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 Ct(e,this._sessionId,kr.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Pt(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=he(e.wsUrl),n=typeof e.token=="function"?"<token-supplier>":e.token??"",r=e.attach?`${e.attach.gen}:${e.attach.token}`:"",s=`${t}${n}${r}${this._sessionId}`;s!==this._docEndpointKey&&(this._docEndpointKey=s,this.connectDocs(Ut({serverUrl:t,sessionId:this._sessionId,token:e.token,attach:e.attach,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let n=ot(),r=new AbortController;t.signal&&(t.signal.aborted?r.abort(t.signal.reason):t.signal.addEventListener("abort",()=>r.abort(t.signal.reason),{once:!0}));let s=null;if(typeof t.timeout=="number"&&t.timeout>=0){let d=t.timeout;s=setTimeout(()=>r.abort(new pt(d,n)),d)}let o=this._consumeResponse(n,e,!1,r.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{s&&clearTimeout(s),a?.()})}_consumeResponse(e,t,n,r,s){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(Sr),a=Rr(e);return Dr(o,e,t,a,this._streamData.consumerId,n,()=>this.stream(a),r,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),s??Tr)}requestStream(e,t={}){let n=ot();return this._consumeResponse(n,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let n=ot(),r=this._consumeResponse(n,e,!1,t.signal,t.docSyncTimeout);return r.start(),r.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}connect(){return this._transport.connect()}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=hn(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 X)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new X);let e=this._cancelHandler().then(t=>(this.disconnect(),t));return this._cancelPromise=e,e.catch(()=>{this._cancelPromise===e&&(this._cancelPromise=void 0)}),e}disconnect(){this.detach()}detach(e){let t=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let r of t)try{r()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let n=Array.from(this._activeRequests);this._activeRequests.clear();for(let r of n)try{r(new gt)}catch{}this._gateOff=!0,clearTimeout(this._gateTimer??void 0),this._gateTimer=null;for(let r of this._gateDocUnsubs.splice(0))r();for(let r of this._docs.values())r.dispose();this._docs.clear();for(let r of this._streams.values())r.dispose();this._streams.clear(),this._transport.disconnect(e)}};var Wr={failed:!0,rejected:!0,expired:!0,cancelled:!0,canceled:!0,closed:!0},Ur={idle:!0,queued:!0,provisioning:!0,waiting_for_capacity:!0,unavailable:!0,connecting:!0};function Ir(i){return Ur[i]===!0}function gn(i){let e=i.fetchImpl??globalThis.fetch,t=i.baseUrl.replace(/\/+$/,""),n=null,r=!1,s=!1,o=0,a=i.transport.on("phase",h);function d(){s||(s=!0,a(),u())}function l(){o+=1,o>=15&&d()}async function c(){if(!r){r=!0;try{let m=await i.jwt?.(),g=await e(`${t}/api/session-requests/${encodeURIComponent(i.requestId)}?wait_s=15`,{...m?{headers:{authorization:`Bearer ${m}`}}:{},signal:Cr(20*1e3)});if(g.status===404||g.status===410){d();return}if(g.ok){let S=await g.json().catch(()=>{}),p=typeof S?.status=="string"?S.status:void 0;if(p!==void 0&&Wr[p]===!0){d();return}o=0;return}l()}catch{l()}finally{r=!1}}}function u(){n!==null&&(clearInterval(n),n=null)}function h(){if(Ir(i.transport.phase.name)){n===null&&(n=setInterval(()=>{c()},2e4),n.unref?.());return}u()}return h(),d}function Cr(i){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(i):void 0}function vn(i){return`urun:session:v2:${i.orgId}:${i.app}:${i.functionName}`}function lt(){try{return globalThis.sessionStorage??null}catch{return null}}var ct=new Map;function Le(i){if(!i)return;let e=i.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=JSON.parse(atob(t+"=".repeat((4-t.length%4)%4)));return typeof n?.sub=="string"&&n.sub.length>0?n.sub:void 0}catch{return}}function Pr(i,e){return i!==void 0&&e!==void 0&&i!==e}function ut(i,e){let t=lt(),n=null;if(t)try{let s=t.getItem(i);if(s){let o=JSON.parse(s);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(n={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{n=null}let r=ct.get(i)??n??null;return!r||Pr(r.actor,e)?null:r}function wn(i,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};ct.set(i,t);let n=lt();if(n)try{n.setItem(i,JSON.stringify(t))}catch{}}function We(i){ct.delete(i);let e=lt();if(e)try{e.removeItem(i)}catch{}}var bn=new Set(["paused","acquiring","live"]),Mr=new Set(["24h","keep"]);function yn(i){if(typeof i!="string"||i.length===0)return null;let e=new Date(i);return Number.isFinite(e.getTime())?e:null}function xr(i){if(typeof i?.id!="string"||i.id.length===0)throw new Pe("[urun] session list returned a row with no id \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_row"});if(typeof i.state!="string"||!bn.has(i.state))throw new Pe(`[urun] session ${i.id} reported an unrecognized state ${JSON.stringify(i.state)} \u2014 this @urun-sh/core build knows only ${[...bn].join(", ")}. The SDK may be out of date for this control plane. NOTE: there is no terminal session state; a word like "closed" or "ended" arriving here is a server-side bug.`,{code:"unknown_session_state"});let e=!1;return typeof i.recordings_expired=="boolean"?e=i.recordings_expired:console.warn(`[urun] session ${i.id} list row has no recordings_expired (or a non-boolean value) \u2014 this control plane predates it; treating the session as not-expired`),{id:i.id,label:typeof i.label=="string"&&i.label.length>0?i.label:null,state:i.state,app:typeof i.app=="string"?i.app:"",functionName:typeof i.function=="string"?i.function:"",createdAt:yn(i.created_at),lastActiveAt:yn(i.last_active_at),archived:i.archived===!0,preview:typeof i.preview=="string"&&i.preview.length>0?i.preview:null,recordingsExpired:e,retention:Mr.has(i.retention)?i.retention:(i.retention!==void 0&&console.warn(`[urun] session ${i.id} reported an unrecognized retention ${JSON.stringify(i.retention)} \u2014 defaulting to '24h'`),"24h")}}var Ue=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:n}=await _t({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(xr),nextCursor:n}}async end(e){await Tt({...this._request,sessionId:e})}async archive(e){await $e({...this._request,sessionId:e,archived:!0})}async unarchive(e){await $e({...this._request,sessionId:e,archived:!1})}async setName(e,t,n={}){await At({...this._request,sessionId:e,name:t,source:n.source})}};function kn(i,e,t){let n=Le(t);wn(i,n!==void 0?{sessionId:e,actor:n}:{sessionId:e})}var Or=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Es(i,e){return new Ue(i,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function Ds(i,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(t,n){if(!(Or.has(n)||typeof n!="string"))return(r,s)=>{let o=r??{},a=vn({orgId:e.orgId,app:i,functionName:n}),d=!s?.sessionId&&!e.sessionKey&&!!s?.label,l,c=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,u=c(),h=e.jwt,m=e.getAccessToken?async b=>{let k=await e.getAccessToken(b);return k&&(h=k),k}:void 0,g={...e,getAccessToken:m},S=new oe,p=new ue({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:u,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),v=new De(u,S,p,dt(g),ee(g),{activity:s?.activity}),w,R=!1,D,U=!1,E,I,y=new Promise(b=>{I=b}),T,V=b=>{b.sessionId||E||(E="teardown",T="ticket",Ne({baseUrl:b.baseUrl,requestId:b.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider}))},G=b=>{E||b.sessionId||(E="abandon",Ne({baseUrl:b.baseUrl,requestId:b.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider,reason:"client_abandoned"}))},W=b=>{let k=b.sessionId||!l?b:{...b,sessionId:l};w=k,I({status:"ready",handle:k}),(U||E==="teardown")&&V(k)};v.setNamedSessionIdProbe(()=>w?.sessionId),v.setEndHandler(async()=>{let b=w?{status:"ready",handle:w}:await y;if(b.status==="unavailable")throw new X("[urun] session allocation failed before a releasable request was created",{cause:b.cause});let k=w??b.handle;return We(a),E==="teardown"?k.sessionId?{status:"paused",sessionId:k.sessionId,reason:"client_ended"}:{status:"canceled",requestId:k.requestId}:(E="end",k.sessionId?yt({baseUrl:k.baseUrl,sessionId:k.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider}):Fe({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider}))}),v.setCancelHandler(async()=>{let b=w?{status:"ready",handle:w}:await y;if(b.status==="unavailable")throw new X("[urun] session allocation failed before a cancellable request was created",{cause:b.cause});let k=w??b.handle;if(k.sessionId)throw new ht(`[urun] cancel() is for a queued admission request, but this call already has session ${k.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:k.sessionId,code:"cancel_on_live_session"});E="end";try{let L=await Fe({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider});return We(a),L}catch(L){throw E==="end"&&(E=void 0),L}});let $=async b=>{let k,L=s?.sessionId??e.sessionKey??l,x,f;if(L===void 0&&!d){let M=ut(a);if(M?.sessionId){if(f=Le(h),M.actor!==void 0&&f===void 0&&m){let z=await Promise.resolve(m()).catch(()=>{});f=Le(z??e.jwt)}x=M.actor!==void 0&&f!==void 0&&M.actor!==f?void 0:M.sessionId}}let A=L??x,P=(M,z)=>kt({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:n,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider,...e.shape?{shape:e.shape}:{},idempotencyKey:M,sessionKey:z,label:s?.label,...s?.sharedApp?{sharedApp:!0}:{},concurrencyKey:s?.concurrencyKey,priority:e.priority,onAdmission:F=>{p.reportAdmission(F),F.sessionId&&!l&&(l=F.sessionId,k=F.sessionId,w&&w.sessionId!==F.sessionId&&W({...w,sessionId:F.sessionId}),R||(e.sessionKey||kn(a,F.sessionId,h),v.setSessionId(F.sessionId)))},onRequest:W}),_;try{_=await P(b,A)}catch(M){let z=M instanceof Y&&M.code==="session_name_not_yours"&&A!==void 0&&A===l&&s?.sessionId===void 0&&e.sessionKey===void 0;if(x===void 0&&!z||!(M instanceof Y)||M.code!=="session_name_not_yours")throw M;let F=x??A;if(F===void 0)throw M;console.warn(`[urun] session_name_not_yours: the control plane refused session ${F} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),z&&(l=void 0),ut(a,f)?.sessionId===F&&We(a),_=await P(c(),void 0)}let Ce=m?await m()??void 0:e.jwt;if(k&&k!==_.sessionId)throw w&&w.sessionId!==_.sessionId&&W({...w,sessionId:_.sessionId}),new Y(`Gateway contract violation: admission minted session ${k} but allocation completed as ${_.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return l=_.sessionId,w&&w.sessionId!==_.sessionId&&W({...w,sessionId:_.sessionId}),R||(e.sessionKey||kn(a,_.sessionId,h),v.setSessionId(_.sessionId),Q=bt(_.baseUrl)?{baseUrl:_.baseUrl,sessionId:_.sessionId}:null,v.setArtifactsAuth(ee({...g,baseUrl:_.baseUrl})),p.setEndsAt(_.endsAt),p.seedRegion(Et(_.response))),{url:_.wsUrl,sessionId:_.sessionId,jwt:Ce,iceServers:_.response.ice_servers,endsAt:_.endsAt,sfuAttach:_.sfuAttach}},C,K,Q=null,B=m?b=>!b?.redial&&C?C:Promise.resolve(m(b?.redial?{forceRefresh:!0,reason:"background"}:void 0)).then(k=>C=k??C):()=>C,Z=()=>{let b=p.connectedUrl;return b?he(b):void 0};if(p.setConnectionResolver(async()=>{let b=await $(c());return C=b.jwt,K=b.sfuAttach,b}),p.setConnectionViewRefresher(async()=>Q?St({baseUrl:Q.baseUrl,sessionId:Q.sessionId,jwt:h}):null),p.on("connected",()=>{p.multiplexer&&S.setTarget(p.multiplexer);let b=p.connectedUrl;b&&v.setDocTransport({wsUrl:b,token:B,attach:K,resolveServerUrl:Z})}),(async b=>{let k;try{k=await $(b)}catch(f){if(R){I({status:"unavailable",cause:f});return}console.error(`[urun] Failed to create session for ${n}:`,f),w&&G(w);let A=f instanceof Error?f:new Error(String(f)),P=f instanceof Y?f.httpStatus:void 0,_=f instanceof Y?f.code:void 0,Ce=f instanceof Y?f.retryAfterSeconds:void 0;p.reportAllocationFailure(A,P,_,Ce),I({status:"unavailable",cause:f});return}if(R)return;let L=Q!==null?null:e.baseUrl,x=w?.requestId;L!==null&&x!==void 0&&!R&&(D=gn({requestId:x,baseUrl:L,jwt:async()=>m?await m()??h:h,transport:p})),p.setAuth({jwt:k.jwt,authProvider:e.authProvider,orgId:e.orgId}),p.setConnection({url:k.url,sessionId:k.sessionId,iceServers:k.iceServers,sfuAttach:k.sfuAttach}),ae()&&await de(),C=k.jwt,K=k.sfuAttach,v.setDocTransport({wsUrl:k.url,token:B,attach:K,resolveServerUrl:Z}),await p.connect({app:i,functionName:n,args:o}),v.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback})})(u).catch(b=>{console.error(`[urun] Failed to connect session for ${n}:`,b)}),e.releaseOnLeave!==!1){let b=Vt(()=>{if(R=!0,D?.(),D=void 0,p.leaveLeg())return;if(p.connectedUrl!==null){p.disconnect();return}p.disconnect();let A=w;A?V(A):U=!0});v.onDisconnect(b);let k,L,x=!1,f=()=>{x||(x=!0,k?.(),L?.())};y.then(A=>{A.status!=="ready"||x||(k=Kt(()=>w!==void 0))}),L=v.onPhase(A=>{let P=A?.name;(P==="paused"||P==="error")&&f()}),x&&L(),v.onDisconnect(f)}return v}}})}export{Nr as a,Fr as b,$r as c,qe as d,Mt as e,xt as f,Sn as g,pe as h,O as i,He as j,Be as k,Br as l,J as m,q as n,fe as o,je as p,Ve as q,Ke as r,Ge as s,te as t,Ft as u,Vr as v,ne as w,Kr as x,Qr as y,Yr as z,$t as A,Ln as B,Wn as C,Xr as D,qt as E,Ht as F,Un as G,In as H,Zr as I,me as J,ti as K,jt as L,Vt as M,Kt as N,Qt as O,xn as P,zt as Q,ge as R,N as S,we as T,Zt as U,be as V,Hn as W,ze as X,tn as Y,Te as Z,Ae as _,Re as $,Ee as aa,pn as ba,Tr as ca,De as da,Ue as ea,Es as fa,Ds as ga};