@urun-sh/core 0.6.18 → 0.6.20

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.
@@ -1,4 +1,4 @@
1
- import{$ as rn,B as Te,C as Yr,D as Qr,E as Xr,F as Jr,G as Zr,H as J,I as Ft,J as Re,K as Ze,L as $t,M as qt,N as Bt,O as et,P as jt,Q as Ht,R as Vt,S as en,T as Gt,U as Ae,V as tt,W as tn,X as rt,Z as Kt,a as Nt,aa as nn,b as ye,ba as sn,c as G,ca as on,d as Ke,da as Ee,e as be,f as Se,fa as Ce,g as ze,ga as zt,h as Ye,ha as Yt,i as Qe,ia as Qt,j as Nr,ja as Xt,k as Fr,l as ke,m as Xe,n as $r,o as qr,p as Br,q as jr,r as K,s as Hr,t as Vr,u as Gr,v as Kr,w as Je,x as zr,y as _e}from"./chunk-5KH6VNMJ.mjs";var an=15e3,dn=45e3,cn=12e4,nt="platform",it="activation",st="desired.activation";function Jt(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 ln=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],ne=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 r of this._watches.values())this._arm(r)}}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 r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}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=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let n=()=>this._firstMedia(e);r.addEventListener("unmute",n,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",n));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),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 ln){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_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,r){let n={state:t,elapsedMs:r,stream:e.name},s=Jt(this._options.hint());s!==void 0&&(n.hint=s),e.lastEvent=n;for(let o of Array.from(this._handlers))o(n)}};var D=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",n){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,n!==void 0&&(this.cause=n),Object.setPrototypeOf(this,new.target.prototype)}},Ie=class extends D{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},De=class extends D{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function ie(i){return{baseUrl:i.baseUrl,fallbackUrls:i.fallbackUrls,orgId:i.orgId,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}function un(i){return new z(i)}var z=class{_options;constructor(e){this._options=e}async list(e){let r=er(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new D("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(Zt)}async getDownloadUrl(e,t){let r=er(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!hn(n))throw new D("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Zt(r.artifact),downloadUrl:n}}async _request(e,t){let r=Ft(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let s of r)try{return await this._requestFromBase(s,e,t)}catch(o){if(n=o instanceof Error?o:new Error(String(o)),n instanceof D&&fn(n.status))throw n}throw n??new D("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${J(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,s=await this._resolveToken(),o=await fetch(n,{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(n,{method:"GET",headers:this._headers(s)}))}if(!o.ok){let{code:a,message:d}=await this._readError(o,e);throw mn(o.status,a,d)}try{return await o.json()}catch(a){throw new D(`[urun] runtime artifacts: invalid JSON response from ${J(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 r=J(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 ${r}: ${a}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}};function Zt(i){if(!i||typeof i!="object")throw new D("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=i,t=q(e,"artifact_id")||q(e,"id"),r=q(e,"filename"),n=q(e,"kind"),s=q(e,"status")||"ready",o=pn(e,"size_bytes"),a=q(e,"sha256");if(!t||!r||!n||o==null||!a)throw new D("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:q(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:s,createdAt:q(e,"created_at"),expiresAt:q(e,"expires_at")}}function q(i,e){let t=i[e];return typeof t=="string"&&t.length>0?t:void 0}function pn(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function hn(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function fn(i){return i===401||i===403}function mn(i,e,t){return i===401?new Ie(t,e):i===404?new De(t,e):new D(t,i,e)}function er(i){if(!i||typeof i!="object"||Array.isArray(i))throw new D("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var O=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)}},se=class extends O{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Pe=class extends O{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Le=class extends O{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)}},Ue=class extends O{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)}},Me=class extends O{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)}},Z=class extends O{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",r=400){super(e,{status:r,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function ot(i){return/^(\d+[smhdw])+$/.test(i)}function gn(i){if(i==="pin")return{action:"pin"};if(ot(i))return{action:"retain",duration:i};throw new Z(`[urun] recordings: "${i}" is not a duration or "pin"`)}function vn(i,e,t){let r=t||e||`HTTP ${i}`;if(i===401)return new se(r,e??"unauthorized");if(i===404)return new Pe(r,e??"not_found");if(i===400)return new Z(r,e??"bad_request",400);if(i===409)switch(e){case"retain_not_temp":return new Le(r,e);case"pin_requires_active_temp":return new Ue(r,e);case"permanent_locked":return new Me(r,e)}return new O(r,{status:i,code:e??`http_${i}`})}var ee=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let r=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(r)?r:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!ot(t))throw new Z(`[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 O("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),s=await this._resolveToken(),o=await this._fetch(n,e,s,r.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(n,e,s,r.body))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw vn(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let s={Authorization:`Bearer ${r}`,apikey:r,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 n!==void 0&&(s["Content-Type"]="application/json",o.body=JSON.stringify(n)),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 se("[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 r=(await e.json()).error;if(r&&typeof r=="object"){let{code:n,message:s}=r;return{code:typeof n=="string"?n:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function wn(i){return new ee(i)}var yn=1e3,bn=12e3;function at(i,e,t={}){let r=null,n=0,s=0,o=null,a=-1,d=()=>{let h=i.get("desired.billing.generationSeconds");if(typeof h!="number"||!Number.isFinite(h)||h<=0)return null;let y=i.get("desired.billing.epoch"),w=i.get("desired.billing.updatedAtMs");return{seconds:h,epoch:typeof y=="number"&&Number.isFinite(y)?y:0,updatedAtMs:typeof w=="number"&&Number.isFinite(w)?w:null}},l=()=>{if(r===null)return null;let h=Math.min(Math.max(0,Date.now()-n),s);return r+h/1e3},c=()=>{let h=t.creditsPerSecond;if(typeof h=="number"&&Number.isFinite(h)&&h>0)return h;let y=i.get("desired.billing.creditsPerSecond");return typeof y=="number"&&Number.isFinite(y)&&y>0?y:null},p=()=>{let h=l();if(h===null)return;let y=Math.floor(h);if(y<=a)return;a=y;let w={seconds:y},T=c();T!==null&&(w.estimatedCredits=y*T),e(w)},u=h=>{n=Date.now();let y=h===null?0:Math.max(0,n-h);s=Math.max(0,12e3-y)},f=()=>{let h=d();if(h!==null){if(o!==null&&h.epoch!==o){o=h.epoch,r=h.seconds,a=-1,u(h.updatedAtMs),p();return}r!==null&&h.seconds<=r||(o=h.epoch,r=h.seconds,u(h.updatedAtMs),p())}};f();let m=i.on("change",f),S=setInterval(p,1e3);return S.unref?.(),()=>{clearInterval(S),m()}}var tr="activity",rr="visibility",Sn=15e3,dt=["pointerdown","pointermove","keydown","wheel","touchstart"];function ct(i){let e=i.now??Date.now,t=i.mode==="explicit",r=t?null:i.windowTarget!==void 0?i.windowTarget:typeof window<"u"?window:null,n=t?null:i.documentTarget!==void 0?i.documentTarget:typeof document<"u"?document:null,s=!1,o,a=()=>{if(s)return;let u=e();if(!(o!==void 0&&u-o<15e3)){o=u;try{i.awareness.setLocalStateField(tr,{at:u})}catch{}}},d=()=>{if(!(s||!n||n.visibilityState===void 0))try{i.awareness.setLocalStateField(rr,n.visibilityState)}catch{}},l=()=>a(),c=()=>{d(),(!n||n.visibilityState===void 0||n.visibilityState==="visible")&&a()};if(r)for(let u of dt)r.addEventListener(u,l,{passive:!0,capture:!0});n&&n.addEventListener("visibilitychange",c);let p=null;return!t&&i.isProducing&&(p=setInterval(()=>{if(!s)try{i.isProducing?.()&&a()}catch{}},15e3),p.unref?.()),a(),d(),{touch:a,dispose(){if(!s){if(s=!0,r)for(let u of dt)r.removeEventListener(u,l,{capture:!0});n&&n.removeEventListener("visibilitychange",c),p&&(clearInterval(p),p=null)}}}}var ir="user_activity",sr="focus",kn=3e4;function nr(i){switch(i){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var oe=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(nr(e.state));let t=e.on("stateChange",n=>{this._setState(nr(n))}),r=()=>{t(),this._transportUnsubs.delete(r)};return this._transportUnsubs.add(r),r}_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(sr,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(ir,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 _n=250;function lt(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 r=Date.now();r-e<250||(e=r,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 ut(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,i())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function pt(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 or="video/mp4";function ht(i,e={}){let t=e.timesliceMs??1e3,r=null,n=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 p=e.mimeType??(typeof c.isTypeSupported=="function"&&c.isTypeSupported(or)?or:void 0),u=new MediaStream([a]),f=new c(u,p?{mimeType:p}:void 0);r=f;let m=Promise.resolve();f.ondataavailable=S=>{let h=S.data;s||!h||h.size===0||(m=m.then(async()=>{let y=new Uint8Array(await h.arrayBuffer());s||d(y)}))},f.onstop=()=>{m.then(()=>{s||l()})},f.onerror=()=>{m.then(()=>{s||l()})},f.start(t)};return{start(a,d){if(r||s)return;let l=i.track();if(l){o(l,a,d);return}n=i.onTrack(c=>{!c||r||s||(n?.(),n=null,o(c,a,d))})},stop(){if(s)return;s=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Tn(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 ar(i,e){let t=null,r=!1,n=!1,s=new ReadableStream({pull(o){r||(r=!0,t=i(e),t.start(a=>{if(!n)try{o.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{o.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Tn(s)}import{encode as Rn,decode as An}from"@msgpack/msgpack";var dr=65536;function mt(i){let e=Rn(i),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var de=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>dr)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let n=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(Object.assign(An(n),{raw:n}))}return t}};function cr(i,e){let t=new DataView(i.buffer,i.byteOffset,i.byteLength),r=t.getUint8(0),n=(r&240)===128,s=r===222;if(!n&&!s&&!(r===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let a=n?r&15:s?t.getUint16(1,!1):t.getUint32(1,!1),d=n?1:s?3:5,l=[];l.push(i.subarray(0,d));for(let f=0;f<a;f++){let m=d,S=ae(i,t,d);d=S.end;let y=ae(i,t,d).end;if(En(t.getUint8(m))){let w=t.getUint8(m),T=(w&224)===160?1:w===217?2:w===218?3:5;if(new TextDecoder().decode(i.subarray(m+T,S.end))==="t"){l.push(i.subarray(m,S.end));let R=new TextEncoder().encode(e);if(R.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");l.push(new Uint8Array([160|R.byteLength]),R)}else l.push(i.subarray(m,y))}else l.push(i.subarray(m,y));d=y}let c=l.reduce((f,m)=>f+m.byteLength,0),p=new Uint8Array(c),u=0;for(let f of l)p.set(f,u),u+=f.byteLength;return p}function En(i){return(i&224)===160?!0:i===217||i===218||i===219}function ae(i,e,t){let r=e.getUint8(t),n=t;if(r<=127||r>=224)return{start:n,end:t+1};if((r&224)===160)return{start:n,end:t+1+(r&31)};if((r&240)===128||(r&240)===144){let o=r&15;t+=1;let a=(r&240)===128?o*2:o;for(let d=0;d<a;d++)t=ae(i,e,t).end;return{start:n,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[r]!==void 0)return{start:n,end:t+1+s[r]};if(r===217||r===196)return{start:n,end:t+2+e.getUint8(t+1)};if(r===218||r===197)return{start:n,end:t+3+e.getUint16(t+1,!1)};if(r===219||r===198)return{start:n,end:t+5+e.getUint32(t+1,!1)};if(r===220||r===221){let o=r===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===220?3:5;for(let a=0;a<o;a++)t=ae(i,e,t).end;return{start:n,end:t}}if(r===222||r===223){let o=r===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===222?3:5;for(let a=0;a<o*2;a++)t=ae(i,e,t).end;return{start:n,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${r.toString(16)} at byte ${n}`)}var P=12,ft=1,Cn=0,xe=1,lr=2;function ce(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&ft)===ft,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function gt(i){let e=new Uint8Array(P),t=new DataView(e.buffer);return t.setUint32(0,i.groupId,!0),t.setUint32(4,i.frameSeq,!0),t.setUint8(8,i.keyframe?ft:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??Cn),e}var In=100,ur=100,le=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??In}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<P)return;let t=ce(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 r=this.pending.get(t.frameSeq);if(r||(r={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r)),!r.chunks[t.fragIndex]){r.chunks[t.fragIndex]=e.subarray(P),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let n of this.pending.keys())n<t.frameSeq-1&&(this.pending.delete(n),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-ur?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-ur}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 r=t.chunks.reduce((o,a)=>o+a.byteLength,0),n=new Uint8Array(r),s=0;for(let o of t.chunks)n.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:n})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Dn=/^avc[13]\.[0-9a-fA-F]{6}$/;function Pn(i){return Dn.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 vt(i,e){let t=Pn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var pr=1,We=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}if(this.name===null){if(this.buf.byteLength<2)return[];let r=this.buf[0];if(r!==pr)throw new Error(`[urun] wt data stream: unknown header version 0x${r.toString(16)} \u2014 rejecting stream`);let n=this.buf[1];if(n===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+n)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+n)),this.buf=this.buf.subarray(2+n)}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+r)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let n=rt(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),n===tt&&(this.ended=!0),t.push({name:this.name,payload:n})}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 wt(i,e){let t=i.getReader();for(;;){let{value:r,done:n}=await t.read();if(n)return;r&&Ln(r,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function Ln(i,e){let t=i.getReader(),r=new We;try{for(;;){let{value:n,done:s}=await t.read();if(s)break;if(!(!n||n.byteLength===0))for(let{name:o,payload:a}of r.push(n))e.onData(o,a)}r.finish()}catch(n){try{await t.cancel?.(n)}catch{}throw n}}var yt=40,hr=2,Y=48e3,Un=64,Mn=100,bt=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<P)return;let t=ce(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-Mn)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let r=this.pending.get(t.frameSeq);if(!r)for(r={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r);this.pending.size>Un;){let a=1/0;for(let d of this.pending.keys())d<a&&(a=d);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=r.fragCount||r.chunks[t.fragIndex]||(r.chunks[t.fragIndex]=e.subarray(P),r.received++,r.received<r.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let n=r.chunks.reduce((a,d)=>a+(d?.byteLength??0),0),s=new Uint8Array(n),o=0;for(let a of r.chunks)s.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:r.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}},Oe=class{constructor(e,t){this.config=e;this.seam=t;let r=this.seam.jitterBufferTargetMs??yt;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${yt}ms`),r=yt),this.targetS=Math.max(0,r)/1e3}config;seam;decoder=null;ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;contentBaseS=null;wallBaseS=0;reanchorLogged=!1;lastTsS=null;pendingTs=[];bridgeTrack=null;scheduledCount=0;lastScheduledAt=0;rebuildGen=0;rebuildTimes=[];rebuildBudgetLoggedAt=-1e4;lastRemote=null;assembler=new bt(e=>this.decodeFrame(e));start(){let e=globalThis.AudioDecoder,t=globalThis.AudioContext;if(typeof e!="function"||typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new t({sampleRate:this.config.sampleRate}),this.dest=this.ctx.createMediaStreamDestination();try{this.initDecoder(e)}catch(n){throw this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,n}this.trackSurfaced=!0,this.ctx.resume?.().catch(()=>{});let r=this.dest.stream.getAudioTracks()[0];if(!r)throw new Error("[urun] playout start produced no bridge track");this.surfaceTrack(r)}stop(){if(!this.stopped){this.stopped=!0;try{this.seam.renderHop?.setSource(null)}catch{}this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ctx?.close().catch(()=>{})}}initDecoder(e){let t=new e({output:r=>this.schedule(r,this.pendingTs.shift()),error:r=>this.onDecoderError(r)});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 n=globalThis.AudioDecoder;if(typeof n!="function")return;try{this.initDecoder(n)}catch{return}}let r=this.decoder;r&&(this.pendingTs.push(e.timestamp),r.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/Y)),data:e.data})))}schedule(e,t){let r=this.ctx,n=this.dest;if(!r||!n||this.stopped){e.close();return}let s=e.numberOfFrames,o=Math.max(1,e.numberOfChannels),a=r.createBuffer(o,s,e.sampleRate);for(let p=0;p<o;p++){let u=new Float32Array(s);e.copyTo(u,{planeIndex:p,format:"f32-planar"}),a.copyToChannel(u,p)}let d=s/e.sampleRate;e.close();let l=r.createBufferSource();l.buffer=a,l.connect(n);let c;if(t===void 0)c=Math.max(this.playhead,r.currentTime+this.targetS);else{this.contentBaseS===null&&(this.contentBaseS=t/Y,this.wallBaseS=r.currentTime+this.targetS),c=this.wallBaseS+t/Y-this.contentBaseS;let p=null;this.lastTsS!==null&&(t<this.lastTsS?(c=r.currentTime+this.targetS,p=`backward ts step ${(this.lastTsS-t/Y).toFixed(3)}s (producer clock reset)`):c>r.currentTime+this.targetS+Math.max(d,this.targetS)&&(p=`forward jump ${(c-r.currentTime).toFixed(3)}s out (lead + ${d.toFixed(3)}s tolerance exceeded \u2014 barge flush / producer re-anchor)`),p&&(this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored on a content-timeline discontinuity: ${p} \u2014 the gap is honest silence at rate 1.0, never a stretch`)),this.contentBaseS=t/Y,this.wallBaseS=r.currentTime+this.targetS,c=this.wallBaseS)),c<r.currentTime&&(this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored ${(r.currentTime-c).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=t/Y,this.wallBaseS=r.currentTime+this.targetS,c=this.wallBaseS)}l.start(c),this.scheduledCount++,this.lastScheduledAt=performance.now(),t!==void 0&&(this.lastTsS=t/Y),this.playhead=c+d}armBridgeEndedWatch(e){let t=this.rebuildGen;e.addEventListener?.("ended",()=>{if(!this.stopped&&!(t!==this.rebuildGen||this.bridgeTrack!==e)){console.warn("[urun] WT audio bridge track ENDED while the lane is live \u2014 rebuilding the WebAudio playout surface and re-delivering the bridge track");try{this.rebuildSurface()}catch(r){console.error(`[urun] WT audio bridge rebuild failed \u2014 the reply stays silent until the next lane death re-delivers: ${r instanceof Error?r.message:String(r)}`)}}},{once:!0})}playoutProgress(){return{scheduled:this.scheduledCount,lastScheduledAt:this.lastScheduledAt,surfaced:this.trackSurfaced&&this.bridgeTrack?.readyState!=="ended"}}rebuildSurface(){if(this.stopped)return;let e=performance.now();if(this.rebuildTimes=this.rebuildTimes.filter(s=>e-s<1e4),this.rebuildTimes.length>=hr){e-this.rebuildBudgetLoggedAt>1e4&&(this.rebuildBudgetLoggedAt=e,console.error(`[urun] WT audio bridge rebuild budget spent (${hr} 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.rebuildGen++;let t=globalThis.AudioContext;if(typeof t!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");let r=new t({sampleRate:this.config.sampleRate});this.ctx=r,r.resume?.().catch(()=>{}),this.dest=r.createMediaStreamDestination(),this.playhead=0,this.contentBaseS=null,this.lastTsS=null,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)}surfaceTrack(e){this.bridgeTrack=e,this.armBridgeEndedWatch(e),this.lastRemote&&this.lastRemote.readyState==="live"?this.seam.onTrack(this.lastRemote):this.seam.onTrack(e);let t=this.seam.renderHop;t&&(t.onRemote(r=>{if(this.stopped)return;if(r?this.lastRemote=r:this.lastRemote&&this.lastRemote.readyState!=="live"&&(this.lastRemote=null),r){this.seam.onTrack(r);return}if(this.lastRemote&&this.lastRemote.readyState==="live"){this.seam.onTrack(this.lastRemote);return}let n=this.bridgeTrack&&this.bridgeTrack.readyState==="live"?this.bridgeTrack:null;this.seam.onTrack(n)}),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(r){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${r instanceof Error?r.message:String(r)}`)}}};var ue=1200;function St(i,e,t,r,n){let s=r-P;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=gt({groupId:e>>>0,frameSeq:i>>>0,keyframe:n?.keyframe??!0,fragIndex:d,fragCount:o,lane:n?.lane??xe}),p=new Uint8Array(P+l.byteLength);p.set(c,0),p.set(l,P),a.push(p)}return a}var xn=`
1
+ import{$ as rn,B as Te,C as Yr,D as Qr,E as Xr,F as Jr,G as Zr,H as J,I as Ft,J as Re,K as Ze,L as $t,M as qt,N as Bt,O as et,P as jt,Q as Ht,R as Vt,S as en,T as Gt,U as Ae,V as tt,W as tn,X as rt,Z as Kt,a as Nt,aa as nn,b as ye,ba as sn,c as G,ca as on,d as Ke,da as Ee,e as be,f as Se,fa as Ce,g as ze,ga as zt,h as Ye,ha as Yt,i as Qe,ia as Qt,j as Nr,ja as Xt,k as Fr,l as ke,m as Xe,n as $r,o as qr,p as Br,q as jr,r as K,s as Hr,t as Vr,u as Gr,v as Kr,w as Je,x as zr,y as _e}from"./chunk-XYC7JMAJ.mjs";var an=15e3,dn=45e3,cn=12e4,nt="platform",it="activation",st="desired.activation";function Jt(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 ln=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],ne=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 r of this._watches.values())this._arm(r)}}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 r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}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=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let n=()=>this._firstMedia(e);r.addEventListener("unmute",n,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",n));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),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 ln){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_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,r){let n={state:t,elapsedMs:r,stream:e.name},s=Jt(this._options.hint());s!==void 0&&(n.hint=s),e.lastEvent=n;for(let o of Array.from(this._handlers))o(n)}};var D=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",n){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,n!==void 0&&(this.cause=n),Object.setPrototypeOf(this,new.target.prototype)}},Ie=class extends D{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},De=class extends D{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function ie(i){return{baseUrl:i.baseUrl,fallbackUrls:i.fallbackUrls,orgId:i.orgId,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}function un(i){return new z(i)}var z=class{_options;constructor(e){this._options=e}async list(e){let r=er(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new D("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(Zt)}async getDownloadUrl(e,t){let r=er(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!hn(n))throw new D("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Zt(r.artifact),downloadUrl:n}}async _request(e,t){let r=Ft(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let s of r)try{return await this._requestFromBase(s,e,t)}catch(o){if(n=o instanceof Error?o:new Error(String(o)),n instanceof D&&fn(n.status))throw n}throw n??new D("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${J(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,s=await this._resolveToken(),o=await fetch(n,{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(n,{method:"GET",headers:this._headers(s)}))}if(!o.ok){let{code:a,message:d}=await this._readError(o,e);throw mn(o.status,a,d)}try{return await o.json()}catch(a){throw new D(`[urun] runtime artifacts: invalid JSON response from ${J(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 r=J(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 ${r}: ${a}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}};function Zt(i){if(!i||typeof i!="object")throw new D("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=i,t=q(e,"artifact_id")||q(e,"id"),r=q(e,"filename"),n=q(e,"kind"),s=q(e,"status")||"ready",o=pn(e,"size_bytes"),a=q(e,"sha256");if(!t||!r||!n||o==null||!a)throw new D("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:q(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:s,createdAt:q(e,"created_at"),expiresAt:q(e,"expires_at")}}function q(i,e){let t=i[e];return typeof t=="string"&&t.length>0?t:void 0}function pn(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function hn(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function fn(i){return i===401||i===403}function mn(i,e,t){return i===401?new Ie(t,e):i===404?new De(t,e):new D(t,i,e)}function er(i){if(!i||typeof i!="object"||Array.isArray(i))throw new D("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var O=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)}},se=class extends O{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Pe=class extends O{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Le=class extends O{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)}},Ue=class extends O{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)}},Me=class extends O{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)}},Z=class extends O{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",r=400){super(e,{status:r,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function ot(i){return/^(\d+[smhdw])+$/.test(i)}function gn(i){if(i==="pin")return{action:"pin"};if(ot(i))return{action:"retain",duration:i};throw new Z(`[urun] recordings: "${i}" is not a duration or "pin"`)}function vn(i,e,t){let r=t||e||`HTTP ${i}`;if(i===401)return new se(r,e??"unauthorized");if(i===404)return new Pe(r,e??"not_found");if(i===400)return new Z(r,e??"bad_request",400);if(i===409)switch(e){case"retain_not_temp":return new Le(r,e);case"pin_requires_active_temp":return new Ue(r,e);case"permanent_locked":return new Me(r,e)}return new O(r,{status:i,code:e??`http_${i}`})}var ee=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let r=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(r)?r:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!ot(t))throw new Z(`[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 O("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),s=await this._resolveToken(),o=await this._fetch(n,e,s,r.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(n,e,s,r.body))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw vn(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let s={Authorization:`Bearer ${r}`,apikey:r,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 n!==void 0&&(s["Content-Type"]="application/json",o.body=JSON.stringify(n)),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 se("[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 r=(await e.json()).error;if(r&&typeof r=="object"){let{code:n,message:s}=r;return{code:typeof n=="string"?n:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function wn(i){return new ee(i)}var yn=1e3,bn=12e3;function at(i,e,t={}){let r=null,n=0,s=0,o=null,a=-1,d=()=>{let h=i.get("desired.billing.generationSeconds");if(typeof h!="number"||!Number.isFinite(h)||h<=0)return null;let y=i.get("desired.billing.epoch"),w=i.get("desired.billing.updatedAtMs");return{seconds:h,epoch:typeof y=="number"&&Number.isFinite(y)?y:0,updatedAtMs:typeof w=="number"&&Number.isFinite(w)?w:null}},l=()=>{if(r===null)return null;let h=Math.min(Math.max(0,Date.now()-n),s);return r+h/1e3},c=()=>{let h=t.creditsPerSecond;if(typeof h=="number"&&Number.isFinite(h)&&h>0)return h;let y=i.get("desired.billing.creditsPerSecond");return typeof y=="number"&&Number.isFinite(y)&&y>0?y:null},p=()=>{let h=l();if(h===null)return;let y=Math.floor(h);if(y<=a)return;a=y;let w={seconds:y},T=c();T!==null&&(w.estimatedCredits=y*T),e(w)},u=h=>{n=Date.now();let y=h===null?0:Math.max(0,n-h);s=Math.max(0,12e3-y)},f=()=>{let h=d();if(h!==null){if(o!==null&&h.epoch!==o){o=h.epoch,r=h.seconds,a=-1,u(h.updatedAtMs),p();return}r!==null&&h.seconds<=r||(o=h.epoch,r=h.seconds,u(h.updatedAtMs),p())}};f();let m=i.on("change",f),S=setInterval(p,1e3);return S.unref?.(),()=>{clearInterval(S),m()}}var tr="activity",rr="visibility",Sn=15e3,dt=["pointerdown","pointermove","keydown","wheel","touchstart"];function ct(i){let e=i.now??Date.now,t=i.mode==="explicit",r=t?null:i.windowTarget!==void 0?i.windowTarget:typeof window<"u"?window:null,n=t?null:i.documentTarget!==void 0?i.documentTarget:typeof document<"u"?document:null,s=!1,o,a=()=>{if(s)return;let u=e();if(!(o!==void 0&&u-o<15e3)){o=u;try{i.awareness.setLocalStateField(tr,{at:u})}catch{}}},d=()=>{if(!(s||!n||n.visibilityState===void 0))try{i.awareness.setLocalStateField(rr,n.visibilityState)}catch{}},l=()=>a(),c=()=>{d(),(!n||n.visibilityState===void 0||n.visibilityState==="visible")&&a()};if(r)for(let u of dt)r.addEventListener(u,l,{passive:!0,capture:!0});n&&n.addEventListener("visibilitychange",c);let p=null;return!t&&i.isProducing&&(p=setInterval(()=>{if(!s)try{i.isProducing?.()&&a()}catch{}},15e3),p.unref?.()),a(),d(),{touch:a,dispose(){if(!s){if(s=!0,r)for(let u of dt)r.removeEventListener(u,l,{capture:!0});n&&n.removeEventListener("visibilitychange",c),p&&(clearInterval(p),p=null)}}}}var ir="user_activity",sr="focus",kn=3e4;function nr(i){switch(i){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var oe=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(nr(e.state));let t=e.on("stateChange",n=>{this._setState(nr(n))}),r=()=>{t(),this._transportUnsubs.delete(r)};return this._transportUnsubs.add(r),r}_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(sr,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(ir,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 _n=250;function lt(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 r=Date.now();r-e<250||(e=r,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 ut(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,i())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function pt(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 or="video/mp4";function ht(i,e={}){let t=e.timesliceMs??1e3,r=null,n=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 p=e.mimeType??(typeof c.isTypeSupported=="function"&&c.isTypeSupported(or)?or:void 0),u=new MediaStream([a]),f=new c(u,p?{mimeType:p}:void 0);r=f;let m=Promise.resolve();f.ondataavailable=S=>{let h=S.data;s||!h||h.size===0||(m=m.then(async()=>{let y=new Uint8Array(await h.arrayBuffer());s||d(y)}))},f.onstop=()=>{m.then(()=>{s||l()})},f.onerror=()=>{m.then(()=>{s||l()})},f.start(t)};return{start(a,d){if(r||s)return;let l=i.track();if(l){o(l,a,d);return}n=i.onTrack(c=>{!c||r||s||(n?.(),n=null,o(c,a,d))})},stop(){if(s)return;s=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Tn(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 ar(i,e){let t=null,r=!1,n=!1,s=new ReadableStream({pull(o){r||(r=!0,t=i(e),t.start(a=>{if(!n)try{o.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{o.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Tn(s)}import{encode as Rn,decode as An}from"@msgpack/msgpack";var dr=65536;function mt(i){let e=Rn(i),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var de=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>dr)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let n=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(Object.assign(An(n),{raw:n}))}return t}};function cr(i,e){let t=new DataView(i.buffer,i.byteOffset,i.byteLength),r=t.getUint8(0),n=(r&240)===128,s=r===222;if(!n&&!s&&!(r===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let a=n?r&15:s?t.getUint16(1,!1):t.getUint32(1,!1),d=n?1:s?3:5,l=[];l.push(i.subarray(0,d));for(let f=0;f<a;f++){let m=d,S=ae(i,t,d);d=S.end;let y=ae(i,t,d).end;if(En(t.getUint8(m))){let w=t.getUint8(m),T=(w&224)===160?1:w===217?2:w===218?3:5;if(new TextDecoder().decode(i.subarray(m+T,S.end))==="t"){l.push(i.subarray(m,S.end));let R=new TextEncoder().encode(e);if(R.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");l.push(new Uint8Array([160|R.byteLength]),R)}else l.push(i.subarray(m,y))}else l.push(i.subarray(m,y));d=y}let c=l.reduce((f,m)=>f+m.byteLength,0),p=new Uint8Array(c),u=0;for(let f of l)p.set(f,u),u+=f.byteLength;return p}function En(i){return(i&224)===160?!0:i===217||i===218||i===219}function ae(i,e,t){let r=e.getUint8(t),n=t;if(r<=127||r>=224)return{start:n,end:t+1};if((r&224)===160)return{start:n,end:t+1+(r&31)};if((r&240)===128||(r&240)===144){let o=r&15;t+=1;let a=(r&240)===128?o*2:o;for(let d=0;d<a;d++)t=ae(i,e,t).end;return{start:n,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[r]!==void 0)return{start:n,end:t+1+s[r]};if(r===217||r===196)return{start:n,end:t+2+e.getUint8(t+1)};if(r===218||r===197)return{start:n,end:t+3+e.getUint16(t+1,!1)};if(r===219||r===198)return{start:n,end:t+5+e.getUint32(t+1,!1)};if(r===220||r===221){let o=r===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===220?3:5;for(let a=0;a<o;a++)t=ae(i,e,t).end;return{start:n,end:t}}if(r===222||r===223){let o=r===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===222?3:5;for(let a=0;a<o*2;a++)t=ae(i,e,t).end;return{start:n,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${r.toString(16)} at byte ${n}`)}var P=12,ft=1,Cn=0,xe=1,lr=2;function ce(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&ft)===ft,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function gt(i){let e=new Uint8Array(P),t=new DataView(e.buffer);return t.setUint32(0,i.groupId,!0),t.setUint32(4,i.frameSeq,!0),t.setUint8(8,i.keyframe?ft:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??Cn),e}var In=100,ur=100,le=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??In}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<P)return;let t=ce(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 r=this.pending.get(t.frameSeq);if(r||(r={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r)),!r.chunks[t.fragIndex]){r.chunks[t.fragIndex]=e.subarray(P),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let n of this.pending.keys())n<t.frameSeq-1&&(this.pending.delete(n),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-ur?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-ur}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 r=t.chunks.reduce((o,a)=>o+a.byteLength,0),n=new Uint8Array(r),s=0;for(let o of t.chunks)n.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:n})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Dn=/^avc[13]\.[0-9a-fA-F]{6}$/;function Pn(i){return Dn.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 vt(i,e){let t=Pn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var pr=1,We=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}if(this.name===null){if(this.buf.byteLength<2)return[];let r=this.buf[0];if(r!==pr)throw new Error(`[urun] wt data stream: unknown header version 0x${r.toString(16)} \u2014 rejecting stream`);let n=this.buf[1];if(n===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+n)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+n)),this.buf=this.buf.subarray(2+n)}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+r)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let n=rt(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),n===tt&&(this.ended=!0),t.push({name:this.name,payload:n})}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 wt(i,e){let t=i.getReader();for(;;){let{value:r,done:n}=await t.read();if(n)return;r&&Ln(r,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function Ln(i,e){let t=i.getReader(),r=new We;try{for(;;){let{value:n,done:s}=await t.read();if(s)break;if(!(!n||n.byteLength===0))for(let{name:o,payload:a}of r.push(n))e.onData(o,a)}r.finish()}catch(n){try{await t.cancel?.(n)}catch{}throw n}}var yt=40,hr=2,Y=48e3,Un=64,Mn=100,bt=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<P)return;let t=ce(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-Mn)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let r=this.pending.get(t.frameSeq);if(!r)for(r={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r);this.pending.size>Un;){let a=1/0;for(let d of this.pending.keys())d<a&&(a=d);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=r.fragCount||r.chunks[t.fragIndex]||(r.chunks[t.fragIndex]=e.subarray(P),r.received++,r.received<r.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let n=r.chunks.reduce((a,d)=>a+(d?.byteLength??0),0),s=new Uint8Array(n),o=0;for(let a of r.chunks)s.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:r.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}},Oe=class{constructor(e,t){this.config=e;this.seam=t;let r=this.seam.jitterBufferTargetMs??yt;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${yt}ms`),r=yt),this.targetS=Math.max(0,r)/1e3}config;seam;decoder=null;ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;contentBaseS=null;wallBaseS=0;reanchorLogged=!1;lastTsS=null;pendingTs=[];bridgeTrack=null;scheduledCount=0;lastScheduledAt=0;rebuildGen=0;rebuildTimes=[];rebuildBudgetLoggedAt=-1e4;lastRemote=null;assembler=new bt(e=>this.decodeFrame(e));start(){let e=globalThis.AudioDecoder,t=globalThis.AudioContext;if(typeof e!="function"||typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new t({sampleRate:this.config.sampleRate}),this.dest=this.ctx.createMediaStreamDestination();try{this.initDecoder(e)}catch(n){throw this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,n}this.trackSurfaced=!0,this.ctx.resume?.().catch(()=>{});let r=this.dest.stream.getAudioTracks()[0];if(!r)throw new Error("[urun] playout start produced no bridge track");this.surfaceTrack(r)}stop(){if(!this.stopped){this.stopped=!0;try{this.seam.renderHop?.setSource(null)}catch{}this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ctx?.close().catch(()=>{})}}initDecoder(e){let t=new e({output:r=>this.schedule(r,this.pendingTs.shift()),error:r=>this.onDecoderError(r)});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 n=globalThis.AudioDecoder;if(typeof n!="function")return;try{this.initDecoder(n)}catch{return}}let r=this.decoder;r&&(this.pendingTs.push(e.timestamp),r.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/Y)),data:e.data})))}schedule(e,t){let r=this.ctx,n=this.dest;if(!r||!n||this.stopped){e.close();return}let s=e.numberOfFrames,o=Math.max(1,e.numberOfChannels),a=r.createBuffer(o,s,e.sampleRate);for(let p=0;p<o;p++){let u=new Float32Array(s);e.copyTo(u,{planeIndex:p,format:"f32-planar"}),a.copyToChannel(u,p)}let d=s/e.sampleRate;e.close();let l=r.createBufferSource();l.buffer=a,l.connect(n);let c;if(t===void 0)c=Math.max(this.playhead,r.currentTime+this.targetS);else{this.contentBaseS===null&&(this.contentBaseS=t/Y,this.wallBaseS=r.currentTime+this.targetS),c=this.wallBaseS+t/Y-this.contentBaseS;let p=null;this.lastTsS!==null&&(t<this.lastTsS?(c=r.currentTime+this.targetS,p=`backward ts step ${(this.lastTsS-t/Y).toFixed(3)}s (producer clock reset)`):c>r.currentTime+this.targetS+Math.max(d,this.targetS)&&(p=`forward jump ${(c-r.currentTime).toFixed(3)}s out (lead + ${d.toFixed(3)}s tolerance exceeded \u2014 barge flush / producer re-anchor)`),p&&(this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored on a content-timeline discontinuity: ${p} \u2014 the gap is honest silence at rate 1.0, never a stretch`)),this.contentBaseS=t/Y,this.wallBaseS=r.currentTime+this.targetS,c=this.wallBaseS)),c<r.currentTime&&(this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored ${(r.currentTime-c).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=t/Y,this.wallBaseS=r.currentTime+this.targetS,c=this.wallBaseS)}l.start(c),this.scheduledCount++,this.lastScheduledAt=performance.now(),t!==void 0&&(this.lastTsS=t/Y),this.playhead=c+d}armBridgeEndedWatch(e){let t=this.rebuildGen;e.addEventListener?.("ended",()=>{if(!this.stopped&&!(t!==this.rebuildGen||this.bridgeTrack!==e)){console.warn("[urun] WT audio bridge track ENDED while the lane is live \u2014 rebuilding the WebAudio playout surface and re-delivering the bridge track");try{this.rebuildSurface()}catch(r){console.error(`[urun] WT audio bridge rebuild failed \u2014 the reply stays silent until the next lane death re-delivers: ${r instanceof Error?r.message:String(r)}`)}}},{once:!0})}playoutProgress(){return{scheduled:this.scheduledCount,lastScheduledAt:this.lastScheduledAt,surfaced:this.trackSurfaced&&this.bridgeTrack?.readyState!=="ended"}}rebuildSurface(){if(this.stopped)return;let e=performance.now();if(this.rebuildTimes=this.rebuildTimes.filter(s=>e-s<1e4),this.rebuildTimes.length>=hr){e-this.rebuildBudgetLoggedAt>1e4&&(this.rebuildBudgetLoggedAt=e,console.error(`[urun] WT audio bridge rebuild budget spent (${hr} 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.rebuildGen++;let t=globalThis.AudioContext;if(typeof t!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");let r=new t({sampleRate:this.config.sampleRate});this.ctx=r,r.resume?.().catch(()=>{}),this.dest=r.createMediaStreamDestination(),this.playhead=0,this.contentBaseS=null,this.lastTsS=null,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)}surfaceTrack(e){this.bridgeTrack=e,this.armBridgeEndedWatch(e),this.lastRemote&&this.lastRemote.readyState==="live"?this.seam.onTrack(this.lastRemote):this.seam.onTrack(e);let t=this.seam.renderHop;t&&(t.onRemote(r=>{if(this.stopped)return;if(r?this.lastRemote=r:this.lastRemote&&this.lastRemote.readyState!=="live"&&(this.lastRemote=null),r){this.seam.onTrack(r);return}if(this.lastRemote&&this.lastRemote.readyState==="live"){this.seam.onTrack(this.lastRemote);return}let n=this.bridgeTrack&&this.bridgeTrack.readyState==="live"?this.bridgeTrack:null;this.seam.onTrack(n)}),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(r){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${r instanceof Error?r.message:String(r)}`)}}};var ue=1200;function St(i,e,t,r,n){let s=r-P;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=gt({groupId:e>>>0,frameSeq:i>>>0,keyframe:n?.keyframe??!0,fragIndex:d,fragCount:o,lane:n?.lane??xe}),p=new Uint8Array(P+l.byteLength);p.set(c,0),p.set(l,P),a.push(p)}return a}var xn=`
2
2
  self.onrtctransform = (event) => {
3
3
  const transformer = event.transformer
4
4
  if (transformer.options?.role === 'sender') {
@@ -26,4 +26,4 @@ self.onrtctransform = (event) => {
26
26
  }
27
27
  `;function fr(i){let e=i.match(/a=rtpmap:(\d+) opus\/48000\/2/)?.[1];if(!e)return i;let t="usedtx=1;useinbandfec=1;maxaveragebitrate=32000",r=!1,n=i.split(`\r
28
28
  `).map(s=>s.startsWith(`a=fmtp:${e} `)&&!s.includes("usedtx=")?(r=!0,`${s};${t}`):s);if(!r){let s=n.findIndex(o=>o===`a=rtpmap:${e} opus/48000/2`);s>=0&&n.splice(s+1,0,`a=fmtp:${e} ${t}`)}return n.join(`\r
29
- `)}var Ne=class{constructor(e){this.sink=e}sink;frameSeq=0;stopped=!1;deadCb=null;sendPc=null;recvPc=null;sender=null;currentTrack=null;renderSender=null;renderRemoteCb=null;renderEndedListener=null;worker=null;workerUrl=null;nodeBridge=null;endedListener=null;candQueue=null;negotiatedOnce=!1;negotiating=!1;renegotiateQueued=!1;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.currentTrack&&e.readyState==="live")return;let t=null;if(!(e!==null&&(t=Wn(e)?this.bridgedTrack(e):e,!t))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(t)}catch(r){this.die(`replaceTrack: ${r instanceof Error?r.message:String(r)}`);return}this.currentTrack=t,t&&this.wireTrackLiveness(t);return}t!==null&&this.engage(t)}}stop(){if(!this.stopped){this.stopped=!0,this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(e){let t=globalThis;if(typeof t.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof t.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let r;try{r=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let n=this.sendPc.addTrack(e);this.sender=n,this.currentTrack=e,this.wireTrackLiveness(e);let s=t.RTCRtpScriptTransform;n.transform=new s(r,{role:"sender"}),!this.negotiatedOnce&&this.negotiate().catch(o=>this.die(`loopback negotiate: ${o instanceof Error?o.message:String(o)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let t=e.RTCPeerConnection;this.sendPc=new t({iceServers:[]}),this.recvPc=new t({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=r=>{if(!r.candidate)return;let n=this.candQueue;n!==null&&(n.toRecv.push(r.candidate),this.flushCandidates())},this.recvPc.onicecandidate=r=>{if(!r.candidate)return;let n=this.candQueue;n!==null&&(n.toSend.push(r.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(r=>this.die(`loopback renegotiate: ${r instanceof Error?r.message:String(r)}`))},this.recvPc.ontrack=r=>{let n=r.transceiver?.mid??null;n!==null&&n===this.renderMidOf()&&this.renderRemoteCb?.(r.track)}}setRenderSource(e){if(!this.stopped){if(e===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(e);else try{this.renderSender.replaceTrack(e)}catch(t){this.die(`render replaceTrack: ${t instanceof Error?t.message:String(t)}`);return}this.wireRenderRemote(e),this.negotiatedOnce||this.negotiate().catch(t=>this.die(`loopback negotiate: ${t instanceof Error?t.message:String(t)}`))}}}onRenderTrack(e){this.renderRemoteCb=e}renderMidOf(){if(!this.renderSender)return null;let e=this.sendPc;try{return e.getTransceivers?.().find(t=>t.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(e){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},e.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let e=this.sendPc,t=this.recvPc;if(!(!e||!t||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let r=await e.createOffer();r.sdp=fr(r.sdp??""),await e.setLocalDescription(r),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:r.sdp});let n=await t.createAnswer();n.sdp=fr(n.sdp??""),await t.setLocalDescription(n),await e.setRemoteDescription(t.localDescription??{type:"answer",sdp:n.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let e=this.candQueue;if(e){for(;e.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(e.toSend.shift())).catch(()=>{});for(;e.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(e.toRecv.shift())).catch(()=>{})}}bridgedTrack(e){let t=e;try{let r=t.context.createMediaStreamDestination();t.connect(r);let n=r.stream.getAudioTracks()[0]??null;return n?(this.nodeBridge={node:t,dest:r},n):(this.die("AudioNode bridge produced no audio track"),null)}catch(r){return this.die(`AudioNode bridge: ${r instanceof Error?r.message:String(r)}`),null}}wireTrackLiveness(e){this.endedListener=()=>this.die("mic track ended"),e.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([xn],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=t=>{let r=t.data;r?.type==="enc"&&r.payload instanceof ArrayBuffer?this.onEncodedFrame(r.rtpTimestamp??0,new Uint8Array(r.payload)):r?.type==="err"&&this.die(`transform: ${r.detail??"unknown"}`)},e.onerror=t=>this.die(`transform worker: ${t.message||"error"}`),this.worker=e,e}onEncodedFrame(e,t){if(this.stopped)return;let r=St(this.frameSeq,e,t,this.sink.maxDatagramSize()||ue);if(r===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let n of r)this.sink.send(n);this.frameSeq=this.frameSeq+1>>>0}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function Wn(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var On=9e4,Nn="avc1.42E01F",Fn=60,$n=3,qn=1e4;function Bn(i){return Math.round(i*(On/1e6))%2**32>>>0}var Fe=class{constructor(e){this.sink=e}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}requestKeyframe(){this.keyframeWanted=!0}setSource(e){if(this.stopped||(this.teardownCapture(),e===null))return;let r=globalThis.MediaStreamTrackProcessor;if(typeof r!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let n=++this.generation,s=new r({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,s.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&n===this.generation;){let{value:a,done:d}=await s.read();if(d)break;if(a){if(o||this.stopped||n!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&n===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:Nn,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 n=this.keyframeWanted||this.framesSinceKeyframe>=Fn;this.keyframeWanted=!1,this.framesSinceKeyframe=n?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:n})}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 r=St(this.frameSeq,Bn(e.timestamp),t,this.sink.maxDatagramSize()||ue,{lane:lr,keyframe:e.type==="key"});if(r===null){console.warn(`[urun] WT video uplink: AU of ${t.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let n of r)this.sink.send(n);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(r=>t-r<qn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=$n){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 jn(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 r=new TextEncoder().encode(e);if(r.byteLength===0||r.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${r.byteLength})`));let n=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+r.byteLength);d[0]=1,d[1]=r.byteLength,d.set(r,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),jn(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=n.catch(()=>{}),n}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 mr=250,Hn=25,Vn=2e3,Gn=15e3,Kn=1e3,zn=45e3,Yn=500,gr=10,Qn=2,Xn=2,kt=2,pe=class i{constructor(e,t,r,n,s,o,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=n;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;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new le({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=this.offer.codec,r=t!==void 0&&t!=="";this.hasVideoLane=r,r&&vt(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(c=>({algorithm:"sha-256",value:Uint8Array.from(atob(c),p=>p.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let n=await this.wt.createBidirectionalStream();this.writer=n.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let s=n.readable.getReader(),o=new de,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")),r&&(vt(l.codec,"hello-ack"),this.initDecoder(l.codec,l.width,l.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let c={setSource:u=>{this.renderSource=u,this.audioUplinkLane?.setRenderSource?.(u)},onRemote:u=>{this.renderRemoteCb=u}},p=new Oe(this.offer.audio,{...this.audioLane,renderHop:c});try{p.start(),this.audioPlayout=p}catch(u){console.warn(`[urun] WT audio lane failed to start (${u instanceof Error?u.message:String(u)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),p.stop()}}if(this.offer.audioUp===!0&&this.audioUplink&&this.engageUplinkLane("audio"),this.offer.videoUp===!0&&this.videoUplink&&this.engageUplinkLane("video"),this.offer.dataUp===!0&&this.dataUplink)try{let c=this.wt.createUnidirectionalStream?.bind(this.wt);if(!c)throw new Error("WebTransport uni streams are not creatable in this environment");let p=new $e({openUniStream:async()=>(await c()).getWriter()});p.onDead(u=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(u)}),this.dataUplinkSender=p,this.dataUplink.onUplink(p)}catch(c){let p=c instanceof Error?c.message:String(c);console.warn(`[urun] WT data uplink failed to engage (${p}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(p)}this.controlLoop(s,o,a).catch(c=>this.die(`control loop: ${c}`)),this.datagramLoop().catch(c=>this.die(`datagram loop: ${c}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),Yn)),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 ${mr}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Gn},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Kn))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let t=typeof e.ds=="number"?e.ds:null,r=typeof e.ur=="number"?e.ur:null;if(t===null&&r===null)return;this.gatewayExposesCounters=!0;let n=this.audioDgramsReceived,s=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:r,recvDownlink:n,sentUplink:s},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,d=r!==null&&o.ur!==null?r-o.ur:null,l=n-o.recvDownlink,c=s-o.sentUplink,p="none";if(a!==null&&a>=gr&&l<=0?p="downlink":d!==null&&c>=gr&&d<=0&&(p="uplink"),p==="none"){this.severedStreak="none",this.observePlayoutProgress(l,t);return}if(this.severedStreak!==p){this.severedStreak=p;return}this.severedStreak="none";let u=p==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${c} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+u+` (gateway flow counters ds=${t} ur=${r}, client received=${n} accepted=${s}, confirmed on ${Qn} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,t){let r=this.audioPlayout;if(!r){this.playoutScheduledSeen=null;return}let n=r.playoutProgress(),s=n.surfaced;if(this.playoutScheduledSeen!==null&&n.scheduled>this.playoutScheduledSeen&&s){this.playoutScheduledSeen=n.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=n.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<Xn)){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=${n.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{r.rebuildSurface()}catch(o){console.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=kt}return}this.playoutStallStreak<kt||(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=${n.scheduled} on ${kt} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let t=this.pathLiveness();if(!t.alive)return;let r=performance.now(),n=this.audioLaneLastArrivalAt===null?null:r-this.audioLaneLastArrivalAt,s=this.lastInboundControlAt===null?null:r-this.lastInboundControlAt,o=n===null&&s===null?!0:(n===null||n>=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}o&&s!==null&&s>=zn&&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))}dropDatagramUplinks(e){this.clearUplinkRetryTimers(),(this.audioUplinkLane!==null||this.audioUplinkRetry!==null)&&(this.audioUplinkLane?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e)),(this.videoUplinkLane!==null||this.videoUplinkRetry!==null)&&(this.videoUplinkLane?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e))}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)");this.dataLaneSink=e,wt(this.wt.incomingUnidirectionalStreams,e).catch(t=>{this.die(`data lane: ${t instanceof Error?t.message:String(t)}`)})}initDecoder(e,t,r){let n=globalThis.VideoDecoder;if(typeof n!="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:r};let o=new n({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&&r>0?{codedWidth:t,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"}),this.decoder=o}onDecoderError(e){if(this.stopped||this.deadFired)return;console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=this.decoderConfig;if(!t){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder error with no retained config to re-init from \u2014 video stays down: ${e.message}`));return}try{this.initDecoder(t.codec,t.width,t.height),this.decoderErrorLogged=!1}catch(r){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${r instanceof Error?r.message:String(r)}`));return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}uplinkSend(e,t){if(this.stopped||this.deadFired)return;this.datagramWriter().write(e).then(t,n=>this.onUplinkSendError(n))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let t=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,console.error(`[urun] WT uplink datagram send FAILED (${t}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let r=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(n=>r-n<Vn),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<Hn)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSink(e){this.datagramWriter();let t=0;return{send:r=>this.uplinkSend(r,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??ue}}engageAudioUplink(){let e=new Ne(this.uplinkSink("audio"));e.onDead(t=>this.onUplinkLaneDead("audio",t)),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 Fe(this.uplinkSink("video"));e.onDead(t=>this.onUplinkLaneDead("video",t)),this.videoUplinkLane=e,this.videoUplinkRetry=this.freshLaneBuilt(this.videoUplinkRetry),this.videoUplink.onUplink(e)}engageUplinkLane(e){let t=e==="audio"?"mic":"video";try{e==="audio"?this.engageAudioUplink():this.engageVideoUplink()}catch(r){let n=r instanceof Error?r.message:String(r);console.warn(`[urun] WT ${t} uplink failed to engage (${n}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,n)}}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){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let r=e==="audio"?"mic":"video",n=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,o=n?.builtAt!=null&&Date.now()-n.builtAt>=i.UPLINK_LANE_HEALTHY_MS?1:(n?.count??0)+1;if(o>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}`);return}console.warn(`[urun] WT ${r} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${o}/${i.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let a={count:o,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=a:this.videoUplinkRetry=a,a.timer=setTimeout(()=>{a.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},i.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,t){e==="audio"?this.audioUplink.onUplinkLost(t):this.videoUplink.onUplinkLost(t)}clearUplinkRetryTimers(){for(let e of[this.audioUplinkRetry,this.videoUplinkRetry])e&&(clearTimeout(e.timer),e.timer=void 0)}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:r}=await e.read();if(r)break;if(!t)continue;if(t.byteLength>=P&&t[11]===xe){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let n=performance.now();if(this.lastArrivalTs>0){let s=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(s-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=n,this.reassembler.push(t)}}decodeFrame(e,t,r){let n=globalThis.EncodedVideoChunk;if(typeof n=="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 n({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(mt(e)),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async sendControlRaw(e){try{let t=new Uint8Array(4+e.byteLength);new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),await this.writer.write(t),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async readControl(e,t,r=[]){for(;;){let n=r.shift();if(n)return n;let{value:s,done:o}=await e.read();if(o)return null;s&&r.push(...t.push(s))}}async controlLoop(e,t,r){for(;!this.stopped;){let n=await this.readControl(e,t,r);if(!n)break;let s=n;if(this.lastInboundControlAt=performance.now(),s.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(cr(n.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(),r=(t-e)/1e3;e=t;let n=this.reassembler.drainWindow(),s=n.delivered+n.abandoned;this.lastStats={recvBps:r>0?n.bytes*8/r:0,lossPct:s>0?100*n.abandoned/s:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},mr)}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 vr=2500,wr=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Jn=1e4,he=class i{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;static WT_REDIAL_BASE_MS=2e3;static WT_REDIAL_MAX=3;static WT_REDIAL_CAP_MS=3e4;wtRedialFailures=0;wtRedialTimer=null;disconnected=!1;downlinkStallWatch=null;watchDownlinkStall(e={}){this.downlinkStallWatch={stallMs:e.stallMs??15e3},this.applyStallWatch()}applyStallWatch(){let e=this.session;!e||e.kind!=="webtransport"||!this.downlinkStallWatch||e.watchDownlinkStall?.(this.downlinkStallWatch)}failCurrentWtLeg(e){if(this.disconnected)return;let t=this.session;!t||t.kind!=="webtransport"||t.fail?.(e)}get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis;this.disconnected=!1;let t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,s={webtransport:t&&r&&n,webcodecs:r,codecs:wr,wtData:t&&r&&n&&this.opts.dataLane!==void 0,wtAudio:t&&r&&n&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&n&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:t&&r&&n&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&r&&n&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:s});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 _t(l.start(),this.opts.quicDeadlineMs??vr,"quic connect deadline"),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(l?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let p=String(c instanceof Error?c.message:c);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${p}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(p),c}console.warn("[urun] webtransport failed, falling back to webrtc:",c),this.proceedWebRtcDial(`wt failed: ${String(c instanceof Error?c.message:c)}`),this.notifyEstablished("webrtc",String(c instanceof Error?c.message:c))}}if(this.opts.allowWebRtcFallback===!1){let l=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${l} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(l),new Error(`[urun] WT required but unavailable: ${l}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.disconnected=!0,this.wtRedialTimer!==null&&(clearTimeout(this.wtRedialTimer),this.wtRedialTimer=null),this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,await e?.stop()}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let r=this.session,n=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:wr,wtData:n,wtAudio:s,wtAudioUp:o,wtVideoUp:a,wtDataUp:d}}),!this.offer.webtransport)return null;let l=this.createWebTransportSession();try{await _t(l.start(),this.opts.quicDeadlineMs??vr,"quic connect deadline")}catch(c){throw l.stop().catch(()=>{}),c}if(this.session!==r)return l.stop().catch(()=>{}),null;try{this.engageQuicDataLane(l,n)}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"),r?.stop().catch(()=>{}),l}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let r=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(n,s)=>r.onData(n,s),onLaneError:n=>r.onLaneError(n)}),r.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new pe(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;this.wtRedialFailures=0,this.applyStallWatch(),e.onDead(t=>{if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; re-dialing WT (attempt 1 immediate, then the bounded ladder)`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.redialWtAfterDeath(t);return}let r=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),r){this.session=null,this.wtOnlyLeg=!1,console.warn("[urun] quic died mid-session on a WT-only leg \u2014 RE-DIALING WebTransport first (same session id; the late WebRTC dial is the fallback):",t),this.redialWtAfterDeath(t);return}console.warn("[urun] quic died mid-session, failing over to webrtc:",t),this.lateWebRtcFailover(e,t,r)})}redialWtAfterDeath(e){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures+=1,this.wtRedialFailures===i.WT_REDIAL_MAX+1){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 t=this.wtRedialFailures,r=Rt(i.WT_REDIAL_BASE_MS,t,i.WT_REDIAL_CAP_MS,t===1?0:void 0);console.warn(`[urun] WT re-dial attempt ${t} 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}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 r=Tt(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${i.WT_REDIAL_MAX} failed (${r}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${r}`)}}}lateWebRtcFailover(e,t,r){this.disconnected||(async()=>{let n=this.createWebRtc();try{let s=await _t(this.startWebRtcOn(n),this.opts.webRtcFailoverDeadlineMs??Jn,"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(n.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=s instanceof Error?s.message:String(s),a=r?`media transport lost \u2014 the WebTransport connection dropped (${t}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${t}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;console.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function Tt(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 Rt(i,e,t,r){if(r!==void 0)return r;let n=Math.min(i*2**Math.max(0,e-2),t);return Math.round(n*(.75+Math.random()*.5))}function _t(i,e,t){return new Promise((r,n)=>{let s=setTimeout(()=>n(new Error(t)),e);i.then(o=>{clearTimeout(s),r(o)},o=>{clearTimeout(s),n(o)})})}var Zn=1e4,fe=class{constructor(e,t=Zn){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let r=Ae();return new Promise((n,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!==r)return;if(clearTimeout(o),a(),d.error){s(new Error(`[urun] ${e} failed: ${String(d.error)}`));return}let{type:l,requestId:c,...p}=d;n(p)});this.carrier.sendSignal({type:e,requestId:r,...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(r=>{r.type===e&&t(r)})}};var ei="video",me=class{constructor(e,t=ei){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,n)=>{this.firstMediaResolve=r,this.firstMediaReject=n}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};function yr(i){let e=i;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var ti="video";function br(i,e,t){let r=globalThis,n=r.document;if(!(typeof n?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=i.holdWebRtcDial?.(),a=n.createElement("canvas"),d=!1,l=null,c=!1,p=()=>{if(l){for(let b of l.getVideoTracks())try{b.stop()}catch{}l=null}c&&(c=!1,t.onOverrideTrack(null))},u=new he(new fe(i),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new me(i,t.streamName??ti)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(b,A)=>i.dispatchQuicStreamData(b,A),onQuicLane:()=>i.markStreamDataLaneQuic(),onQuicLaneLost:b=>i.quicStreamDataLaneLost(b),onLaneError:b=>i.raiseQuicStreamDataError(b)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:b=>{d||t.onOverrideAudioTrack(b)}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>C(),onMediaTransportLost:b=>{d||(p(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(b),C())},onTransportChange:(b,A)=>{d||(b==="webrtc"&&(p(),C()),t.onTransportChange?.(b,A))}}),f=i.onWtOnlyLegDeath?.(b=>u.failCurrentWtLeg(b)),m=null,S=()=>{m!==null&&(clearInterval(m),m=null)},h=t.wtRetryBaseMs??2e3,y=t.wtRetryCapMs??3e4,w=null,T=0,C=()=>{if(d||w!==null||u.activeTransport==="webtransport")return;let b=Rt(h,T+2,y);w=setTimeout(()=>{w=null,T+=1,u.retryWebTransport().then(A=>{if(d){A&&u.disconnect().catch(()=>{});return}if(A)return console.debug(`[urun] webtransport upgraded in background (retry ${T})`),T=0,W(A);C()}).catch(A=>{d||(console.debug(`[urun] webtransport background retry ${T} failed: `+Tt(A)),C())})},b)},R=()=>{w!==null&&(clearTimeout(w),w=null)},W=async b=>{if(d||b.kind!=="webtransport")return;let A=t.pathHealthProbeMs??1e4;S();let N=!1;m=setInterval(()=>{if(d||u.activeTransport!=="webtransport")return;let L=yr(b);if(!L){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 U=L.pathLiveness();if(!U.alive){let $=u.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${U.evidence}`+($?" \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(),L.fail(`path health: ${U.evidence}`);return}if(!N){if(N=!0,u.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${A}ms \u2014 the QUIC PATH IS HEALTHY (${U.evidence}), so this is an IDLE APPLICATION, not a dead path; keeping the leg (WT-only leg: no webrtc track exists) and continuing to watch the path`);return}console.warn(`[urun] webtransport established but no QUIC media after ${A}ms \u2014 no media datagrams reached this client (path healthy: ${U.evidence}); webrtc track remains authoritative`)}},A);try{await b.firstMedia}catch(L){S(),console.debug("[urun] webtransport ended before any media flowed:",L);return}if(S(),d||u.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;l=a.captureStream();let H=l.getVideoTracks()[0];H&&(c=!0,t.onOverrideTrack(H))};return(async()=>{let b=await u.connect();if(d){u.disconnect().catch(()=>{});return}await W(b)})().catch(b=>{if(S(),d){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",b);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",b),C();return}o?.proceed(`negotiation unavailable: ${b instanceof Error?b.message:String(b)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",b),C()}),{activeTransport:()=>u.activeTransport,watchDownlinkStall(b){u.watchDownlinkStall(b)},dispose(){d=!0,f?.(),S(),R(),p(),t.onOverrideAudioTrack?.(null),u.disconnect().catch(()=>{})}}}var ri=new Set;function Ct(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var ni="rpc",ii="$presence",_r=3e4,Sr=3e4,si="rpc-resp";function oi(i){return`${si}:${i}`}function At(){return Ae()}function ai(i){if(i&&typeof i=="object"){let e=i.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof i=="string"?i:JSON.stringify(i)}}function di(i,e,t,r,n,s,o,a,d,l){let c=[],p=null,u=!1,f=null,m=!1,S,h,y=new Promise((g,F)=>{S=g,h=F});y.catch(()=>{});let w=o(),T=null,C=null,R=null,W=null,b=null,A=null,N=!0,H=()=>{R&&(clearTimeout(R),R=null),W&&(W(),W=null)},L=()=>{b&&(clearTimeout(b),b=null),A&&(A(),A=null)},U=!1,$=()=>{U||!m||(U=!0,i.set({rpc:{[e]:null}}))},V=()=>{N=!1,H(),L(),T?.(),T=null,C?.(),C=null,a?.removeEventListener("abort",_),w.dispose(),$()},X=()=>{if(p){if(c.length>0){let g=p;p=null,g.resolve({value:c.shift(),done:!1})}else if(f!==null){let g=p;p=null,g.reject(f)}else if(u){let g=p;p=null,g.resolve({value:void 0,done:!0})}}},Ot=g=>{u||(c.push(g),X())},v=g=>{u||(f=g,u=!0,h(g),V(),X())},k=g=>{u||(u=!0,S(g),V(),X())},_=()=>{let g=a?.reason;v(g instanceof Se?g:new ke(e))},I=g=>{if(!(u||!g||typeof g!="object"))switch(L(),$(),g.t){case"delta":typeof g.delta=="string"&&Ot(g.delta);break;case"response":k(g.body);break;case"error":{let{message:F,code:E}=ai(g.body);v(new Se(F,{requestId:e,code:g.code??E}));break}}},M=()=>{let g=w.messages()[Symbol.asyncIterator]();T=()=>{g.return?.(void 0)};let F=()=>{N&&g.next().then(E=>{if(N){if(E.done){u||k(void 0);return}I(E.value),F()}},E=>{N&&v(E)})};F()},x=()=>{if(!m){if(m=!0,a){if(a.aborted){v(new ke(e));return}a.addEventListener("abort",_,{once:!0})}C=d?.(g=>v(g))??null,M(),i.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:s}}}),l&&l>0&&!i.synced&&(R=setTimeout(()=>{R=null,!u&&!i.synced&&v(new Ye(l,e))},l),W=i.onSynced(()=>H())),A=i.onSynced(()=>{A=null,!(u||U||b)&&(b=setTimeout(()=>{b=null,!(u||U)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(Sr/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).`)},Sr))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(x(),c.length>0)return Promise.resolve({value:c.shift(),done:!1});if(f!==null){let g=f;return f=null,Promise.reject(g)}return u?Promise.resolve({value:void 0,done:!0}):new Promise((g,F)=>{p={resolve:g,reject:F}})},return(){return u||(u=!0,S(void 0),V()),Promise.resolve({value:void 0,done:!0})},throw(g){return u||(u=!0,h(g),V()),Promise.reject(g)}}}},body:y,start:x}}function kr(i){if(i&&typeof i=="object"){let{epoch:e,by:t}=i,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function ci(i,e){let r=i.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:n,rt:s,br:o}=r,a={};(n==="audio"||n==="video"||n==="data")&&(a.kind=n);let d=kr(s);d&&(a.rt=d);let l=kr(o);return l&&(a.br=l),a}var Et=class{constructor(e,t,r,n,s){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=n;this._onActivity=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,n=!1,s=null,o={push(d){if(!n)if(r){let l=r;r=null,l.resolve({value:d,done:!1})}else t.push(d)},end(){if(n=!0,r){let d=r;r=null,d.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{n=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(d=>{if(!(d===null||n)&&(s=e._streamConsumeUnavailableError(d),a(),r)){let l=r;r=null,l.reject(s)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.reject(s):n?Promise.resolve({value:void 0,done:!0}):new Promise((d,l)=>{r={resolve:d,reject:l}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let n of r)n(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=ci(t,this._name),n=r?.br;if(n?.by==="runtime")throw new Qe(this._name,"runtime","browser");if(n)return;let s={br:{epoch:1}};r?.rt&&(s.rt=r.rt);let o=r?.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??ht;return ar(t,{track:()=>this.track,onTrack:n=>this.on("track",n)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},ge=class i{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Yt;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,r,n,s,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=n,this._artifactsAuth=s,this._streamData=Kt(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=lt(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=ct({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new oe({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(ii).awareness.setLocalState({role:"client"}),this._activation=new ne({onPhase:a=>this.onPhase(a),hint:()=>this.doc(nt).get(it)??this.doc("control").get(st),onData:(a,d)=>this._streamData.onData(a,d)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await Vt({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),n=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,s=new ye,o=new Ee({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new i(e,s,o,Ct(t),ie({...t,baseUrl:r.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&s.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),o.setEndsAt(r.endsAt),_e()&&await Te();let d=t.getAccessToken,l=d?async()=>await d()??n:n;return a.setDocTransport({wsUrl:r.wsUrl,token:l}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}get region(){return this._transport.region}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return Je(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=at(this.doc("control"),r=>{for(let n of Array.from(this._generationTickHandlers))try{n(r)}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 ee(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,n)=>t.retain(r,n),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new z(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new z(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new Et(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 Qt(e,this._sessionId,ri.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Xt(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=Ce(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",n=`${t}\0${r}\0${this._sessionId}`;n!==this._docEndpointKey&&(this._docEndpointKey=n,this.connectDocs(zt({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let r=At(),n=new AbortController;t.signal&&(t.signal.aborted?n.abort(t.signal.reason):t.signal.addEventListener("abort",()=>n.abort(t.signal.reason),{once:!0}));let s=null;if(typeof t.timeout=="number"&&t.timeout>=0){let d=t.timeout;s=setTimeout(()=>n.abort(new ze(d,r)),d)}let o=this._consumeResponse(r,e,!1,n.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{s&&clearTimeout(s),a?.()})}_consumeResponse(e,t,r,n,s){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(ni),a=oi(e);return di(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),s??_r)}requestStream(e,t={}){let r=At();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=At(),n=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return n.start(),n.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)}}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=br(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t),onOverrideAudioTrack:t=>this.stream("audio")._setOverrideTrack(t),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}),this._downlinkStallWatch&&this._dialNegotiation?.watchDownlinkStall(this._downlinkStallWatch))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}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 G)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new G);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 n of t)try{n()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let r=Array.from(this._activeRequests);this._activeRequests.clear();for(let n of r)try{n(new Xe)}catch{}for(let n of this._docs.values())n.dispose();this._docs.clear();for(let n of this._streams.values())n.dispose();this._streams.clear(),this._transport.disconnect(e)}};function Tr(i){return`urun:session:v2:${i.orgId}:${i.app}:${i.functionName}`}function It(){try{return globalThis.sessionStorage??null}catch{return null}}var Dt=new Map;function qe(i){if(!i)return;let e=i.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=JSON.parse(atob(t+"=".repeat((4-t.length%4)%4)));return typeof r?.sub=="string"&&r.sub.length>0?r.sub:void 0}catch{return}}function li(i,e){return i!==void 0&&e!==void 0&&i!==e}function Pt(i,e){let t=It(),r=null;if(t)try{let s=t.getItem(i);if(s){let o=JSON.parse(s);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(r={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{r=null}let n=Dt.get(i)??r??null;return!n||li(n.actor,e)?null:n}function Rr(i,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};Dt.set(i,t);let r=It();if(r)try{r.setItem(i,JSON.stringify(t))}catch{}}function Be(i){Dt.delete(i);let e=It();if(e)try{e.removeItem(i)}catch{}}var Ar=new Set(["paused","acquiring","live"]),ui=new Set(["24h","keep"]);function Er(i){if(typeof i!="string"||i.length===0)return null;let e=new Date(i);return Number.isFinite(e.getTime())?e:null}function pi(i){if(typeof i?.id!="string"||i.id.length===0)throw new be("[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"||!Ar.has(i.state))throw new be(`[urun] session ${i.id} reported an unrecognized state ${JSON.stringify(i.state)} \u2014 this @urun-sh/core build knows only ${[...Ar].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:Er(i.created_at),lastActiveAt:Er(i.last_active_at),archived:i.archived===!0,preview:typeof i.preview=="string"&&i.preview.length>0?i.preview:null,recordingsExpired:e,retention:ui.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 ve=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:r}=await Bt({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(pi),nextCursor:r}}async end(e){await jt({...this._request,sessionId:e})}async archive(e){await et({...this._request,sessionId:e,archived:!0})}async unarchive(e){await et({...this._request,sessionId:e,archived:!1})}async setName(e,t,r={}){await Ht({...this._request,sessionId:e,name:t,source:r.source})}};function Cr(i,e,t){let r=qe(t);Rr(i,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}var hi=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function fi(i,e){return new ve(i,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function mi(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,r){if(!(hi.has(r)||typeof r!="string"))return(n,s)=>{let o=n??{},a=Tr({orgId:e.orgId,app:i,functionName:r}),d=!s?.sessionId&&!e.sessionKey&&!!s?.label,l,c=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,p=c(),u=e.jwt,f=e.getAccessToken?async v=>{let k=await e.getAccessToken(v);return k&&(u=k),k}:void 0,m={...e,getAccessToken:f},S=new ye,h=new Ee({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:p,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),y=new ge(p,S,h,Ct(m),ie(m),{activity:s?.activity}),w,T=!1,C=!1,R,W,b=new Promise(v=>{W=v}),A,N=v=>{v.sessionId||R||(R="teardown",A="ticket",Re({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))},H=v=>{R||v.sessionId||(R="abandon",Re({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider,reason:"client_abandoned"}))},L=v=>{let k=v.sessionId||!l?v:{...v,sessionId:l};w=k,W({status:"ready",handle:k}),(C||R==="teardown")&&N(k)};y.setEndHandler(async()=>{let v=w?{status:"ready",handle:w}:await b;if(v.status==="unavailable")throw new G("[urun] session allocation failed before a releasable request was created",{cause:v.cause});let k=w??v.handle;return Be(a),R==="teardown"?k.sessionId?{status:"paused",sessionId:k.sessionId,reason:"client_ended"}:{status:"canceled",requestId:k.requestId}:(R="end",k.sessionId?$t({baseUrl:k.baseUrl,sessionId:k.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):Ze({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),y.setCancelHandler(async()=>{let v=w?{status:"ready",handle:w}:await b;if(v.status==="unavailable")throw new G("[urun] session allocation failed before a cancellable request was created",{cause:v.cause});let k=w??v.handle;if(k.sessionId)throw new Ke(`[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"});R="end";try{let _=await Ze({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return Be(a),_}catch(_){throw R==="end"&&(R=void 0),_}});let U=async v=>{let k,_=s?.sessionId??e.sessionKey??l,I,M;if(_===void 0&&!d){let E=Pt(a);if(E?.sessionId){if(M=qe(u),E.actor!==void 0&&M===void 0&&f){let Ge=await Promise.resolve(f()).catch(()=>{});M=qe(Ge??e.jwt)}I=E.actor!==void 0&&M!==void 0&&E.actor!==M?void 0:E.sessionId}}let x=_??I,B=(E,Ge)=>qt({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,idempotencyKey:E,sessionKey:Ge,label:s?.label,...s?.sharedApp?{sharedApp:!0}:{},priority:e.priority,onAdmission:j=>{h.reportAdmission(j),j.sessionId&&!l&&(l=j.sessionId,k=j.sessionId,w&&w.sessionId!==j.sessionId&&L({...w,sessionId:j.sessionId}),T||(e.sessionKey||Cr(a,j.sessionId,u),y.setSessionId(j.sessionId)))},onRequest:L}),g;try{g=await B(v,x)}catch(E){if(I===void 0||!(E instanceof K)||E.code!=="session_name_not_yours")throw E;console.warn(`[urun] session_name_not_yours: the control plane refused session ${I} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),Pt(a,M)?.sessionId===I&&Be(a),g=await B(c(),void 0)}let F=f?await f()??void 0:e.jwt;if(k&&k!==g.sessionId)throw w&&w.sessionId!==g.sessionId&&L({...w,sessionId:g.sessionId}),new K(`Gateway contract violation: admission minted session ${k} but allocation completed as ${g.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return l=g.sessionId,w&&w.sessionId!==g.sessionId&&L({...w,sessionId:g.sessionId}),T||(e.sessionKey||Cr(a,g.sessionId,u),y.setSessionId(g.sessionId),y.setArtifactsAuth(ie({...m,baseUrl:g.baseUrl})),h.setEndsAt(g.endsAt),h.seedRegion(Gt(g.response))),{url:g.wsUrl,sessionId:g.sessionId,jwt:F,iceServers:g.response.ice_servers,endsAt:g.endsAt}},$,V=f?async()=>await f()??$:()=>$,X=()=>{let v=h.connectedUrl;return v?Ce(v):void 0};if(h.setConnectionResolver(async()=>{let v=await U(c());return $=v.jwt,v}),h.on("connected",()=>{h.multiplexer&&S.setTarget(h.multiplexer);let v=h.connectedUrl;v&&y.setDocTransport({wsUrl:v,token:V,resolveServerUrl:X})}),(async v=>{let k;try{k=await U(v)}catch(_){if(T){W({status:"unavailable",cause:_});return}console.error(`[urun] Failed to create session for ${r}:`,_),w&&H(w);let I=_ instanceof Error?_:new Error(String(_)),M=_ instanceof K?_.httpStatus:void 0,x=_ instanceof K?_.code:void 0,B=_ instanceof K?_.retryAfterSeconds:void 0;h.reportAllocationFailure(I,M,x,B),W({status:"unavailable",cause:_});return}T||(h.setAuth({jwt:k.jwt,authProvider:e.authProvider,orgId:e.orgId}),h.setConnection({url:k.url,sessionId:k.sessionId,iceServers:k.iceServers}),_e()&&await Te(),$=k.jwt,y.setDocTransport({wsUrl:k.url,token:V,resolveServerUrl:X}),await h.connect({app:i,functionName:r,args:o}),y.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(p).catch(v=>{console.error(`[urun] Failed to connect session for ${r}:`,v)}),e.releaseOnLeave!==!1){let v=ut(()=>{if(T=!0,h.leaveLeg())return;if(h.connectedUrl!==null){h.disconnect();return}h.disconnect();let x=w;x?N(x):C=!0});y.onDisconnect(v);let k,_,I=!1,M=()=>{I||(I=!0,k?.(),_?.())};b.then(x=>{x.status!=="ready"||I||(k=pt(()=>w!==void 0))}),_=y.onPhase(x=>{let B=x?.name;(B==="paused"||B==="error")&&M()}),I&&_(),y.onDisconnect(M)}return y}}})}var Ir="https://api.urun.sh",Dr="URUN_DEV";function gi(){if(typeof process>"u")return!1;let i=process.env?.[Dr];if(typeof i!="string")return!1;let e=i.trim().toLowerCase();return e==="1"||e==="true"}var Q=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function vi(i,e={}){if(!i)throw new Q("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=J(e.baseUrl??Ir),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata),e.sharedApp&&(n.shared_app=!0),(e.dev??gi())&&(n.dev=!0);let s;try{s=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(n)})}catch(u){throw new Q(`[urun] client token mint request failed: ${u instanceof Error?u.message:String(u)}`)}let o={};try{o=await s.json()}catch{}if(!s.ok){let u=typeof o.message=="string"?o.message:`HTTP ${s.status}`;throw new Q(`[urun] client token mint failed: ${u}`,s.status)}let a=typeof o.token=="string"?o.token:"",d=typeof o.org_id=="string"?o.org_id:"",l=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,c=typeof o.expires_in=="number"?o.expires_in:void 0;if(!a)throw new Q("[urun] client token mint returned no token (control-plane contract violation)",s.status);let p=Number.isFinite(l)?new Date(l):new Date(Date.now()+(c??60)*1e3);return{token:a,expiresAt:p,orgId:d}}var Pr=3e4,Lr="stream:",Lt=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let n;try{n=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(n.rpcId&&this._pendingRpc.has(n.rpcId)){let s=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(s.timer),n.error?s.reject(new Error(n.error)):s.resolve(n.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${Lr}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${Lr}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let s=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(s)&&(this._pendingRpc.delete(s),n(new Error(`RPC request "${e}" timed out after ${Pr}ms`)))},Pr);this._pendingRpc.set(s,{resolve:r,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:s,type:e,...t}))})}};function wi(i){let r=`${i.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(i.orgId)}`,n=new WebSocket(r);(i.jwt||i.apiKey)&&n.addEventListener("open",()=>{n.send(JSON.stringify({type:"auth",orgId:i.orgId,jwt:i.jwt,authProvider:i.authProvider,apiKey:i.apiKey}))});let s=new Nt(n);return new Lt(n,s)}var yi='video/mp4; codecs="avc1.42E01E"';function bi(i,e){let t=e?.codec??yi,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,s=URL.createObjectURL(n);r.src=s,n.addEventListener("sourceopen",()=>{let u;try{u=n.addSourceBuffer(t)}catch(h){throw h instanceof DOMException&&h.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):h}let f=i.getReader();function m(){return u.updating?new Promise(h=>{u.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function S(){try{for(;;){let{done:h,value:y}=await f.read();if(h){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{u.appendBuffer(y)}catch(w){if(w instanceof DOMException&&w.name==="QuotaExceededError"){let T=u.buffered;if(T.length>0){let C=T.start(T.length-1);u.remove(0,C),await m(),u.appendBuffer(y)}else throw w}else throw w}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}S()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let d=a.call(r),l=d.getTracks(),c=0,p=l.length;if(p===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(s)},{once:!0});else for(let u of l)u.addEventListener("ended",()=>{c++,c>=p&&URL.revokeObjectURL(s)});return d}function Si(i){return i.status.startsWith("pending_")}var te=class extends Error{status;code;constructor(e,t){super(e),this.name="CreditsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},we=class extends te{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function ki(i,e,t){let r=t||e||`HTTP ${i}`;return i===401?new we(r,e??"unauthorized"):new te(r,{status:i,code:e??`http_${i}`})}var je=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let e=await this._request("GET","/balance");if(!e||typeof e!="object"||typeof e.org_id!="string")throw new te("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let r=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(r)?r:[]}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),s=await this._resolveToken(),o=await this._fetch(n,e,s);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await this._fetch(n,e,s))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw ki(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r){let n={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(n["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:t,headers:n})}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 we("[urun] credits: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:n,message:s}=r;return{code:typeof n=="string"?n:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function _i(i){return new je(i)}var He=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function Ur(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function Ti(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function Ri(i,e){let t=i.getTracks();if(t.length===1&&t[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function Ut(i,e){for(let t of[...i.lostListeners])try{t(e)}catch{}}var Ve=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let r=this.claims.get(e);r&&(this.claims.delete(e),r.released=!0,r.track=null,r.stream=null,Ut(r,new Error(`${e} capture claim superseded by a newer claim`)));let n=this.createState(e,t);return this.claims.set(e,n),await this.converge(n),n.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new He;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},n;try{n=await t(r)}catch(o){let a=`one-capture getUserMedia(${Ur(r)}) failed`,d=o instanceof Error?o.message:String(o);for(let l of[...this.claims.values()])if(this.claims.delete(l.kind),l.released=!0,l!==e){let c=new Error(`${a} \u2014 ${l.kind} capture lost: ${d||o}`);c.cause=o,Ut(l,c)}throw o}let s=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of s){let a=Ti(n,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let d=Object.assign(new Error(`one-capture getUserMedia(${Ur(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw d;Ut(o,d);continue}if(o.track=a,o.stream=Ri(n,a),o!==e)for(let d of[...o.trackListeners])try{d(a,o.stream)}catch{}}}createState(e,t){let r=this,n={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return n.track},get stream(){return n.stream},update(s){return r.enqueue(async()=>{if(n.released)throw new Error(`${e} capture claim already released`);if(n.constraints=s,await r.converge(n),!n.track)throw new Error(`${e} capture update yielded no track`);return n.track})},release(){n.released||(n.released=!0,r.claims.get(e)===n&&r.claims.delete(e),n.track?.stop(),n.track=null,n.stream=null)},onTrack(s){return n.trackListeners.add(s),()=>n.trackListeners.delete(s)},onLost(s){return n.lostListeners.add(s),()=>n.lostListeners.delete(s)}}};return n}},Ai=null;function Ei(){return Ai??=new Ve}var Mr="input",Ci=30;function Ii(i){let e=i.now??Date.now,t=i.field??Mr,r=1e3/Math.max(i.hz??30,.001),n=new Set,s=0,o=0,a=0,d=0,l,c=null,p=!1,u=()=>{if(p)return;l=e(),d+=1;let m={keys:[...n],buttons:s,pointer:{x:o,y:a},seq:d,at:l};try{i.awareness.setLocalStateField(t,m)}catch{}},f=()=>{if(p)return;let m=e();if(l===void 0||m-l>=r){c&&(clearTimeout(c),c=null),u();return}if(c)return;let S=Math.max(r-(m-l),0);c=setTimeout(()=>{c=null,u()},S),c.unref?.()};return{keyDown(m){let S=String(m).toLowerCase();n.has(S)||(n.add(S),f())},keyUp(m){let S=String(m).toLowerCase();n.delete(S)&&f()},setButtons(m){let S=Number.isFinite(m)?Number(m):0;S!==s&&(s=S,f())},movePointer(m,S){let h=Number.isFinite(m)?Number(m):0,y=Number.isFinite(S)?Number(S):0;h===0&&y===0||(o+=h,a+=y,f())},heldKeys(){return[...n]},clear(){p||(n.clear(),s=0,c&&(clearTimeout(c),c=null),u())},dispose(){if(p)return;let m=n.size>0||s!==0;n.clear(),s=0,c&&(clearTimeout(c),c=null),m&&u(),p=!0}}}var Di=1024,Pi=.92,Li=262144,Ui=256e3,Mt=[.9,.8,.7,.6,.5],xr=.8,Mi=8;function Wt(i,e,t){if(!(i>0)||!(e>0))throw new Error(`reference image has no pixels (${i}x${e})`);let r=Math.min(1,t/Math.max(i,e));return{width:Math.max(1,Math.round(i*r)),height:Math.max(1,Math.round(e*r))}}async function xi(i){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(i,{imageOrientation:"from-image"})}async function Or(i,e,t){let r=await new Promise(n=>{i.toBlob(n,e,e==="image/jpeg"?t:void 0)});if(!r)throw new Error(`could not encode the reference image as ${e}`);return r}function Wr(i,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${i} -> ${e} bytes`)}async function xt(i,e,t,r,n){let s=document.createElement("canvas");s.width=e,s.height=t;let o=s.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,t)),o.drawImage(i,0,0,e,t),await Or(s,r,n)}async function Wi(i,e,t,r){let{width:n,height:s}=e,o=await xt(i,n,s,t,r);if(o.size<=256e3)return{blob:o,width:n,height:s};if(t==="image/jpeg"){for(let d of Mt)if(!(d>=r)&&(o=await xt(i,n,s,t,d),o.size<=256e3))return Wr(`quality ${r} -> ${d}`,o.size),{blob:o,width:n,height:s}}let a=t==="image/jpeg"?Mt[Mt.length-1]:r;for(let d=0;d<Mi;d++)if(n=Math.max(16,Math.round(n*xr)),s=Math.max(16,Math.round(s*xr)),o=await xt(i,n,s,t,a),o.size<=256e3)return Wr(`downscaled to ${n}x${s} @ q${a}`,o.size),{blob:o,width:n,height:s};throw new Error(`this image cannot be sent: even at ${n}x${s} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function Oi(i,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:s}=e,o=await xi(i);try{let a=Wt(o.width,o.height,t),d=await Wi(o,a,r,n);return{bytes:new Uint8Array(await d.blob.arrayBuffer()),type:r,width:d.width,height:d.height,source:s}}finally{o.close()}}function Ni(i){let e=i instanceof Error?i.name:"",t=i instanceof Error?i.message:String(i);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function Fi(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function $i(i,e){let t=i.videoWidth,r=i.videoHeight;if(!(t>0)||!(r>0))throw new Error("the camera has not shown a frame yet");let{maxSize:n=1024,type:s="image/jpeg",quality:o=.92}=e??{},a=Wt(t,r,n),d=document.createElement("canvas");d.width=a.width,d.height=a.height;let l=d.getContext("2d");if(!l)throw new Error("could not prepare the reference image (no 2d canvas context)");s==="image/jpeg"&&(l.fillStyle="#fff",l.fillRect(0,0,a.width,a.height)),l.drawImage(i,0,0,a.width,a.height);let c=await Or(d,s,o);return{bytes:new Uint8Array(await c.arrayBuffer()),type:s,width:a.width,height:a.height,source:"camera"}}var qi=new Set(["w","a","s","d"]),re=(i,e)=>Math.min(e,Math.max(-e,i));function Bi(i={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:n=900,frameRelax:s=.06,maxPan:o=.12,maxLogZoom:a=.22}=i,d=0,l=0,c=0,p=null,u=new Set;return{pointerDelta(f,m){d=re(d-f*e,o),l=re(l-m*e,o)},keyDown(f){let m=f.toLowerCase();qi.has(m)&&u.add(m)},keyUp(f){u.delete(f.toLowerCase())},clearKeys(){u.clear()},frameArrived(){let f=1-s;d*=f,l*=f,c*=f},tick(f){if(p===null){p=f;return}let m=Math.max(0,Math.min(100,f-p))/1e3;p=f,u.has("w")&&(c=re(c+t*m,a)),u.has("s")&&(c=re(c-t*m,a)),u.has("a")&&(d=re(d+r*m,o)),u.has("d")&&(d=re(d-r*m,o));let S=Math.exp(-m*1e3/n);d*=S,l*=S,c*=S},transform(){return{translateX:d,translateY:l,scale:Math.exp(c)}},isIdentity(f=5e-4){return Math.abs(d)<f&&Math.abs(l)<f&&Math.abs(c)<f},reset(){d=0,l=0,c=0,u.clear()}}}export{dn as ACTIVATION_COLD_BOOT_AFTER_MS,cn as ACTIVATION_DEGRADED_AFTER_MS,it as ACTIVATION_HINT_PATH,an as ACTIVATION_STILL_AFTER_MS,dt as ACTIVITY_DOM_EVENTS,tr as ACTIVITY_FIELD,Sn as ACTIVITY_STAMP_MIN_INTERVAL_MS,ne as ActivationMonitor,mi as App,Yr as BACKOFF_BASE_MS,Xr as BACKOFF_MAX_ATTEMPTS,Qr as BACKOFF_MAX_MS,Kr as COLD_BOOT_WHEN_LIVE_TIMEOUT_MS,Ve as CaptureController,He as CaptureUnavailableError,Q as ClientTokenError,je as CreditsClient,te as CreditsError,we as CreditsUnauthorizedError,Li as DATA_CHANNEL_MESSAGE_CEILING,_r as DEFAULT_DOC_SYNC_TIMEOUT_MS,Ir as DEFAULT_GATEWAY_URL,Nr as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Pi as DEFAULT_REFERENCE_JPEG_QUALITY,Di as DEFAULT_REFERENCE_MAX_SIZE,Gr as DEFAULT_WHEN_LIVE_TIMEOUT_MS,rn as DERIVED_LEG_SEP,P as DGRAM_HEADER_BYTES,sr as FOCUS_FIELD,_n as FOREGROUND_COALESCE_MS,le as FrameReassembler,yn as GENERATION_TICK_EMIT_INTERVAL_MS,bn as GENERATION_TICK_MAX_EXTRAPOLATION_MS,Ci as INPUT_PRESENCE_DEFAULT_HZ,Mr as INPUT_PRESENCE_FIELD,Z as InvalidDurationError,st as LEGACY_ACTIVATION_HINT_PATH,nt as PLATFORM_DOC_NAME,Me as PermanentLockedError,Ue as PinRequiresActiveTempError,oe as PresenceTracker,Fr as ProduceAckTimeoutError,Pe as RecordingNotFoundError,ee as RecordingsClient,O as RecordingsError,se as RecordingsUnauthorizedError,ke as RequestAbortError,Xe as RequestCancelledError,Ye as RequestDocSyncError,Se as RequestError,ze as RequestTimeoutError,Le as RetainNotTempError,De as RuntimeArtifactNotFoundError,z as RuntimeArtifactsClient,D as RuntimeArtifactsError,Ie as RuntimeArtifactsUnauthorizedError,on as SIGNALING_PROTOCOL_VERSION,tt as STREAM_END,ge as Session,K as SessionAllocationError,ve as SessionDirectory,be as SessionDirectoryError,Ke as SessionEndError,G as SessionEndUnavailableError,qr as SessionFailedError,Qe as StreamDirectionConflict,he as TransportNegotiator,jr as TransportSessionMismatchError,fe as TransportSessionSignaling,Dr as URUN_DEV_ENV,ir as USER_ACTIVITY_FIELD,kn as USER_ACTIVITY_MIN_INTERVAL_MS,rr as VISIBILITY_FIELD,Ui as WIRE_MESSAGE_BUDGET,dr as WT_CONTROL_FRAME_MAX,pr as WT_DATA_STREAM_VERSION,me as WebRtcSession,pe as WebTransportSession,de as WtControlDecoder,We as WtDataStreamParser,Jt as activationHintFrom,Fi as cameraCaptureAvailable,$i as captureStillFromVideo,Jr as computeBackoffDelay,wt as consumeWtDataStreams,ct as createActivityTracker,Bi as createCameraWarp,vi as createClientToken,_i as createCreditsClient,Ii as createInputPresencePublisher,wn as createRecordingsClient,un as createRuntimeArtifactsClient,wi as createStore,rt as decodeStreamEnvelope,sn as derivedLegName,nn as derivedLegRole,$r as describeSessionFailure,zr as describeSessionPhase,tn as encodeStreamEnvelope,mt as encodeWtControlFrame,Wt as fitWithin,ot as isDurationString,Vr as isPausedPhase,Si as isPendingRecording,Zr as isRetryableSessionError,Hr as isWakingPhase,ht as mediaRecorderChunkSource,Oi as normalizeReferenceImage,gn as normalizeRetention,pt as observeLeaveConfirm,lt as observePageLifecycle,ut as observePageTeardown,ce as parseDgramHeader,en as prewake,Ni as referenceImageErrorMessage,Re as releaseSessionBeacon,fi as sessionDirectory,Br as sessionFailureFromMediaError,Ei as sharedCaptureController,bi as videoStream,at as watchGenerationTick,Je as whenLive,gt as writeDgramHeader};
29
+ `)}var Ne=class{constructor(e){this.sink=e}sink;frameSeq=0;stopped=!1;deadCb=null;sendPc=null;recvPc=null;sender=null;currentTrack=null;renderSender=null;renderRemoteCb=null;renderEndedListener=null;worker=null;workerUrl=null;nodeBridge=null;endedListener=null;candQueue=null;negotiatedOnce=!1;negotiating=!1;renegotiateQueued=!1;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.currentTrack&&e.readyState==="live")return;let t=null;if(!(e!==null&&(t=Wn(e)?this.bridgedTrack(e):e,!t))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(t)}catch(r){this.die(`replaceTrack: ${r instanceof Error?r.message:String(r)}`);return}this.currentTrack=t,t&&this.wireTrackLiveness(t);return}t!==null&&this.engage(t)}}stop(){if(!this.stopped){this.stopped=!0,this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(e){let t=globalThis;if(typeof t.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof t.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let r;try{r=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let n=this.sendPc.addTrack(e);this.sender=n,this.currentTrack=e,this.wireTrackLiveness(e);let s=t.RTCRtpScriptTransform;if(n.transform=new s(r,{role:"sender"}),this.negotiatedOnce){this.negotiate().catch(o=>this.die(`loopback renegotiate: ${o instanceof Error?o.message:String(o)}`));return}this.negotiate().catch(o=>this.die(`loopback negotiate: ${o instanceof Error?o.message:String(o)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let t=e.RTCPeerConnection;this.sendPc=new t({iceServers:[]}),this.recvPc=new t({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=r=>{if(!r.candidate)return;let n=this.candQueue;n!==null&&(n.toRecv.push(r.candidate),this.flushCandidates())},this.recvPc.onicecandidate=r=>{if(!r.candidate)return;let n=this.candQueue;n!==null&&(n.toSend.push(r.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(r=>this.die(`loopback renegotiate: ${r instanceof Error?r.message:String(r)}`))},this.recvPc.ontrack=r=>{let n=r.transceiver?.mid??null;n!==null&&n===this.renderMidOf()&&this.renderRemoteCb?.(r.track)}}setRenderSource(e){if(!this.stopped){if(e===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(e);else try{this.renderSender.replaceTrack(e)}catch(t){this.die(`render replaceTrack: ${t instanceof Error?t.message:String(t)}`);return}this.wireRenderRemote(e),!this.negotiatedOnce&&this.sender&&this.negotiate().catch(t=>this.die(`loopback negotiate: ${t instanceof Error?t.message:String(t)}`))}}}onRenderTrack(e){this.renderRemoteCb=e}renderMidOf(){if(!this.renderSender)return null;let e=this.sendPc;try{return e.getTransceivers?.().find(t=>t.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(e){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},e.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let e=this.sendPc,t=this.recvPc;if(!(!e||!t||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let r=await e.createOffer();r.sdp=fr(r.sdp??""),await e.setLocalDescription(r),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:r.sdp});let n=await t.createAnswer();n.sdp=fr(n.sdp??""),await t.setLocalDescription(n),await e.setRemoteDescription(t.localDescription??{type:"answer",sdp:n.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let e=this.candQueue;if(e){for(;e.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(e.toSend.shift())).catch(()=>{});for(;e.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(e.toRecv.shift())).catch(()=>{})}}bridgedTrack(e){let t=e;try{let r=t.context.createMediaStreamDestination();t.connect(r);let n=r.stream.getAudioTracks()[0]??null;return n?(this.nodeBridge={node:t,dest:r},n):(this.die("AudioNode bridge produced no audio track"),null)}catch(r){return this.die(`AudioNode bridge: ${r instanceof Error?r.message:String(r)}`),null}}wireTrackLiveness(e){this.endedListener=()=>this.die("mic track ended"),e.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([xn],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=t=>{let r=t.data;r?.type==="enc"&&r.payload instanceof ArrayBuffer?this.onEncodedFrame(r.rtpTimestamp??0,new Uint8Array(r.payload)):r?.type==="err"&&this.die(`transform: ${r.detail??"unknown"}`)},e.onerror=t=>this.die(`transform worker: ${t.message||"error"}`),this.worker=e,e}onEncodedFrame(e,t){if(this.stopped)return;let r=St(this.frameSeq,e,t,this.sink.maxDatagramSize()||ue);if(r===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let n of r)this.sink.send(n);this.frameSeq=this.frameSeq+1>>>0}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function Wn(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var On=9e4,Nn="avc1.42E01F",Fn=60,$n=3,qn=1e4;function Bn(i){return Math.round(i*(On/1e6))%2**32>>>0}var Fe=class{constructor(e){this.sink=e}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}requestKeyframe(){this.keyframeWanted=!0}setSource(e){if(this.stopped||(this.teardownCapture(),e===null))return;let r=globalThis.MediaStreamTrackProcessor;if(typeof r!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let n=++this.generation,s=new r({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,s.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&n===this.generation;){let{value:a,done:d}=await s.read();if(d)break;if(a){if(o||this.stopped||n!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&n===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:Nn,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 n=this.keyframeWanted||this.framesSinceKeyframe>=Fn;this.keyframeWanted=!1,this.framesSinceKeyframe=n?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:n})}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 r=St(this.frameSeq,Bn(e.timestamp),t,this.sink.maxDatagramSize()||ue,{lane:lr,keyframe:e.type==="key"});if(r===null){console.warn(`[urun] WT video uplink: AU of ${t.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let n of r)this.sink.send(n);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(r=>t-r<qn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=$n){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 jn(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 r=new TextEncoder().encode(e);if(r.byteLength===0||r.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${r.byteLength})`));let n=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+r.byteLength);d[0]=1,d[1]=r.byteLength,d.set(r,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),jn(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=n.catch(()=>{}),n}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 mr=250,Hn=25,Vn=2e3,Gn=15e3,Kn=1e3,zn=45e3,Yn=500,gr=10,Qn=2,Xn=2,kt=2,pe=class i{constructor(e,t,r,n,s,o,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=n;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;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new le({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=this.offer.codec,r=t!==void 0&&t!=="";this.hasVideoLane=r,r&&vt(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(c=>({algorithm:"sha-256",value:Uint8Array.from(atob(c),p=>p.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let n=await this.wt.createBidirectionalStream();this.writer=n.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let s=n.readable.getReader(),o=new de,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")),r&&(vt(l.codec,"hello-ack"),this.initDecoder(l.codec,l.width,l.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let c={setSource:u=>{this.renderSource=u,this.audioUplinkLane?.setRenderSource?.(u)},onRemote:u=>{this.renderRemoteCb=u}},p=new Oe(this.offer.audio,{...this.audioLane,renderHop:c});try{p.start(),this.audioPlayout=p}catch(u){console.warn(`[urun] WT audio lane failed to start (${u instanceof Error?u.message:String(u)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),p.stop()}}if(this.offer.audioUp===!0&&this.audioUplink&&this.engageUplinkLane("audio"),this.offer.videoUp===!0&&this.videoUplink&&this.engageUplinkLane("video"),this.offer.dataUp===!0&&this.dataUplink)try{let c=this.wt.createUnidirectionalStream?.bind(this.wt);if(!c)throw new Error("WebTransport uni streams are not creatable in this environment");let p=new $e({openUniStream:async()=>(await c()).getWriter()});p.onDead(u=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(u,p)}),this.dataUplinkSender=p,this.dataUplink.onUplink(p)}catch(c){let p=c instanceof Error?c.message:String(c);console.warn(`[urun] WT data uplink failed to engage (${p}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(p)}this.controlLoop(s,o,a).catch(c=>this.die(`control loop: ${c}`)),this.datagramLoop().catch(c=>this.die(`datagram loop: ${c}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),Yn)),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 ${mr}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Gn},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Kn))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let t=typeof e.ds=="number"?e.ds:null,r=typeof e.ur=="number"?e.ur:null;if(t===null&&r===null)return;this.gatewayExposesCounters=!0;let n=this.audioDgramsReceived,s=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:r,recvDownlink:n,sentUplink:s},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,d=r!==null&&o.ur!==null?r-o.ur:null,l=n-o.recvDownlink,c=s-o.sentUplink,p="none";if(a!==null&&a>=gr&&l<=0?p="downlink":d!==null&&c>=gr&&d<=0&&(p="uplink"),p==="none"){this.severedStreak="none",this.observePlayoutProgress(l,t);return}if(this.severedStreak!==p){this.severedStreak=p;return}this.severedStreak="none";let u=p==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${c} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+u+` (gateway flow counters ds=${t} ur=${r}, client received=${n} accepted=${s}, confirmed on ${Qn} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,t){let r=this.audioPlayout;if(!r){this.playoutScheduledSeen=null;return}let n=r.playoutProgress(),s=n.surfaced;if(this.playoutScheduledSeen!==null&&n.scheduled>this.playoutScheduledSeen&&s){this.playoutScheduledSeen=n.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=n.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<Xn)){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=${n.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{r.rebuildSurface()}catch(o){console.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=kt}return}this.playoutStallStreak<kt||(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=${n.scheduled} on ${kt} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let t=this.pathLiveness();if(!t.alive)return;let r=performance.now(),n=this.audioLaneLastArrivalAt===null?null:r-this.audioLaneLastArrivalAt,s=this.lastInboundControlAt===null?null:r-this.lastInboundControlAt,o=n===null&&s===null?!0:(n===null||n>=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}o&&s!==null&&s>=zn&&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 n=this.audioUplinkLane;n?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e,n??void 0)}if(this.videoUplinkLane!==null||this.videoUplinkRetry!==null){let n=this.videoUplinkLane;n?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e,n??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)");this.dataLaneSink=e,wt(this.wt.incomingUnidirectionalStreams,e).catch(t=>{this.die(`data lane: ${t instanceof Error?t.message:String(t)}`)})}initDecoder(e,t,r){let n=globalThis.VideoDecoder;if(typeof n!="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:r};let o=new n({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&&r>0?{codedWidth:t,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"}),this.decoder=o}onDecoderError(e){if(this.stopped||this.deadFired)return;console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=this.decoderConfig;if(!t){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder error with no retained config to re-init from \u2014 video stays down: ${e.message}`));return}try{this.initDecoder(t.codec,t.width,t.height),this.decoderErrorLogged=!1}catch(r){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${r instanceof Error?r.message:String(r)}`));return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}uplinkSend(e,t){if(this.stopped||this.deadFired)return;this.datagramWriter().write(e).then(t,n=>this.onUplinkSendError(n))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let t=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,console.error(`[urun] WT uplink datagram send FAILED (${t}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let r=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(n=>r-n<Vn),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<Hn)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSink(e){this.datagramWriter();let t=0;return{send:r=>this.uplinkSend(r,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??ue}}engageAudioUplink(){let e=new Ne(this.uplinkSink("audio"));e.onDead(t=>this.onUplinkLaneDead("audio",t,e)),e.onRenderTrack?.(t=>this.renderRemoteCb?.(t)),this.renderSource&&e.setRenderSource?.(this.renderSource),this.audioUplinkLane=e,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(e)}engageVideoUplink(){let e=new Fe(this.uplinkSink("video"));e.onDead(t=>this.onUplinkLaneDead("video",t,e)),this.videoUplinkLane=e,this.videoUplinkRetry=this.freshLaneBuilt(this.videoUplinkRetry),this.videoUplink.onUplink(e)}engageUplinkLane(e){let t=e==="audio"?"mic":"video";try{e==="audio"?this.engageAudioUplink():this.engageVideoUplink()}catch(r){let n=r instanceof Error?r.message:String(r);console.warn(`[urun] WT ${t} uplink failed to engage (${n}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,n)}}freshLaneBuilt(e){let t={count:e?.count??0,builtAt:Date.now(),timer:void 0};return e&&(clearTimeout(e.timer),e.timer=void 0),t}onUplinkLaneDead(e,t,r){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let n=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 ${n} 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}`,r);return}console.warn(`[urun] WT ${n} 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,r){e==="audio"?this.audioUplink.onUplinkLost(t,r):this.videoUplink.onUplinkLost(t,r)}clearUplinkRetryTimers(){for(let e of[this.audioUplinkRetry,this.videoUplinkRetry])e&&(clearTimeout(e.timer),e.timer=void 0)}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:r}=await e.read();if(r)break;if(!t)continue;if(t.byteLength>=P&&t[11]===xe){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let n=performance.now();if(this.lastArrivalTs>0){let s=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(s-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=n,this.reassembler.push(t)}}decodeFrame(e,t,r){let n=globalThis.EncodedVideoChunk;if(typeof n=="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 n({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(mt(e)),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async sendControlRaw(e){try{let t=new Uint8Array(4+e.byteLength);new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),await this.writer.write(t),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async readControl(e,t,r=[]){for(;;){let n=r.shift();if(n)return n;let{value:s,done:o}=await e.read();if(o)return null;s&&r.push(...t.push(s))}}async controlLoop(e,t,r){for(;!this.stopped;){let n=await this.readControl(e,t,r);if(!n)break;let s=n;if(this.lastInboundControlAt=performance.now(),s.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(cr(n.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(),r=(t-e)/1e3;e=t;let n=this.reassembler.drainWindow(),s=n.delivered+n.abandoned;this.lastStats={recvBps:r>0?n.bytes*8/r:0,lossPct:s>0?100*n.abandoned/s:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},mr)}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 vr=2500,wr=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Jn=1e4,he=class i{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;static WT_REDIAL_BASE_MS=2e3;static WT_REDIAL_MAX=3;static WT_REDIAL_CAP_MS=3e4;wtRedialFailures=0;wtRedialTimer=null;disconnected=!1;downlinkStallWatch=null;watchDownlinkStall(e={}){this.downlinkStallWatch={stallMs:e.stallMs??15e3},this.applyStallWatch()}applyStallWatch(){let e=this.session;!e||e.kind!=="webtransport"||!this.downlinkStallWatch||e.watchDownlinkStall?.(this.downlinkStallWatch)}failCurrentWtLeg(e){if(this.disconnected)return;let t=this.session;!t||t.kind!=="webtransport"||t.fail?.(e)}get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis;this.disconnected=!1;let t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,s={webtransport:t&&r&&n,webcodecs:r,codecs:wr,wtData:t&&r&&n&&this.opts.dataLane!==void 0,wtAudio:t&&r&&n&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&n&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:t&&r&&n&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&r&&n&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:s});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 _t(l.start(),this.opts.quicDeadlineMs??vr,"quic connect deadline"),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(l?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let p=String(c instanceof Error?c.message:c);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${p}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(p),c}console.warn("[urun] webtransport failed, falling back to webrtc:",c),this.proceedWebRtcDial(`wt failed: ${String(c instanceof Error?c.message:c)}`),this.notifyEstablished("webrtc",String(c instanceof Error?c.message:c))}}if(this.opts.allowWebRtcFallback===!1){let l=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${l} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(l),new Error(`[urun] WT required but unavailable: ${l}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.disconnected=!0,this.wtRedialTimer!==null&&(clearTimeout(this.wtRedialTimer),this.wtRedialTimer=null),this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,await e?.stop()}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let r=this.session,n=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:wr,wtData:n,wtAudio:s,wtAudioUp:o,wtVideoUp:a,wtDataUp:d}}),!this.offer.webtransport)return null;let l=this.createWebTransportSession();try{await _t(l.start(),this.opts.quicDeadlineMs??vr,"quic connect deadline")}catch(c){throw l.stop().catch(()=>{}),c}if(this.session!==r)return l.stop().catch(()=>{}),null;try{this.engageQuicDataLane(l,n)}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"),r?.stop().catch(()=>{}),l}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let r=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(n,s)=>r.onData(n,s),onLaneError:n=>r.onLaneError(n)}),r.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e,this.opts.audioLane);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new pe(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;this.wtRedialFailures=0,this.applyStallWatch(),e.onDead(t=>{if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; re-dialing WT (attempt 1 immediate, then the bounded ladder)`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.redialWtAfterDeath(t);return}let r=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),r){this.session=null,this.wtOnlyLeg=!1,console.warn("[urun] quic died mid-session on a WT-only leg \u2014 RE-DIALING WebTransport first (same session id; the late WebRTC dial is the fallback):",t),this.redialWtAfterDeath(t);return}console.warn("[urun] quic died mid-session, failing over to webrtc:",t),this.lateWebRtcFailover(e,t,r)})}redialWtAfterDeath(e){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures+=1,this.wtRedialFailures===i.WT_REDIAL_MAX+1){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 t=this.wtRedialFailures,r=Rt(i.WT_REDIAL_BASE_MS,t,i.WT_REDIAL_CAP_MS,t===1?0:void 0);console.warn(`[urun] WT re-dial attempt ${t} 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}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 r=Tt(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${i.WT_REDIAL_MAX} failed (${r}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${r}`)}}}lateWebRtcFailover(e,t,r){this.disconnected||(async()=>{let n=this.createWebRtc();try{let s=await _t(this.startWebRtcOn(n),this.opts.webRtcFailoverDeadlineMs??Jn,"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(n.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=s instanceof Error?s.message:String(s),a=r?`media transport lost \u2014 the WebTransport connection dropped (${t}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${t}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;console.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function Tt(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 Rt(i,e,t,r){if(r!==void 0)return r;let n=Math.min(i*2**Math.max(0,e-2),t);return Math.round(n*(.75+Math.random()*.5))}function _t(i,e,t){return new Promise((r,n)=>{let s=setTimeout(()=>n(new Error(t)),e);i.then(o=>{clearTimeout(s),r(o)},o=>{clearTimeout(s),n(o)})})}var Zn=1e4,fe=class{constructor(e,t=Zn){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let r=Ae();return new Promise((n,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!==r)return;if(clearTimeout(o),a(),d.error){s(new Error(`[urun] ${e} failed: ${String(d.error)}`));return}let{type:l,requestId:c,...p}=d;n(p)});this.carrier.sendSignal({type:e,requestId:r,...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(r=>{r.type===e&&t(r)})}};var ei="video",me=class{constructor(e,t=ei){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,n)=>{this.firstMediaResolve=r,this.firstMediaReject=n}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};function yr(i){let e=i;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var ti="video";function br(i,e,t){let r=globalThis,n=r.document;if(!(typeof n?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=i.holdWebRtcDial?.(),a=n.createElement("canvas"),d=!1,l=null,c=!1,p=()=>{if(l){for(let b of l.getVideoTracks())try{b.stop()}catch{}l=null}c&&(c=!1,t.onOverrideTrack(null))},u=new he(new fe(i),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new me(i,t.streamName??ti)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(b,A)=>i.dispatchQuicStreamData(b,A),onQuicLane:()=>i.markStreamDataLaneQuic(),onQuicLaneLost:b=>i.quicStreamDataLaneLost(b),onLaneError:b=>i.raiseQuicStreamDataError(b)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:b=>{d||(b&&i.noteQuicMediaFlowing?.(),t.onOverrideAudioTrack(b))}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>C(),onMediaTransportLost:b=>{d||(p(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(b),C())},onTransportChange:(b,A)=>{d||(b==="webrtc"&&(p(),C()),t.onTransportChange?.(b,A))}}),f=i.onWtOnlyLegDeath?.(b=>u.failCurrentWtLeg(b)),m=null,S=()=>{m!==null&&(clearInterval(m),m=null)},h=t.wtRetryBaseMs??2e3,y=t.wtRetryCapMs??3e4,w=null,T=0,C=()=>{if(d||w!==null||u.activeTransport==="webtransport")return;let b=Rt(h,T+2,y);w=setTimeout(()=>{w=null,T+=1,u.retryWebTransport().then(A=>{if(d){A&&u.disconnect().catch(()=>{});return}if(A)return console.debug(`[urun] webtransport upgraded in background (retry ${T})`),T=0,W(A);C()}).catch(A=>{d||(console.debug(`[urun] webtransport background retry ${T} failed: `+Tt(A)),C())})},b)},R=()=>{w!==null&&(clearTimeout(w),w=null)},W=async b=>{if(d||b.kind!=="webtransport")return;let A=t.pathHealthProbeMs??1e4;S();let N=!1;m=setInterval(()=>{if(d||u.activeTransport!=="webtransport")return;let L=yr(b);if(!L){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 U=L.pathLiveness();if(!U.alive){let $=u.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${U.evidence}`+($?" \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(),L.fail(`path health: ${U.evidence}`);return}if(!N){if(N=!0,u.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${A}ms \u2014 the QUIC PATH IS HEALTHY (${U.evidence}), so this is an IDLE APPLICATION, not a dead path; keeping the leg (WT-only leg: no webrtc track exists) and continuing to watch the path`);return}console.warn(`[urun] webtransport established but no QUIC media after ${A}ms \u2014 no media datagrams reached this client (path healthy: ${U.evidence}); webrtc track remains authoritative`)}},A);try{await b.firstMedia}catch(L){S(),console.debug("[urun] webtransport ended before any media flowed:",L);return}if(S(),d||u.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;l=a.captureStream();let H=l.getVideoTracks()[0];H&&(c=!0,t.onOverrideTrack(H))};return(async()=>{let b=await u.connect();if(d){u.disconnect().catch(()=>{});return}await W(b)})().catch(b=>{if(S(),d){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",b);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",b),C();return}o?.proceed(`negotiation unavailable: ${b instanceof Error?b.message:String(b)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",b),C()}),{activeTransport:()=>u.activeTransport,watchDownlinkStall(b){u.watchDownlinkStall(b)},dispose(){d=!0,f?.(),S(),R(),p(),t.onOverrideAudioTrack?.(null),u.disconnect().catch(()=>{})}}}var ri=new Set;function Ct(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var ni="rpc",ii="$presence",_r=3e4,Sr=3e4,si="rpc-resp";function oi(i){return`${si}:${i}`}function At(){return Ae()}function ai(i){if(i&&typeof i=="object"){let e=i.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof i=="string"?i:JSON.stringify(i)}}function di(i,e,t,r,n,s,o,a,d,l){let c=[],p=null,u=!1,f=null,m=!1,S,h,y=new Promise((g,F)=>{S=g,h=F});y.catch(()=>{});let w=o(),T=null,C=null,R=null,W=null,b=null,A=null,N=!0,H=()=>{R&&(clearTimeout(R),R=null),W&&(W(),W=null)},L=()=>{b&&(clearTimeout(b),b=null),A&&(A(),A=null)},U=!1,$=()=>{U||!m||(U=!0,i.set({rpc:{[e]:null}}))},V=()=>{N=!1,H(),L(),T?.(),T=null,C?.(),C=null,a?.removeEventListener("abort",_),w.dispose(),$()},X=()=>{if(p){if(c.length>0){let g=p;p=null,g.resolve({value:c.shift(),done:!1})}else if(f!==null){let g=p;p=null,g.reject(f)}else if(u){let g=p;p=null,g.resolve({value:void 0,done:!0})}}},Ot=g=>{u||(c.push(g),X())},v=g=>{u||(f=g,u=!0,h(g),V(),X())},k=g=>{u||(u=!0,S(g),V(),X())},_=()=>{let g=a?.reason;v(g instanceof Se?g:new ke(e))},I=g=>{if(!(u||!g||typeof g!="object"))switch(L(),$(),g.t){case"delta":typeof g.delta=="string"&&Ot(g.delta);break;case"response":k(g.body);break;case"error":{let{message:F,code:E}=ai(g.body);v(new Se(F,{requestId:e,code:g.code??E}));break}}},M=()=>{let g=w.messages()[Symbol.asyncIterator]();T=()=>{g.return?.(void 0)};let F=()=>{N&&g.next().then(E=>{if(N){if(E.done){u||k(void 0);return}I(E.value),F()}},E=>{N&&v(E)})};F()},x=()=>{if(!m){if(m=!0,a){if(a.aborted){v(new ke(e));return}a.addEventListener("abort",_,{once:!0})}C=d?.(g=>v(g))??null,M(),i.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:s}}}),l&&l>0&&!i.synced&&(R=setTimeout(()=>{R=null,!u&&!i.synced&&v(new Ye(l,e))},l),W=i.onSynced(()=>H())),A=i.onSynced(()=>{A=null,!(u||U||b)&&(b=setTimeout(()=>{b=null,!(u||U)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(Sr/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).`)},Sr))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(x(),c.length>0)return Promise.resolve({value:c.shift(),done:!1});if(f!==null){let g=f;return f=null,Promise.reject(g)}return u?Promise.resolve({value:void 0,done:!0}):new Promise((g,F)=>{p={resolve:g,reject:F}})},return(){return u||(u=!0,S(void 0),V()),Promise.resolve({value:void 0,done:!0})},throw(g){return u||(u=!0,h(g),V()),Promise.reject(g)}}}},body:y,start:x}}function kr(i){if(i&&typeof i=="object"){let{epoch:e,by:t}=i,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function ci(i,e){let r=i.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:n,rt:s,br:o}=r,a={};(n==="audio"||n==="video"||n==="data")&&(a.kind=n);let d=kr(s);d&&(a.rt=d);let l=kr(o);return l&&(a.br=l),a}var Et=class{constructor(e,t,r,n,s){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=n;this._onActivity=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,n=!1,s=null,o={push(d){if(!n)if(r){let l=r;r=null,l.resolve({value:d,done:!1})}else t.push(d)},end(){if(n=!0,r){let d=r;r=null,d.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{n=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(d=>{if(!(d===null||n)&&(s=e._streamConsumeUnavailableError(d),a(),r)){let l=r;r=null,l.reject(s)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.reject(s):n?Promise.resolve({value:void 0,done:!0}):new Promise((d,l)=>{r={resolve:d,reject:l}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let n of r)n(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=ci(t,this._name),n=r?.br;if(n?.by==="runtime")throw new Qe(this._name,"runtime","browser");if(n)return;let s={br:{epoch:1}};r?.rt&&(s.rt=r.rt);let o=r?.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??ht;return ar(t,{track:()=>this.track,onTrack:n=>this.on("track",n)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},ge=class i{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Yt;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,r,n,s,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=n,this._artifactsAuth=s,this._streamData=Kt(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=lt(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=ct({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new oe({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(ii).awareness.setLocalState({role:"client"}),this._activation=new ne({onPhase:a=>this.onPhase(a),hint:()=>this.doc(nt).get(it)??this.doc("control").get(st),onData:(a,d)=>this._streamData.onData(a,d)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await Vt({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),n=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,s=new ye,o=new Ee({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new i(e,s,o,Ct(t),ie({...t,baseUrl:r.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&s.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),o.setEndsAt(r.endsAt),_e()&&await Te();let d=t.getAccessToken,l=d?async()=>await d()??n:n;return a.setDocTransport({wsUrl:r.wsUrl,token:l}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}get region(){return this._transport.region}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return Je(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=at(this.doc("control"),r=>{for(let n of Array.from(this._generationTickHandlers))try{n(r)}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 ee(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,n)=>t.retain(r,n),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new z(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new z(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new Et(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 Qt(e,this._sessionId,ri.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Xt(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=Ce(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",n=`${t}\0${r}\0${this._sessionId}`;n!==this._docEndpointKey&&(this._docEndpointKey=n,this.connectDocs(zt({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let r=At(),n=new AbortController;t.signal&&(t.signal.aborted?n.abort(t.signal.reason):t.signal.addEventListener("abort",()=>n.abort(t.signal.reason),{once:!0}));let s=null;if(typeof t.timeout=="number"&&t.timeout>=0){let d=t.timeout;s=setTimeout(()=>n.abort(new ze(d,r)),d)}let o=this._consumeResponse(r,e,!1,n.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{s&&clearTimeout(s),a?.()})}_consumeResponse(e,t,r,n,s){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(ni),a=oi(e);return di(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),s??_r)}requestStream(e,t={}){let r=At();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=At(),n=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return n.start(),n.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=br(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t),onOverrideAudioTrack:t=>this.stream("audio")._setOverrideTrack(t),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}),this._downlinkStallWatch&&this._dialNegotiation?.watchDownlinkStall(this._downlinkStallWatch))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}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 G)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new G);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 n of t)try{n()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let r=Array.from(this._activeRequests);this._activeRequests.clear();for(let n of r)try{n(new Xe)}catch{}for(let n of this._docs.values())n.dispose();this._docs.clear();for(let n of this._streams.values())n.dispose();this._streams.clear(),this._transport.disconnect(e)}};function Tr(i){return`urun:session:v2:${i.orgId}:${i.app}:${i.functionName}`}function It(){try{return globalThis.sessionStorage??null}catch{return null}}var Dt=new Map;function qe(i){if(!i)return;let e=i.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=JSON.parse(atob(t+"=".repeat((4-t.length%4)%4)));return typeof r?.sub=="string"&&r.sub.length>0?r.sub:void 0}catch{return}}function li(i,e){return i!==void 0&&e!==void 0&&i!==e}function Pt(i,e){let t=It(),r=null;if(t)try{let s=t.getItem(i);if(s){let o=JSON.parse(s);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(r={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{r=null}let n=Dt.get(i)??r??null;return!n||li(n.actor,e)?null:n}function Rr(i,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};Dt.set(i,t);let r=It();if(r)try{r.setItem(i,JSON.stringify(t))}catch{}}function Be(i){Dt.delete(i);let e=It();if(e)try{e.removeItem(i)}catch{}}var Ar=new Set(["paused","acquiring","live"]),ui=new Set(["24h","keep"]);function Er(i){if(typeof i!="string"||i.length===0)return null;let e=new Date(i);return Number.isFinite(e.getTime())?e:null}function pi(i){if(typeof i?.id!="string"||i.id.length===0)throw new be("[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"||!Ar.has(i.state))throw new be(`[urun] session ${i.id} reported an unrecognized state ${JSON.stringify(i.state)} \u2014 this @urun-sh/core build knows only ${[...Ar].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:Er(i.created_at),lastActiveAt:Er(i.last_active_at),archived:i.archived===!0,preview:typeof i.preview=="string"&&i.preview.length>0?i.preview:null,recordingsExpired:e,retention:ui.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 ve=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:r}=await Bt({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(pi),nextCursor:r}}async end(e){await jt({...this._request,sessionId:e})}async archive(e){await et({...this._request,sessionId:e,archived:!0})}async unarchive(e){await et({...this._request,sessionId:e,archived:!1})}async setName(e,t,r={}){await Ht({...this._request,sessionId:e,name:t,source:r.source})}};function Cr(i,e,t){let r=qe(t);Rr(i,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}var hi=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function fi(i,e){return new ve(i,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function mi(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,r){if(!(hi.has(r)||typeof r!="string"))return(n,s)=>{let o=n??{},a=Tr({orgId:e.orgId,app:i,functionName:r}),d=!s?.sessionId&&!e.sessionKey&&!!s?.label,l,c=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,p=c(),u=e.jwt,f=e.getAccessToken?async v=>{let k=await e.getAccessToken(v);return k&&(u=k),k}:void 0,m={...e,getAccessToken:f},S=new ye,h=new Ee({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:p,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),y=new ge(p,S,h,Ct(m),ie(m),{activity:s?.activity}),w,T=!1,C=!1,R,W,b=new Promise(v=>{W=v}),A,N=v=>{v.sessionId||R||(R="teardown",A="ticket",Re({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))},H=v=>{R||v.sessionId||(R="abandon",Re({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider,reason:"client_abandoned"}))},L=v=>{let k=v.sessionId||!l?v:{...v,sessionId:l};w=k,W({status:"ready",handle:k}),(C||R==="teardown")&&N(k)};y.setEndHandler(async()=>{let v=w?{status:"ready",handle:w}:await b;if(v.status==="unavailable")throw new G("[urun] session allocation failed before a releasable request was created",{cause:v.cause});let k=w??v.handle;return Be(a),R==="teardown"?k.sessionId?{status:"paused",sessionId:k.sessionId,reason:"client_ended"}:{status:"canceled",requestId:k.requestId}:(R="end",k.sessionId?$t({baseUrl:k.baseUrl,sessionId:k.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):Ze({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),y.setCancelHandler(async()=>{let v=w?{status:"ready",handle:w}:await b;if(v.status==="unavailable")throw new G("[urun] session allocation failed before a cancellable request was created",{cause:v.cause});let k=w??v.handle;if(k.sessionId)throw new Ke(`[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"});R="end";try{let _=await Ze({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return Be(a),_}catch(_){throw R==="end"&&(R=void 0),_}});let U=async v=>{let k,_=s?.sessionId??e.sessionKey??l,I,M;if(_===void 0&&!d){let E=Pt(a);if(E?.sessionId){if(M=qe(u),E.actor!==void 0&&M===void 0&&f){let Ge=await Promise.resolve(f()).catch(()=>{});M=qe(Ge??e.jwt)}I=E.actor!==void 0&&M!==void 0&&E.actor!==M?void 0:E.sessionId}}let x=_??I,B=(E,Ge)=>qt({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,idempotencyKey:E,sessionKey:Ge,label:s?.label,...s?.sharedApp?{sharedApp:!0}:{},priority:e.priority,onAdmission:j=>{h.reportAdmission(j),j.sessionId&&!l&&(l=j.sessionId,k=j.sessionId,w&&w.sessionId!==j.sessionId&&L({...w,sessionId:j.sessionId}),T||(e.sessionKey||Cr(a,j.sessionId,u),y.setSessionId(j.sessionId)))},onRequest:L}),g;try{g=await B(v,x)}catch(E){if(I===void 0||!(E instanceof K)||E.code!=="session_name_not_yours")throw E;console.warn(`[urun] session_name_not_yours: the control plane refused session ${I} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),Pt(a,M)?.sessionId===I&&Be(a),g=await B(c(),void 0)}let F=f?await f()??void 0:e.jwt;if(k&&k!==g.sessionId)throw w&&w.sessionId!==g.sessionId&&L({...w,sessionId:g.sessionId}),new K(`Gateway contract violation: admission minted session ${k} but allocation completed as ${g.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return l=g.sessionId,w&&w.sessionId!==g.sessionId&&L({...w,sessionId:g.sessionId}),T||(e.sessionKey||Cr(a,g.sessionId,u),y.setSessionId(g.sessionId),y.setArtifactsAuth(ie({...m,baseUrl:g.baseUrl})),h.setEndsAt(g.endsAt),h.seedRegion(Gt(g.response))),{url:g.wsUrl,sessionId:g.sessionId,jwt:F,iceServers:g.response.ice_servers,endsAt:g.endsAt}},$,V=f?async()=>await f()??$:()=>$,X=()=>{let v=h.connectedUrl;return v?Ce(v):void 0};if(h.setConnectionResolver(async()=>{let v=await U(c());return $=v.jwt,v}),h.on("connected",()=>{h.multiplexer&&S.setTarget(h.multiplexer);let v=h.connectedUrl;v&&y.setDocTransport({wsUrl:v,token:V,resolveServerUrl:X})}),(async v=>{let k;try{k=await U(v)}catch(_){if(T){W({status:"unavailable",cause:_});return}console.error(`[urun] Failed to create session for ${r}:`,_),w&&H(w);let I=_ instanceof Error?_:new Error(String(_)),M=_ instanceof K?_.httpStatus:void 0,x=_ instanceof K?_.code:void 0,B=_ instanceof K?_.retryAfterSeconds:void 0;h.reportAllocationFailure(I,M,x,B),W({status:"unavailable",cause:_});return}T||(h.setAuth({jwt:k.jwt,authProvider:e.authProvider,orgId:e.orgId}),h.setConnection({url:k.url,sessionId:k.sessionId,iceServers:k.iceServers}),_e()&&await Te(),$=k.jwt,y.setDocTransport({wsUrl:k.url,token:V,resolveServerUrl:X}),await h.connect({app:i,functionName:r,args:o}),y.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(p).catch(v=>{console.error(`[urun] Failed to connect session for ${r}:`,v)}),e.releaseOnLeave!==!1){let v=ut(()=>{if(T=!0,h.leaveLeg())return;if(h.connectedUrl!==null){h.disconnect();return}h.disconnect();let x=w;x?N(x):C=!0});y.onDisconnect(v);let k,_,I=!1,M=()=>{I||(I=!0,k?.(),_?.())};b.then(x=>{x.status!=="ready"||I||(k=pt(()=>w!==void 0))}),_=y.onPhase(x=>{let B=x?.name;(B==="paused"||B==="error")&&M()}),I&&_(),y.onDisconnect(M)}return y}}})}var Ir="https://api.urun.sh",Dr="URUN_DEV";function gi(){if(typeof process>"u")return!1;let i=process.env?.[Dr];if(typeof i!="string")return!1;let e=i.trim().toLowerCase();return e==="1"||e==="true"}var Q=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function vi(i,e={}){if(!i)throw new Q("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=J(e.baseUrl??Ir),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata),e.sharedApp&&(n.shared_app=!0),(e.dev??gi())&&(n.dev=!0);let s;try{s=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(n)})}catch(u){throw new Q(`[urun] client token mint request failed: ${u instanceof Error?u.message:String(u)}`)}let o={};try{o=await s.json()}catch{}if(!s.ok){let u=typeof o.message=="string"?o.message:`HTTP ${s.status}`;throw new Q(`[urun] client token mint failed: ${u}`,s.status)}let a=typeof o.token=="string"?o.token:"",d=typeof o.org_id=="string"?o.org_id:"",l=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,c=typeof o.expires_in=="number"?o.expires_in:void 0;if(!a)throw new Q("[urun] client token mint returned no token (control-plane contract violation)",s.status);let p=Number.isFinite(l)?new Date(l):new Date(Date.now()+(c??60)*1e3);return{token:a,expiresAt:p,orgId:d}}var Pr=3e4,Lr="stream:",Lt=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let n;try{n=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(n.rpcId&&this._pendingRpc.has(n.rpcId)){let s=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(s.timer),n.error?s.reject(new Error(n.error)):s.resolve(n.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${Lr}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${Lr}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let s=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(s)&&(this._pendingRpc.delete(s),n(new Error(`RPC request "${e}" timed out after ${Pr}ms`)))},Pr);this._pendingRpc.set(s,{resolve:r,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:s,type:e,...t}))})}};function wi(i){let r=`${i.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(i.orgId)}`,n=new WebSocket(r);(i.jwt||i.apiKey)&&n.addEventListener("open",()=>{n.send(JSON.stringify({type:"auth",orgId:i.orgId,jwt:i.jwt,authProvider:i.authProvider,apiKey:i.apiKey}))});let s=new Nt(n);return new Lt(n,s)}var yi='video/mp4; codecs="avc1.42E01E"';function bi(i,e){let t=e?.codec??yi,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,s=URL.createObjectURL(n);r.src=s,n.addEventListener("sourceopen",()=>{let u;try{u=n.addSourceBuffer(t)}catch(h){throw h instanceof DOMException&&h.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):h}let f=i.getReader();function m(){return u.updating?new Promise(h=>{u.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function S(){try{for(;;){let{done:h,value:y}=await f.read();if(h){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{u.appendBuffer(y)}catch(w){if(w instanceof DOMException&&w.name==="QuotaExceededError"){let T=u.buffered;if(T.length>0){let C=T.start(T.length-1);u.remove(0,C),await m(),u.appendBuffer(y)}else throw w}else throw w}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}S()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let d=a.call(r),l=d.getTracks(),c=0,p=l.length;if(p===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(s)},{once:!0});else for(let u of l)u.addEventListener("ended",()=>{c++,c>=p&&URL.revokeObjectURL(s)});return d}function Si(i){return i.status.startsWith("pending_")}var te=class extends Error{status;code;constructor(e,t){super(e),this.name="CreditsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},we=class extends te{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function ki(i,e,t){let r=t||e||`HTTP ${i}`;return i===401?new we(r,e??"unauthorized"):new te(r,{status:i,code:e??`http_${i}`})}var je=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let e=await this._request("GET","/balance");if(!e||typeof e!="object"||typeof e.org_id!="string")throw new te("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let r=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(r)?r:[]}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),s=await this._resolveToken(),o=await this._fetch(n,e,s);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await this._fetch(n,e,s))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw ki(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r){let n={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(n["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:t,headers:n})}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 we("[urun] credits: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:n,message:s}=r;return{code:typeof n=="string"?n:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function _i(i){return new je(i)}var He=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function Ur(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function Ti(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function Ri(i,e){let t=i.getTracks();if(t.length===1&&t[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function Ut(i,e){for(let t of[...i.lostListeners])try{t(e)}catch{}}var Ve=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let r=this.claims.get(e);r&&(this.claims.delete(e),r.released=!0,r.track=null,r.stream=null,Ut(r,new Error(`${e} capture claim superseded by a newer claim`)));let n=this.createState(e,t);return this.claims.set(e,n),await this.converge(n),n.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new He;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},n;try{n=await t(r)}catch(o){let a=`one-capture getUserMedia(${Ur(r)}) failed`,d=o instanceof Error?o.message:String(o);for(let l of[...this.claims.values()])if(this.claims.delete(l.kind),l.released=!0,l!==e){let c=new Error(`${a} \u2014 ${l.kind} capture lost: ${d||o}`);c.cause=o,Ut(l,c)}throw o}let s=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of s){let a=Ti(n,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let d=Object.assign(new Error(`one-capture getUserMedia(${Ur(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw d;Ut(o,d);continue}if(o.track=a,o.stream=Ri(n,a),o!==e)for(let d of[...o.trackListeners])try{d(a,o.stream)}catch{}}}createState(e,t){let r=this,n={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return n.track},get stream(){return n.stream},update(s){return r.enqueue(async()=>{if(n.released)throw new Error(`${e} capture claim already released`);if(n.constraints=s,await r.converge(n),!n.track)throw new Error(`${e} capture update yielded no track`);return n.track})},release(){n.released||(n.released=!0,r.claims.get(e)===n&&r.claims.delete(e),n.track?.stop(),n.track=null,n.stream=null)},onTrack(s){return n.trackListeners.add(s),()=>n.trackListeners.delete(s)},onLost(s){return n.lostListeners.add(s),()=>n.lostListeners.delete(s)}}};return n}},Ai=null;function Ei(){return Ai??=new Ve}var Mr="input",Ci=30;function Ii(i){let e=i.now??Date.now,t=i.field??Mr,r=1e3/Math.max(i.hz??30,.001),n=new Set,s=0,o=0,a=0,d=0,l,c=null,p=!1,u=()=>{if(p)return;l=e(),d+=1;let m={keys:[...n],buttons:s,pointer:{x:o,y:a},seq:d,at:l};try{i.awareness.setLocalStateField(t,m)}catch{}},f=()=>{if(p)return;let m=e();if(l===void 0||m-l>=r){c&&(clearTimeout(c),c=null),u();return}if(c)return;let S=Math.max(r-(m-l),0);c=setTimeout(()=>{c=null,u()},S),c.unref?.()};return{keyDown(m){let S=String(m).toLowerCase();n.has(S)||(n.add(S),f())},keyUp(m){let S=String(m).toLowerCase();n.delete(S)&&f()},setButtons(m){let S=Number.isFinite(m)?Number(m):0;S!==s&&(s=S,f())},movePointer(m,S){let h=Number.isFinite(m)?Number(m):0,y=Number.isFinite(S)?Number(S):0;h===0&&y===0||(o+=h,a+=y,f())},heldKeys(){return[...n]},clear(){p||(n.clear(),s=0,c&&(clearTimeout(c),c=null),u())},dispose(){if(p)return;let m=n.size>0||s!==0;n.clear(),s=0,c&&(clearTimeout(c),c=null),m&&u(),p=!0}}}var Di=1024,Pi=.92,Li=262144,Ui=256e3,Mt=[.9,.8,.7,.6,.5],xr=.8,Mi=8;function Wt(i,e,t){if(!(i>0)||!(e>0))throw new Error(`reference image has no pixels (${i}x${e})`);let r=Math.min(1,t/Math.max(i,e));return{width:Math.max(1,Math.round(i*r)),height:Math.max(1,Math.round(e*r))}}async function xi(i){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(i,{imageOrientation:"from-image"})}async function Or(i,e,t){let r=await new Promise(n=>{i.toBlob(n,e,e==="image/jpeg"?t:void 0)});if(!r)throw new Error(`could not encode the reference image as ${e}`);return r}function Wr(i,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${i} -> ${e} bytes`)}async function xt(i,e,t,r,n){let s=document.createElement("canvas");s.width=e,s.height=t;let o=s.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,t)),o.drawImage(i,0,0,e,t),await Or(s,r,n)}async function Wi(i,e,t,r){let{width:n,height:s}=e,o=await xt(i,n,s,t,r);if(o.size<=256e3)return{blob:o,width:n,height:s};if(t==="image/jpeg"){for(let d of Mt)if(!(d>=r)&&(o=await xt(i,n,s,t,d),o.size<=256e3))return Wr(`quality ${r} -> ${d}`,o.size),{blob:o,width:n,height:s}}let a=t==="image/jpeg"?Mt[Mt.length-1]:r;for(let d=0;d<Mi;d++)if(n=Math.max(16,Math.round(n*xr)),s=Math.max(16,Math.round(s*xr)),o=await xt(i,n,s,t,a),o.size<=256e3)return Wr(`downscaled to ${n}x${s} @ q${a}`,o.size),{blob:o,width:n,height:s};throw new Error(`this image cannot be sent: even at ${n}x${s} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function Oi(i,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:s}=e,o=await xi(i);try{let a=Wt(o.width,o.height,t),d=await Wi(o,a,r,n);return{bytes:new Uint8Array(await d.blob.arrayBuffer()),type:r,width:d.width,height:d.height,source:s}}finally{o.close()}}function Ni(i){let e=i instanceof Error?i.name:"",t=i instanceof Error?i.message:String(i);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function Fi(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function $i(i,e){let t=i.videoWidth,r=i.videoHeight;if(!(t>0)||!(r>0))throw new Error("the camera has not shown a frame yet");let{maxSize:n=1024,type:s="image/jpeg",quality:o=.92}=e??{},a=Wt(t,r,n),d=document.createElement("canvas");d.width=a.width,d.height=a.height;let l=d.getContext("2d");if(!l)throw new Error("could not prepare the reference image (no 2d canvas context)");s==="image/jpeg"&&(l.fillStyle="#fff",l.fillRect(0,0,a.width,a.height)),l.drawImage(i,0,0,a.width,a.height);let c=await Or(d,s,o);return{bytes:new Uint8Array(await c.arrayBuffer()),type:s,width:a.width,height:a.height,source:"camera"}}var qi=new Set(["w","a","s","d"]),re=(i,e)=>Math.min(e,Math.max(-e,i));function Bi(i={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:n=900,frameRelax:s=.06,maxPan:o=.12,maxLogZoom:a=.22}=i,d=0,l=0,c=0,p=null,u=new Set;return{pointerDelta(f,m){d=re(d-f*e,o),l=re(l-m*e,o)},keyDown(f){let m=f.toLowerCase();qi.has(m)&&u.add(m)},keyUp(f){u.delete(f.toLowerCase())},clearKeys(){u.clear()},frameArrived(){let f=1-s;d*=f,l*=f,c*=f},tick(f){if(p===null){p=f;return}let m=Math.max(0,Math.min(100,f-p))/1e3;p=f,u.has("w")&&(c=re(c+t*m,a)),u.has("s")&&(c=re(c-t*m,a)),u.has("a")&&(d=re(d+r*m,o)),u.has("d")&&(d=re(d-r*m,o));let S=Math.exp(-m*1e3/n);d*=S,l*=S,c*=S},transform(){return{translateX:d,translateY:l,scale:Math.exp(c)}},isIdentity(f=5e-4){return Math.abs(d)<f&&Math.abs(l)<f&&Math.abs(c)<f},reset(){d=0,l=0,c=0,u.clear()}}}export{dn as ACTIVATION_COLD_BOOT_AFTER_MS,cn as ACTIVATION_DEGRADED_AFTER_MS,it as ACTIVATION_HINT_PATH,an as ACTIVATION_STILL_AFTER_MS,dt as ACTIVITY_DOM_EVENTS,tr as ACTIVITY_FIELD,Sn as ACTIVITY_STAMP_MIN_INTERVAL_MS,ne as ActivationMonitor,mi as App,Yr as BACKOFF_BASE_MS,Xr as BACKOFF_MAX_ATTEMPTS,Qr as BACKOFF_MAX_MS,Kr as COLD_BOOT_WHEN_LIVE_TIMEOUT_MS,Ve as CaptureController,He as CaptureUnavailableError,Q as ClientTokenError,je as CreditsClient,te as CreditsError,we as CreditsUnauthorizedError,Li as DATA_CHANNEL_MESSAGE_CEILING,_r as DEFAULT_DOC_SYNC_TIMEOUT_MS,Ir as DEFAULT_GATEWAY_URL,Nr as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Pi as DEFAULT_REFERENCE_JPEG_QUALITY,Di as DEFAULT_REFERENCE_MAX_SIZE,Gr as DEFAULT_WHEN_LIVE_TIMEOUT_MS,rn as DERIVED_LEG_SEP,P as DGRAM_HEADER_BYTES,sr as FOCUS_FIELD,_n as FOREGROUND_COALESCE_MS,le as FrameReassembler,yn as GENERATION_TICK_EMIT_INTERVAL_MS,bn as GENERATION_TICK_MAX_EXTRAPOLATION_MS,Ci as INPUT_PRESENCE_DEFAULT_HZ,Mr as INPUT_PRESENCE_FIELD,Z as InvalidDurationError,st as LEGACY_ACTIVATION_HINT_PATH,nt as PLATFORM_DOC_NAME,Me as PermanentLockedError,Ue as PinRequiresActiveTempError,oe as PresenceTracker,Fr as ProduceAckTimeoutError,Pe as RecordingNotFoundError,ee as RecordingsClient,O as RecordingsError,se as RecordingsUnauthorizedError,ke as RequestAbortError,Xe as RequestCancelledError,Ye as RequestDocSyncError,Se as RequestError,ze as RequestTimeoutError,Le as RetainNotTempError,De as RuntimeArtifactNotFoundError,z as RuntimeArtifactsClient,D as RuntimeArtifactsError,Ie as RuntimeArtifactsUnauthorizedError,on as SIGNALING_PROTOCOL_VERSION,tt as STREAM_END,ge as Session,K as SessionAllocationError,ve as SessionDirectory,be as SessionDirectoryError,Ke as SessionEndError,G as SessionEndUnavailableError,qr as SessionFailedError,Qe as StreamDirectionConflict,he as TransportNegotiator,jr as TransportSessionMismatchError,fe as TransportSessionSignaling,Dr as URUN_DEV_ENV,ir as USER_ACTIVITY_FIELD,kn as USER_ACTIVITY_MIN_INTERVAL_MS,rr as VISIBILITY_FIELD,Ui as WIRE_MESSAGE_BUDGET,dr as WT_CONTROL_FRAME_MAX,pr as WT_DATA_STREAM_VERSION,me as WebRtcSession,pe as WebTransportSession,de as WtControlDecoder,We as WtDataStreamParser,Jt as activationHintFrom,Fi as cameraCaptureAvailable,$i as captureStillFromVideo,Jr as computeBackoffDelay,wt as consumeWtDataStreams,ct as createActivityTracker,Bi as createCameraWarp,vi as createClientToken,_i as createCreditsClient,Ii as createInputPresencePublisher,wn as createRecordingsClient,un as createRuntimeArtifactsClient,wi as createStore,rt as decodeStreamEnvelope,sn as derivedLegName,nn as derivedLegRole,$r as describeSessionFailure,zr as describeSessionPhase,tn as encodeStreamEnvelope,mt as encodeWtControlFrame,Wt as fitWithin,ot as isDurationString,Vr as isPausedPhase,Si as isPendingRecording,Zr as isRetryableSessionError,Hr as isWakingPhase,ht as mediaRecorderChunkSource,Oi as normalizeReferenceImage,gn as normalizeRetention,pt as observeLeaveConfirm,lt as observePageLifecycle,ut as observePageTeardown,ce as parseDgramHeader,en as prewake,Ni as referenceImageErrorMessage,Re as releaseSessionBeacon,fi as sessionDirectory,Br as sessionFailureFromMediaError,Ei as sharedCaptureController,bi as videoStream,at as watchGenerationTick,Je as whenLive,gt as writeDgramHeader};