@urun-sh/core 0.6.14 → 0.6.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/index.js +7 -7
- package/dist/adapter/index.mjs +1 -1
- package/dist/{app-C5CQ2W7V.mjs → app-JQES6MVY.mjs} +1 -1
- package/dist/chunk-GEHV47FN.mjs +30 -0
- package/dist/index.browser.d.mts +10 -2
- package/dist/index.browser.d.ts +10 -2
- package/dist/index.browser.js +4 -4
- package/dist/index.browser.mjs +3 -3
- package/dist/index.d.mts +10 -2
- package/dist/index.d.ts +10 -2
- package/dist/index.js +7 -7
- package/dist/index.mjs +1 -1
- package/dist/internal.browser.d.mts +1 -1
- package/dist/internal.browser.d.ts +1 -1
- package/dist/internal.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/package.json +1 -1
- package/dist/chunk-NQNN244C.mjs +0 -30
- /package/dist/{stream-data-BP5Nzvtw.d.mts → stream-data-BHDuPKhI.d.mts} +0 -0
- /package/dist/{stream-data-BP5Nzvtw.d.ts → stream-data-BHDuPKhI.d.ts} +0 -0
- /package/dist/{stream-data-D86z7UJ5.d.mts → stream-data-gthI5aJp.d.mts} +0 -0
- /package/dist/{stream-data-D86z7UJ5.d.ts → stream-data-gthI5aJp.d.ts} +0 -0
package/dist/index.browser.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as en,B as Te,C as Kr,D as Gr,E as zr,F as Yr,G as Qr,H as J,I as Nt,J as Re,K as Ze,L as Ft,M as $t,N as qt,O as et,P as Bt,Q as jt,R as Xr,S as Ht,T as Ae,U as tt,V as Jr,W as rt,Y as Vt,_ as Zr,a as Ot,aa as tn,b as be,ba as rn,c as K,ca as Ee,d as Ge,e as ye,ea as Ce,f as ke,fa as Kt,g as ze,ga as Gt,h as Ye,ha as zt,i as Qe,ia as Yt,j as Mr,k as Wr,l as Se,m as Xe,n as Or,o as Nr,p as Fr,q as $r,r as G,s as qr,t as Br,u as jr,v as Hr,w as Je,x as Vr,y as _e}from"./chunk-F2X3TCVZ.mjs";var nn=15e3,sn=45e3,on=12e4,nt="platform",it="activation",st="desired.activation";function Qt(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 an=[{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 an){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=Qt(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 dn(i){return new z(i)}var z=class{_options;constructor(e){this._options=e}async list(e){let r=Jt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new D("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(Xt)}async getDownloadUrl(e,t){let r=Jt(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!ln(n))throw new D("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Xt(r.artifact),downloadUrl:n}}async _request(e,t){let r=Nt(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&&un(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 pn(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 Xt(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=cn(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 cn(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function ln(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function un(i){return i===401||i===403}function pn(i,e,t){return i===401?new Ie(t,e):i===404?new De(t,e):new D(t,i,e)}function Jt(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)}},xe=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 hn(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 fn(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 xe(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 fn(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 mn(i){return new ee(i)}var gn=1e3,vn=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 b=i.get("desired.billing.epoch"),w=i.get("desired.billing.updatedAtMs");return{seconds:h,epoch:typeof b=="number"&&Number.isFinite(b)?b: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 b=i.get("desired.billing.creditsPerSecond");return typeof b=="number"&&Number.isFinite(b)&&b>0?b:null},p=()=>{let h=l();if(h===null)return;let b=Math.floor(h);if(b<=a)return;a=b;let w={seconds:b},T=c();T!==null&&(w.estimatedCredits=b*T),e(w)},u=h=>{n=Date.now();let b=h===null?0:Math.max(0,n-h);s=Math.max(0,12e3-b)},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),k=setInterval(p,1e3);return k.unref?.(),()=>{clearInterval(k),m()}}var Zt="activity",er="visibility",wn=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(Zt,{at:u})}catch{}}},d=()=>{if(!(s||!n||n.visibilityState===void 0))try{i.awareness.setLocalStateField(er,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 rr="user_activity",nr="focus",bn=3e4;function tr(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(tr(e.state));let t=e.on("stateChange",n=>{this._setState(tr(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(nr,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(rr,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 yn=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 ir="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(ir)?ir:void 0),u=new MediaStream([a]),f=new c(u,p?{mimeType:p}:void 0);r=f;let m=Promise.resolve();f.ondataavailable=k=>{let h=k.data;s||!h||h.size===0||(m=m.then(async()=>{let b=new Uint8Array(await h.arrayBuffer());s||d(b)}))},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 kn(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 sr(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 kn(s)}import{encode as Sn,decode as _n}from"@msgpack/msgpack";var or=65536;function mt(i){let e=Sn(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>or)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(_n(n),{raw:n}))}return t}};function ar(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,k=ae(i,t,d);d=k.end;let b=ae(i,t,d).end;if(Tn(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,k.end))==="t"){l.push(i.subarray(m,k.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,b))}else l.push(i.subarray(m,b));d=b}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 Tn(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,Rn=0,Me=1,dr=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??Rn),e}var An=100,cr=100,le=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??An}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-cr?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-cr}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 En=/^avc[13]\.[0-9a-fA-F]{6}$/;function Cn(i){return En.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=Cn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var lr=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!==lr)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&&In(r,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function In(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 bt=40,Y=48e3,Dn=64,Pn=100,yt=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-Pn)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>Dn;){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??bt;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${bt}ms`),r=bt),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;assembler=new yt(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(r){throw this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,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}if(!this.trackSurfaced){this.trackSurfaced=!0,r.resume?.().catch(()=>{});let p=n.stream.getAudioTracks()[0];p&&this.surfaceTrack(p)}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),t!==void 0&&(this.lastTsS=t/Y),this.playhead=c+d}armBridgeEndedWatch(e){e.addEventListener?.("ended",()=>{if(!this.stopped){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(t){console.error(`[urun] WT audio bridge rebuild failed \u2014 the reply stays silent until the next lane death re-delivers: ${t instanceof Error?t.message:String(t)}`)}}},{once:!0})}rebuildSurface(){let e=globalThis.AudioContext;if(typeof e!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");let t=this.ctx,r=new e({sampleRate:this.config.sampleRate});this.ctx=r,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),t?.close().catch(()=>{})}surfaceTrack(e){this.bridgeTrack=e,this.armBridgeEndedWatch(e),this.seam.onTrack(e);let t=this.seam.renderHop;t&&(t.onRemote(r=>{if(this.stopped)return;let n=this.bridgeTrack&&this.bridgeTrack.readyState==="live"?this.bridgeTrack:null;this.seam.onTrack(r??n??null)}),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 kt(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??Me}),p=new Uint8Array(P+l.byteLength);p.set(c,0),p.set(l,P),a.push(p)}return a}var Ln=`
|
|
1
|
+
import{$ as rn,B as Te,C as zr,D as Yr,E as Qr,F as Xr,G as Jr,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 Zr,S as Vt,T as Ae,U as tt,V as en,W as rt,Y as Gt,_ as tn,a as Nt,aa as nn,b as be,ba as sn,c as G,ca as Ee,d as Ke,e as ye,ea as Ce,f as Se,fa as Kt,g as ze,ga as zt,h as Ye,ha as Yt,i as Qe,ia as Qt,j as Or,k as Nr,l as ke,m as Xe,n as Fr,o as $r,p as qr,q as Br,r as K,s as jr,t as Hr,u as Vr,v as Gr,w as Je,x as Kr,y as _e}from"./chunk-F2X3TCVZ.mjs";var on=15e3,an=45e3,dn=12e4,nt="platform",it="activation",st="desired.activation";function Xt(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 cn=[{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 cn){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=Xt(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 ln(i){return new z(i)}var z=class{_options;constructor(e){this._options=e}async list(e){let r=Zt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new D("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(Jt)}async getDownloadUrl(e,t){let r=Zt(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!pn(n))throw new D("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Jt(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&&hn(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 fn(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 Jt(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=un(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 un(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function pn(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function hn(i){return i===401||i===403}function fn(i,e,t){return i===401?new Ie(t,e):i===404?new De(t,e):new D(t,i,e)}function Zt(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 mn(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 gn(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 gn(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 vn(i){return new ee(i)}var wn=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 b=i.get("desired.billing.epoch"),w=i.get("desired.billing.updatedAtMs");return{seconds:h,epoch:typeof b=="number"&&Number.isFinite(b)?b: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 b=i.get("desired.billing.creditsPerSecond");return typeof b=="number"&&Number.isFinite(b)&&b>0?b:null},p=()=>{let h=l();if(h===null)return;let b=Math.floor(h);if(b<=a)return;a=b;let w={seconds:b},T=c();T!==null&&(w.estimatedCredits=b*T),e(w)},u=h=>{n=Date.now();let b=h===null?0:Math.max(0,n-h);s=Math.max(0,12e3-b)},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 er="activity",tr="visibility",yn=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(er,{at:u})}catch{}}},d=()=>{if(!(s||!n||n.visibilityState===void 0))try{i.awareness.setLocalStateField(tr,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 nr="user_activity",ir="focus",Sn=3e4;function rr(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(rr(e.state));let t=e.on("stateChange",n=>{this._setState(rr(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(ir,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(nr,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 kn=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 sr="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(sr)?sr: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 b=new Uint8Array(await h.arrayBuffer());s||d(b)}))},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 _n(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 or(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 _n(s)}import{encode as Tn,decode as Rn}from"@msgpack/msgpack";var ar=65536;function mt(i){let e=Tn(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>ar)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(Rn(n),{raw:n}))}return t}};function dr(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 b=ae(i,t,d).end;if(An(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,b))}else l.push(i.subarray(m,b));d=b}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 An(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,En=0,xe=1,cr=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??En),e}var Cn=100,lr=100,le=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??Cn}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-lr?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-lr}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 In=/^avc[13]\.[0-9a-fA-F]{6}$/;function Dn(i){return In.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=Dn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var ur=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!==ur)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&&Pn(r,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function Pn(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 bt=40,pr=2,Y=48e3,Ln=64,Un=100,yt=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-Un)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>Ln;){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??bt;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${bt}ms`),r=bt),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 yt(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>=pr){e-this.rebuildBudgetLoggedAt>1e4&&(this.rebuildBudgetLoggedAt=e,console.error(`[urun] WT audio bridge rebuild budget spent (${pr} 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 Mn=`
|
|
2
2
|
self.onrtctransform = (event) => {
|
|
3
3
|
const transformer = event.transformer
|
|
4
4
|
if (transformer.options?.role === 'sender') {
|
|
@@ -24,6 +24,6 @@ self.onrtctransform = (event) => {
|
|
|
24
24
|
self.postMessage({ type: 'err', detail: String(e) }))
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
|
-
`;function
|
|
27
|
+
`;function hr(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=Un(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=ur(r.sdp??""),await e.setLocalDescription(r),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:r.sdp});let n=await t.createAnswer();n.sdp=ur(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([Ln],{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=kt(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 Un(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var xn=9e4,Mn="avc1.42E01F",Wn=60,On=3,Nn=1e4;function Fn(i){return Math.round(i*(xn/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:Mn,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>=Wn;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=kt(this.frameSeq,Fn(e.timestamp),t,this.sink.maxDatagramSize()||ue,{lane:dr,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<Nn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=On){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 $n(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),$n(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 pr=250,qn=25,Bn=2e3,jn=15e3,Hn=1e3,Vn=45e3,Kn=500,hr=10,Gn=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";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(),Kn)),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 ${pr}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??jn},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Hn))}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"}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>=hr&&l<=0?p="downlink":d!==null&&c>=hr&&d<=0&&(p="uplink"),p==="none"){this.severedStreak="none";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 ${Gn} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}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>=Vn&&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<Bn),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<qn)&&(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]===Me){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(ar(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(()=>{})},pr)}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 fr=2500,mr=["av01.0.08M.08","avc1.42E01F","avc1.640028"],zn=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:mr,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 St(l.start(),this.opts.quicDeadlineMs??fr,"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:mr,wtData:n,wtAudio:s,wtAudioUp:o,wtVideoUp:a,wtDataUp:d}}),!this.offer.webtransport)return null;let l=this.createWebTransportSession();try{await St(l.start(),this.opts.quicDeadlineMs??fr,"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=Tt(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=_t(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 St(this.startWebRtcOn(n),this.opts.webRtcFailoverDeadlineMs??zn,"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 _t(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 Tt(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 St(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 Yn=1e4,fe=class{constructor(e,t=Yn){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 Qn="video",me=class{constructor(e,t=Qn){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 gr(i){let e=i;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var Xn="video";function vr(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 y of l.getVideoTracks())try{y.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??Xn)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(y,A)=>i.dispatchQuicStreamData(y,A),onQuicLane:()=>i.markStreamDataLaneQuic(),onQuicLaneLost:y=>i.quicStreamDataLaneLost(y),onLaneError:y=>i.raiseQuicStreamDataError(y)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:y=>{d||t.onOverrideAudioTrack(y)}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>C(),onMediaTransportLost:y=>{d||(p(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(y),C())},onTransportChange:(y,A)=>{d||(y==="webrtc"&&(p(),C()),t.onTransportChange?.(y,A))}}),f=i.onWtOnlyLegDeath?.(y=>u.failCurrentWtLeg(y)),m=null,k=()=>{m!==null&&(clearInterval(m),m=null)},h=t.wtRetryBaseMs??2e3,b=t.wtRetryCapMs??3e4,w=null,T=0,C=()=>{if(d||w!==null||u.activeTransport==="webtransport")return;let y=Tt(h,T+2,b);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: `+_t(A)),C())})},y)},R=()=>{w!==null&&(clearTimeout(w),w=null)},W=async y=>{if(d||y.kind!=="webtransport")return;let A=t.pathHealthProbeMs??1e4;k();let N=!1;m=setInterval(()=>{if(d||u.activeTransport!=="webtransport")return;let L=gr(y);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)"),k();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"),k(),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 y.firstMedia}catch(L){k(),console.debug("[urun] webtransport ended before any media flowed:",L);return}if(k(),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 y=await u.connect();if(d){u.disconnect().catch(()=>{});return}await W(y)})().catch(y=>{if(k(),d){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",y);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",y),C();return}o?.proceed(`negotiation unavailable: ${y instanceof Error?y.message:String(y)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",y),C()}),{activeTransport:()=>u.activeTransport,watchDownlinkStall(y){u.watchDownlinkStall(y)},dispose(){d=!0,f?.(),k(),R(),p(),t.onOverrideAudioTrack?.(null),u.disconnect().catch(()=>{})}}}var Jn=new Set;function Et(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var Zn="rpc",ei="$presence",yr=3e4,wr=3e4,ti="rpc-resp";function ri(i){return`${ti}:${i}`}function Rt(){return Ae()}function ni(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 ii(i,e,t,r,n,s,o,a,d,l){let c=[],p=null,u=!1,f=null,m=!1,k,h,b=new Promise((g,F)=>{k=g,h=F});b.catch(()=>{});let w=o(),T=null,C=null,R=null,W=null,y=null,A=null,N=!0,H=()=>{R&&(clearTimeout(R),R=null),W&&(W(),W=null)},L=()=>{y&&(clearTimeout(y),y=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})}}},Wt=g=>{u||(c.push(g),X())},v=g=>{u||(f=g,u=!0,h(g),V(),X())},S=g=>{u||(u=!0,k(g),V(),X())},_=()=>{let g=a?.reason;v(g instanceof ke?g:new Se(e))},I=g=>{if(!(u||!g||typeof g!="object"))switch(L(),$(),g.t){case"delta":typeof g.delta=="string"&&Wt(g.delta);break;case"response":S(g.body);break;case"error":{let{message:F,code:E}=ni(g.body);v(new ke(F,{requestId:e,code:g.code??E}));break}}},x=()=>{let g=w.messages()[Symbol.asyncIterator]();T=()=>{g.return?.(void 0)};let F=()=>{N&&g.next().then(E=>{if(N){if(E.done){u||S(void 0);return}I(E.value),F()}},E=>{N&&v(E)})};F()},M=()=>{if(!m){if(m=!0,a){if(a.aborted){v(new Se(e));return}a.addEventListener("abort",_,{once:!0})}C=d?.(g=>v(g))??null,x(),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||y)&&(y=setTimeout(()=>{y=null,!(u||U)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(wr/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).`)},wr))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(M(),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,k(void 0),V()),Promise.resolve({value:void 0,done:!0})},throw(g){return u||(u=!0,h(g),V()),Promise.reject(g)}}}},body:b,start:M}}function br(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 si(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=br(s);d&&(a.rt=d);let l=br(o);return l&&(a.br=l),a}var At=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=si(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 sr(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 Gt;_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=Vt(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(ei).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 jt({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 be,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,Et(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 At(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._autoTouch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new zt(e,this._sessionId,Jn.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Yt(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(Kt({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=Rt(),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(Zn),a=ri(e);return ii(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),s??yr)}requestStream(e,t={}){let r=Rt();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Rt(),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=vr(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 K)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new K);let e=this._cancelHandler().then(t=>(this.disconnect(),t));return this._cancelPromise=e,e.catch(()=>{this._cancelPromise===e&&(this._cancelPromise=void 0)}),e}disconnect(){this.detach()}detach(e){let t=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let 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 kr(i){return`urun:session:v2:${i.orgId}:${i.app}:${i.functionName}`}function Ct(){try{return globalThis.sessionStorage??null}catch{return null}}var It=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 oi(i,e){return i!==void 0&&e!==void 0&&i!==e}function Dt(i,e){let t=Ct(),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=It.get(i)??r??null;return!n||oi(n.actor,e)?null:n}function Sr(i,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};It.set(i,t);let r=Ct();if(r)try{r.setItem(i,JSON.stringify(t))}catch{}}function Be(i){It.delete(i);let e=Ct();if(e)try{e.removeItem(i)}catch{}}var _r=new Set(["paused","acquiring","live"]),ai=new Set(["24h","keep"]);function Tr(i){if(typeof i!="string"||i.length===0)return null;let e=new Date(i);return Number.isFinite(e.getTime())?e:null}function di(i){if(typeof i?.id!="string"||i.id.length===0)throw new ye("[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"||!_r.has(i.state))throw new ye(`[urun] session ${i.id} reported an unrecognized state ${JSON.stringify(i.state)} \u2014 this @urun-sh/core build knows only ${[..._r].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:Tr(i.created_at),lastActiveAt:Tr(i.last_active_at),archived:i.archived===!0,preview:typeof i.preview=="string"&&i.preview.length>0?i.preview:null,recordingsExpired:e,retention:ai.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 qt({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(di),nextCursor:r}}async end(e){await Bt({...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})}};function Rr(i,e,t){let r=qe(t);Sr(i,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}var ci=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function li(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 ui(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(!(ci.has(r)||typeof r!="string"))return(n,s)=>{let o=n??{},a=kr({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 S=await e.getAccessToken(v);return S&&(u=S),S}:void 0,m={...e,getAccessToken:f},k=new be,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}),b=new ge(p,k,h,Et(m),ie(m),{activity:s?.activity}),w,T=!1,C=!1,R,W,y=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 S=v.sessionId||!l?v:{...v,sessionId:l};w=S,W({status:"ready",handle:S}),(C||R==="teardown")&&N(S)};b.setEndHandler(async()=>{let v=w?{status:"ready",handle:w}:await y;if(v.status==="unavailable")throw new K("[urun] session allocation failed before a releasable request was created",{cause:v.cause});let S=w??v.handle;return Be(a),R==="teardown"?S.sessionId?{status:"paused",sessionId:S.sessionId,reason:"client_ended"}:{status:"canceled",requestId:S.requestId}:(R="end",S.sessionId?Ft({baseUrl:S.baseUrl,sessionId:S.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):Ze({baseUrl:S.baseUrl,requestId:S.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),b.setCancelHandler(async()=>{let v=w?{status:"ready",handle:w}:await y;if(v.status==="unavailable")throw new K("[urun] session allocation failed before a cancellable request was created",{cause:v.cause});let S=w??v.handle;if(S.sessionId)throw new Ge(`[urun] cancel() is for a queued admission request, but this call already has session ${S.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:S.sessionId,code:"cancel_on_live_session"});R="end";try{let _=await Ze({baseUrl:S.baseUrl,requestId:S.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 S,_=s?.sessionId??e.sessionKey??l,I,x;if(_===void 0&&!d){let E=Dt(a);if(E?.sessionId){if(x=qe(u),E.actor!==void 0&&x===void 0&&f){let Ke=await Promise.resolve(f()).catch(()=>{});x=qe(Ke??e.jwt)}I=E.actor!==void 0&&x!==void 0&&E.actor!==x?void 0:E.sessionId}}let M=_??I,B=(E,Ke)=>$t({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,idempotencyKey:E,sessionKey:Ke,label:s?.label,...s?.sharedApp?{sharedApp:!0}:{},priority:e.priority,onAdmission:j=>{h.reportAdmission(j),j.sessionId&&!l&&(l=j.sessionId,S=j.sessionId,w&&w.sessionId!==j.sessionId&&L({...w,sessionId:j.sessionId}),T||(e.sessionKey||Rr(a,j.sessionId,u),b.setSessionId(j.sessionId)))},onRequest:L}),g;try{g=await B(v,M)}catch(E){if(I===void 0||!(E instanceof G)||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`),Dt(a,x)?.sessionId===I&&Be(a),g=await B(c(),void 0)}let F=f?await f()??void 0:e.jwt;if(S&&S!==g.sessionId)throw w&&w.sessionId!==g.sessionId&&L({...w,sessionId:g.sessionId}),new G(`Gateway contract violation: admission minted session ${S} 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||Rr(a,g.sessionId,u),b.setSessionId(g.sessionId),b.setArtifactsAuth(ie({...m,baseUrl:g.baseUrl})),h.setEndsAt(g.endsAt),h.seedRegion(Ht(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&&k.setTarget(h.multiplexer);let v=h.connectedUrl;v&&b.setDocTransport({wsUrl:v,token:V,resolveServerUrl:X})}),(async v=>{let S;try{S=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(_)),x=_ instanceof G?_.httpStatus:void 0,M=_ instanceof G?_.code:void 0,B=_ instanceof G?_.retryAfterSeconds:void 0;h.reportAllocationFailure(I,x,M,B),W({status:"unavailable",cause:_});return}T||(h.setAuth({jwt:S.jwt,authProvider:e.authProvider,orgId:e.orgId}),h.setConnection({url:S.url,sessionId:S.sessionId,iceServers:S.iceServers}),_e()&&await Te(),$=S.jwt,b.setDocTransport({wsUrl:S.url,token:V,resolveServerUrl:X}),await h.connect({app:i,functionName:r,args:o}),b.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 M=w;M?N(M):C=!0});b.onDisconnect(v);let S,_,I=!1,x=()=>{I||(I=!0,S?.(),_?.())};y.then(M=>{M.status!=="ready"||I||(S=pt(()=>w!==void 0))}),_=b.onPhase(M=>{let B=M?.name;(B==="paused"||B==="error")&&x()}),I&&_(),b.onDisconnect(x)}return b}}})}var Ar="https://api.urun.sh",Er="URUN_DEV";function pi(){if(typeof process>"u")return!1;let i=process.env?.[Er];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 hi(i,e={}){if(!i)throw new Q("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=J(e.baseUrl??Ar),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??pi())&&(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 Cr=3e4,Ir="stream:",Pt=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=`${Ir}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${Ir}${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 ${Cr}ms`)))},Cr);this._pendingRpc.set(s,{resolve:r,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:s,type:e,...t}))})}};function fi(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 Ot(n);return new Pt(n,s)}var mi='video/mp4; codecs="avc1.42E01E"';function gi(i,e){let t=e?.codec??mi,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 k(){try{for(;;){let{done:h,value:b}=await f.read();if(h){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{u.appendBuffer(b)}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(b)}else throw w}else throw w}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}k()}),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 vi(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 wi(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 wi(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 bi(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 Dr(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function yi(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function ki(i,e){let t=i.getTracks();if(t.length===1&&t[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function Lt(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,Lt(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(${Dr(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,Lt(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=yi(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(${Dr(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw d;Lt(o,d);continue}if(o.track=a,o.stream=ki(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}},Si=null;function _i(){return Si??=new Ve}var Pr="input",Ti=30;function Ri(i){let e=i.now??Date.now,t=i.field??Pr,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 k=Math.max(r-(m-l),0);c=setTimeout(()=>{c=null,u()},k),c.unref?.()};return{keyDown(m){let k=String(m).toLowerCase();n.has(k)||(n.add(k),f())},keyUp(m){let k=String(m).toLowerCase();n.delete(k)&&f()},setButtons(m){let k=Number.isFinite(m)?Number(m):0;k!==s&&(s=k,f())},movePointer(m,k){let h=Number.isFinite(m)?Number(m):0,b=Number.isFinite(k)?Number(k):0;h===0&&b===0||(o+=h,a+=b,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 Ai=1024,Ei=.92,Ci=262144,Ii=256e3,Ut=[.9,.8,.7,.6,.5],Lr=.8,Di=8;function Mt(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 Pi(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 xr(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 Ur(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 xr(s,r,n)}async function Li(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 Ut)if(!(d>=r)&&(o=await xt(i,n,s,t,d),o.size<=256e3))return Ur(`quality ${r} -> ${d}`,o.size),{blob:o,width:n,height:s}}let a=t==="image/jpeg"?Ut[Ut.length-1]:r;for(let d=0;d<Di;d++)if(n=Math.max(16,Math.round(n*Lr)),s=Math.max(16,Math.round(s*Lr)),o=await xt(i,n,s,t,a),o.size<=256e3)return Ur(`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 Ui(i,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:s}=e,o=await Pi(i);try{let a=Mt(o.width,o.height,t),d=await Li(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 xi(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 Mi(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function Wi(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=Mt(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 xr(d,s,o);return{bytes:new Uint8Array(await c.arrayBuffer()),type:s,width:a.width,height:a.height,source:"camera"}}var Oi=new Set(["w","a","s","d"]),re=(i,e)=>Math.min(e,Math.max(-e,i));function Ni(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();Oi.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 k=Math.exp(-m*1e3/n);d*=k,l*=k,c*=k},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{sn as ACTIVATION_COLD_BOOT_AFTER_MS,on as ACTIVATION_DEGRADED_AFTER_MS,it as ACTIVATION_HINT_PATH,nn as ACTIVATION_STILL_AFTER_MS,dt as ACTIVITY_DOM_EVENTS,Zt as ACTIVITY_FIELD,wn as ACTIVITY_STAMP_MIN_INTERVAL_MS,ne as ActivationMonitor,ui as App,Kr as BACKOFF_BASE_MS,zr as BACKOFF_MAX_ATTEMPTS,Gr as BACKOFF_MAX_MS,Hr 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,Ci as DATA_CHANNEL_MESSAGE_CEILING,yr as DEFAULT_DOC_SYNC_TIMEOUT_MS,Ar as DEFAULT_GATEWAY_URL,Mr as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Ei as DEFAULT_REFERENCE_JPEG_QUALITY,Ai as DEFAULT_REFERENCE_MAX_SIZE,jr as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Zr as DERIVED_LEG_SEP,P as DGRAM_HEADER_BYTES,nr as FOCUS_FIELD,yn as FOREGROUND_COALESCE_MS,le as FrameReassembler,gn as GENERATION_TICK_EMIT_INTERVAL_MS,vn as GENERATION_TICK_MAX_EXTRAPOLATION_MS,Ti as INPUT_PRESENCE_DEFAULT_HZ,Pr as INPUT_PRESENCE_FIELD,Z as InvalidDurationError,st as LEGACY_ACTIVATION_HINT_PATH,nt as PLATFORM_DOC_NAME,xe as PermanentLockedError,Ue as PinRequiresActiveTempError,oe as PresenceTracker,Wr as ProduceAckTimeoutError,Pe as RecordingNotFoundError,ee as RecordingsClient,O as RecordingsError,se as RecordingsUnauthorizedError,Se as RequestAbortError,Xe as RequestCancelledError,Ye as RequestDocSyncError,ke as RequestError,ze as RequestTimeoutError,Le as RetainNotTempError,De as RuntimeArtifactNotFoundError,z as RuntimeArtifactsClient,D as RuntimeArtifactsError,Ie as RuntimeArtifactsUnauthorizedError,rn as SIGNALING_PROTOCOL_VERSION,tt as STREAM_END,ge as Session,G as SessionAllocationError,ve as SessionDirectory,ye as SessionDirectoryError,Ge as SessionEndError,K as SessionEndUnavailableError,Nr as SessionFailedError,Qe as StreamDirectionConflict,he as TransportNegotiator,$r as TransportSessionMismatchError,fe as TransportSessionSignaling,Er as URUN_DEV_ENV,rr as USER_ACTIVITY_FIELD,bn as USER_ACTIVITY_MIN_INTERVAL_MS,er as VISIBILITY_FIELD,Ii as WIRE_MESSAGE_BUDGET,or as WT_CONTROL_FRAME_MAX,lr as WT_DATA_STREAM_VERSION,me as WebRtcSession,pe as WebTransportSession,de as WtControlDecoder,We as WtDataStreamParser,Qt as activationHintFrom,Mi as cameraCaptureAvailable,Wi as captureStillFromVideo,Yr as computeBackoffDelay,wt as consumeWtDataStreams,ct as createActivityTracker,Ni as createCameraWarp,hi as createClientToken,bi as createCreditsClient,Ri as createInputPresencePublisher,mn as createRecordingsClient,dn as createRuntimeArtifactsClient,fi as createStore,rt as decodeStreamEnvelope,tn as derivedLegName,en as derivedLegRole,Or as describeSessionFailure,Vr as describeSessionPhase,Jr as encodeStreamEnvelope,mt as encodeWtControlFrame,Mt as fitWithin,ot as isDurationString,Br as isPausedPhase,vi as isPendingRecording,Qr as isRetryableSessionError,qr as isWakingPhase,ht as mediaRecorderChunkSource,Ui as normalizeReferenceImage,hn as normalizeRetention,pt as observeLeaveConfirm,lt as observePageLifecycle,ut as observePageTeardown,ce as parseDgramHeader,Xr as prewake,xi as referenceImageErrorMessage,Re as releaseSessionBeacon,li as sessionDirectory,Fr as sessionFailureFromMediaError,_i as sharedCaptureController,gi 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=xn(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=hr(r.sdp??""),await e.setLocalDescription(r),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:r.sdp});let n=await t.createAnswer();n.sdp=hr(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([Mn],{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 xn(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var Wn=9e4,On="avc1.42E01F",Nn=60,Fn=3,$n=1e4;function qn(i){return Math.round(i*(Wn/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:On,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>=Nn;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,qn(e.timestamp),t,this.sink.maxDatagramSize()||ue,{lane:cr,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<$n),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=Fn){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 Bn(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),Bn(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 fr=250,jn=25,Hn=2e3,Vn=15e3,Gn=1e3,Kn=45e3,zn=500,mr=10,Yn=2,Qn=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(),zn)),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 ${fr}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Vn},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Gn))}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>=mr&&l<=0?p="downlink":d!==null&&c>=mr&&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 ${Yn} 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<Qn)){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>=Kn&&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<Hn),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<jn)&&(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(dr(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(()=>{})},fr)}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 gr=2500,vr=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Xn=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:vr,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??gr,"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:vr,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??gr,"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??Xn,"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 Jn=1e4,fe=class{constructor(e,t=Jn){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 Zn="video",me=class{constructor(e,t=Zn){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 wr(i){let e=i;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var ei="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 y of l.getVideoTracks())try{y.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??ei)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(y,A)=>i.dispatchQuicStreamData(y,A),onQuicLane:()=>i.markStreamDataLaneQuic(),onQuicLaneLost:y=>i.quicStreamDataLaneLost(y),onLaneError:y=>i.raiseQuicStreamDataError(y)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:y=>{d||t.onOverrideAudioTrack(y)}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>C(),onMediaTransportLost:y=>{d||(p(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(y),C())},onTransportChange:(y,A)=>{d||(y==="webrtc"&&(p(),C()),t.onTransportChange?.(y,A))}}),f=i.onWtOnlyLegDeath?.(y=>u.failCurrentWtLeg(y)),m=null,S=()=>{m!==null&&(clearInterval(m),m=null)},h=t.wtRetryBaseMs??2e3,b=t.wtRetryCapMs??3e4,w=null,T=0,C=()=>{if(d||w!==null||u.activeTransport==="webtransport")return;let y=Rt(h,T+2,b);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())})},y)},R=()=>{w!==null&&(clearTimeout(w),w=null)},W=async y=>{if(d||y.kind!=="webtransport")return;let A=t.pathHealthProbeMs??1e4;S();let N=!1;m=setInterval(()=>{if(d||u.activeTransport!=="webtransport")return;let L=wr(y);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 y.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 y=await u.connect();if(d){u.disconnect().catch(()=>{});return}await W(y)})().catch(y=>{if(S(),d){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",y);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",y),C();return}o?.proceed(`negotiation unavailable: ${y instanceof Error?y.message:String(y)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",y),C()}),{activeTransport:()=>u.activeTransport,watchDownlinkStall(y){u.watchDownlinkStall(y)},dispose(){d=!0,f?.(),S(),R(),p(),t.onOverrideAudioTrack?.(null),u.disconnect().catch(()=>{})}}}var ti=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 ri="rpc",ni="$presence",kr=3e4,yr=3e4,ii="rpc-resp";function si(i){return`${ii}:${i}`}function At(){return Ae()}function oi(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 ai(i,e,t,r,n,s,o,a,d,l){let c=[],p=null,u=!1,f=null,m=!1,S,h,b=new Promise((g,F)=>{S=g,h=F});b.catch(()=>{});let w=o(),T=null,C=null,R=null,W=null,y=null,A=null,N=!0,H=()=>{R&&(clearTimeout(R),R=null),W&&(W(),W=null)},L=()=>{y&&(clearTimeout(y),y=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}=oi(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||y)&&(y=setTimeout(()=>{y=null,!(u||U)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(yr/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).`)},yr))})}};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:b,start:x}}function Sr(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 di(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=Sr(s);d&&(a.rt=d);let l=Sr(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=di(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 or(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 zt;_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=Gt(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(ni).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 Ht({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 be,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 Yt(e,this._sessionId,ti.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Qt(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(Kt({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(ri),a=si(e);return ai(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),s??kr)}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 _r(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 ci(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||ci(n.actor,e)?null:n}function Tr(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 Rr=new Set(["paused","acquiring","live"]),li=new Set(["24h","keep"]);function Ar(i){if(typeof i!="string"||i.length===0)return null;let e=new Date(i);return Number.isFinite(e.getTime())?e:null}function ui(i){if(typeof i?.id!="string"||i.id.length===0)throw new ye("[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"||!Rr.has(i.state))throw new ye(`[urun] session ${i.id} reported an unrecognized state ${JSON.stringify(i.state)} \u2014 this @urun-sh/core build knows only ${[...Rr].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:Ar(i.created_at),lastActiveAt:Ar(i.last_active_at),archived:i.archived===!0,preview:typeof i.preview=="string"&&i.preview.length>0?i.preview:null,recordingsExpired:e,retention:li.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(ui),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})}};function Er(i,e,t){let r=qe(t);Tr(i,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}var pi=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function hi(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 fi(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(!(pi.has(r)||typeof r!="string"))return(n,s)=>{let o=n??{},a=_r({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 be,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}),b=new ge(p,S,h,Ct(m),ie(m),{activity:s?.activity}),w,T=!1,C=!1,R,W,y=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)};b.setEndHandler(async()=>{let v=w?{status:"ready",handle:w}:await y;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}))}),b.setCancelHandler(async()=>{let v=w?{status:"ready",handle:w}:await y;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||Er(a,j.sessionId,u),b.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||Er(a,g.sessionId,u),b.setSessionId(g.sessionId),b.setArtifactsAuth(ie({...m,baseUrl:g.baseUrl})),h.setEndsAt(g.endsAt),h.seedRegion(Vt(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&&b.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,b.setDocTransport({wsUrl:k.url,token:V,resolveServerUrl:X}),await h.connect({app:i,functionName:r,args:o}),b.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});b.onDisconnect(v);let k,_,I=!1,M=()=>{I||(I=!0,k?.(),_?.())};y.then(x=>{x.status!=="ready"||I||(k=pt(()=>w!==void 0))}),_=b.onPhase(x=>{let B=x?.name;(B==="paused"||B==="error")&&M()}),I&&_(),b.onDisconnect(M)}return b}}})}var Cr="https://api.urun.sh",Ir="URUN_DEV";function mi(){if(typeof process>"u")return!1;let i=process.env?.[Ir];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 gi(i,e={}){if(!i)throw new Q("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=J(e.baseUrl??Cr),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??mi())&&(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 Dr=3e4,Pr="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=`${Pr}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${Pr}${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 ${Dr}ms`)))},Dr);this._pendingRpc.set(s,{resolve:r,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:s,type:e,...t}))})}};function vi(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 wi='video/mp4; codecs="avc1.42E01E"';function bi(i,e){let t=e?.codec??wi,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:b}=await f.read();if(h){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{u.appendBuffer(b)}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(b)}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 yi(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 Si(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 Si(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 ki(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 Lr(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function _i(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function Ti(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(${Lr(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=_i(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(${Lr(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw d;Ut(o,d);continue}if(o.track=a,o.stream=Ti(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}},Ri=null;function Ai(){return Ri??=new Ve}var Ur="input",Ei=30;function Ci(i){let e=i.now??Date.now,t=i.field??Ur,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,b=Number.isFinite(S)?Number(S):0;h===0&&b===0||(o+=h,a+=b,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 Ii=1024,Di=.92,Pi=262144,Li=256e3,Mt=[.9,.8,.7,.6,.5],Mr=.8,Ui=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 Mi(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 Wr(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 xr(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 Wr(s,r,n)}async function xi(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 xr(`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<Ui;d++)if(n=Math.max(16,Math.round(n*Mr)),s=Math.max(16,Math.round(s*Mr)),o=await xt(i,n,s,t,a),o.size<=256e3)return xr(`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 Wi(i,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:s}=e,o=await Mi(i);try{let a=Wt(o.width,o.height,t),d=await xi(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 Oi(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 Ni(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function Fi(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 Wr(d,s,o);return{bytes:new Uint8Array(await c.arrayBuffer()),type:s,width:a.width,height:a.height,source:"camera"}}var $i=new Set(["w","a","s","d"]),re=(i,e)=>Math.min(e,Math.max(-e,i));function qi(i={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond: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();$i.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{an as ACTIVATION_COLD_BOOT_AFTER_MS,dn as ACTIVATION_DEGRADED_AFTER_MS,it as ACTIVATION_HINT_PATH,on as ACTIVATION_STILL_AFTER_MS,dt as ACTIVITY_DOM_EVENTS,er as ACTIVITY_FIELD,yn as ACTIVITY_STAMP_MIN_INTERVAL_MS,ne as ActivationMonitor,fi as App,zr as BACKOFF_BASE_MS,Qr as BACKOFF_MAX_ATTEMPTS,Yr as BACKOFF_MAX_MS,Gr 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,Pi as DATA_CHANNEL_MESSAGE_CEILING,kr as DEFAULT_DOC_SYNC_TIMEOUT_MS,Cr as DEFAULT_GATEWAY_URL,Or as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Di as DEFAULT_REFERENCE_JPEG_QUALITY,Ii as DEFAULT_REFERENCE_MAX_SIZE,Vr as DEFAULT_WHEN_LIVE_TIMEOUT_MS,tn as DERIVED_LEG_SEP,P as DGRAM_HEADER_BYTES,ir as FOCUS_FIELD,kn as FOREGROUND_COALESCE_MS,le as FrameReassembler,wn as GENERATION_TICK_EMIT_INTERVAL_MS,bn as GENERATION_TICK_MAX_EXTRAPOLATION_MS,Ei as INPUT_PRESENCE_DEFAULT_HZ,Ur 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,Nr 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,sn as SIGNALING_PROTOCOL_VERSION,tt as STREAM_END,ge as Session,K as SessionAllocationError,ve as SessionDirectory,ye as SessionDirectoryError,Ke as SessionEndError,G as SessionEndUnavailableError,$r as SessionFailedError,Qe as StreamDirectionConflict,he as TransportNegotiator,Br as TransportSessionMismatchError,fe as TransportSessionSignaling,Ir as URUN_DEV_ENV,nr as USER_ACTIVITY_FIELD,Sn as USER_ACTIVITY_MIN_INTERVAL_MS,tr as VISIBILITY_FIELD,Li as WIRE_MESSAGE_BUDGET,ar as WT_CONTROL_FRAME_MAX,ur as WT_DATA_STREAM_VERSION,me as WebRtcSession,pe as WebTransportSession,de as WtControlDecoder,We as WtDataStreamParser,Xt as activationHintFrom,Ni as cameraCaptureAvailable,Fi as captureStillFromVideo,Xr as computeBackoffDelay,wt as consumeWtDataStreams,ct as createActivityTracker,qi as createCameraWarp,gi as createClientToken,ki as createCreditsClient,Ci as createInputPresencePublisher,vn as createRecordingsClient,ln as createRuntimeArtifactsClient,vi as createStore,rt as decodeStreamEnvelope,nn as derivedLegName,rn as derivedLegRole,Fr as describeSessionFailure,Kr as describeSessionPhase,en as encodeStreamEnvelope,mt as encodeWtControlFrame,Wt as fitWithin,ot as isDurationString,Hr as isPausedPhase,yi as isPendingRecording,Jr as isRetryableSessionError,jr as isWakingPhase,ht as mediaRecorderChunkSource,Wi as normalizeReferenceImage,mn as normalizeRetention,pt as observeLeaveConfirm,lt as observePageLifecycle,ut as observePageTeardown,ce as parseDgramHeader,Zr as prewake,Oi as referenceImageErrorMessage,Re as releaseSessionBeacon,hi as sessionDirectory,qr as sessionFailureFromMediaError,Ai as sharedCaptureController,bi as videoStream,at as watchGenerationTick,Je as whenLive,gt as writeDgramHeader};
|