@urun-sh/core 0.3.1 → 0.3.2
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/{chunk-CVMFNMRA.mjs → chunk-PWRSYBG2.mjs} +2 -2
- package/dist/{chunk-JQPCE4OM.mjs → chunk-TYT5X4G2.mjs} +2 -2
- package/dist/index.browser.d.mts +2 -2
- package/dist/index.browser.d.ts +2 -2
- package/dist/index.browser.js +2 -2
- package/dist/index.browser.mjs +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -5
- 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.browser.mjs +1 -1
- package/dist/internal.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.mjs +1 -1
- package/dist/{stream-data-BJoG7tYI.d.mts → stream-data-Bl4UHVAa.d.mts} +2 -0
- package/dist/{stream-data-BJoG7tYI.d.ts → stream-data-Bl4UHVAa.d.ts} +2 -0
- package/package.json +1 -1
package/dist/index.browser.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as Ut,A as Er,B as Rr,C as V,D as Rt,E as Ve,F as Ct,G as It,H as Dt,I as Cr,J as we,M as be,N as ye,O as He,P as Ir,Q as Ge,S as Pt,U as Dr,V as Pr,W as Ur,X as xr,Y as ke,_ as _e,a as At,aa as xt,b as me,ba as Mt,c as Z,ca as Lt,d as fr,e as he,f as Ne,g as Fe,h as qe,i as mr,j as hr,k as ge,l as $e,m as gr,n as vr,o as wr,p as br,q as ve,r as Et,s as yr,t as Be,u as kr,v as je,w as _r,x as Sr,y as Tr,z as Ar}from"./chunk-JQPCE4OM.mjs";var Mr=15e3,Lr=45e3,Or=12e4,Ke="platform",ze="activation",Ye="desired.activation";function Ot(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 Wr=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],ee=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==="ended"||t?.name==="expired")&&this.dispose()}),this._stopped&&(this._offPhase(),this._offPhase=null)}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=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 Wr){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},o=Ot(this._options.hint());o!==void 0&&(n.hint=o),e.lastEvent=n;for(let s of Array.from(this._handlers))s(n)}};var E=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)}},Se=class extends E{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Te=class extends E{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function te(i){return{baseUrl:i.baseUrl,fallbackUrls:i.fallbackUrls,orgId:i.orgId,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}function Nr(i){return new $(i)}var $=class{_options;constructor(e){this._options=e}async list(e){let r=Nt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new E("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(Wt)}async getDownloadUrl(e,t){let r=Nt(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!qr(n))throw new E("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Wt(r.artifact),downloadUrl:n}}async _request(e,t){let r=Rt(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let o of r)try{return await this._requestFromBase(o,e,t)}catch(s){if(n=s instanceof Error?s:new Error(String(s)),n instanceof E&&$r(n.status))throw n}throw n??new E("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${V(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,o=await this._resolveToken(),s=await fetch(n,{method:"GET",headers:this._headers(o)});if(s.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,s=await fetch(n,{method:"GET",headers:this._headers(o)}))}if(!s.ok){let{code:a,message:c}=await this._readError(s,e);throw Br(s.status,a,c)}try{return await s.json()}catch(a){throw new E(`[urun] runtime artifacts: invalid JSON response from ${V(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=V(t);try{let o=(await e.json()).error;if(o&&typeof o=="object"){let{code:s,message:a}=o;return{code:typeof s=="string"&&s.length>0?s:`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 Wt(i){if(!i||typeof i!="object")throw new E("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=i,t=L(e,"artifact_id")||L(e,"id"),r=L(e,"filename"),n=L(e,"kind"),o=L(e,"status")||"ready",s=Fr(e,"size_bytes"),a=L(e,"sha256");if(!t||!r||!n||s==null||!a)throw new E("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:L(e,"content_type")||"application/octet-stream",sizeBytes:s,sha256:a,status:o,createdAt:L(e,"created_at"),expiresAt:L(e,"expires_at")}}function L(i,e){let t=i[e];return typeof t=="string"&&t.length>0?t:void 0}function Fr(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function qr(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function $r(i){return i===401||i===403}function Br(i,e,t){return i===401?new Se(t,e):i===404?new Te(t,e):new E(t,i,e)}function Nt(i){if(!i||typeof i!="object"||Array.isArray(i))throw new E("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var P=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)}},re=class extends P{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Ae=class extends P{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Ee=class extends P{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)}},Re=class extends P{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)}},Ce=class extends P{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)}},H=class extends P{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 Qe(i){return/^(\d+[smhdw])+$/.test(i)}function jr(i){if(i==="pin")return{action:"pin"};if(Qe(i))return{action:"retain",duration:i};throw new H(`[urun] recordings: "${i}" is not a duration or "pin"`)}function Vr(i,e,t){let r=t||e||`HTTP ${i}`;if(i===401)return new re(r,e??"unauthorized");if(i===404)return new Ae(r,e??"not_found");if(i===400)return new H(r,e??"bad_request",400);if(i===409)switch(e){case"retain_not_temp":return new Ee(r,e);case"pin_requires_active_temp":return new Re(r,e);case"permanent_locked":return new Ce(r,e)}return new P(r,{status:i,code:e??`http_${i}`})}var G=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(!Qe(t))throw new H(`[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 P("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),o=await this._resolveToken(),s=await this._fetch(n,e,o,r.body);if(s.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,s=await this._fetch(n,e,o,r.body))}if(!s.ok){let{code:a,message:c}=await this._readError(s);throw Vr(s.status,a,c)}return this._readJson(s)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,s])=>`${encodeURIComponent(o)}=${encodeURIComponent(s)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let o={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(o["X-Auth-Provider"]=this._options.authProvider);let s={method:t,headers:o};return n!==void 0&&(o["Content-Type"]="application/json",s.body=JSON.stringify(n)),fetch(e,s)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new re("[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:o}=r;return{code:typeof n=="string"?n:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Hr(i){return new G(i)}var Gr=1e3,Kr=12e3;function Xe(i,e,t={}){let r=null,n=0,o=0,s=null,a=-1,c=()=>{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"),S=i.get("desired.billing.updatedAtMs");return{seconds:h,epoch:typeof b=="number"&&Number.isFinite(b)?b:0,updatedAtMs:typeof S=="number"&&Number.isFinite(S)?S:null}},u=()=>{if(r===null)return null;let h=Math.min(Math.max(0,Date.now()-n),o);return r+h/1e3},d=()=>{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},l=()=>{let h=u();if(h===null)return;let b=Math.floor(h);if(b<=a)return;a=b;let S={seconds:b},A=d();A!==null&&(S.estimatedCredits=b*A),e(S)},p=h=>{n=Date.now();let b=h===null?0:Math.max(0,n-h);o=Math.max(0,12e3-b)},f=()=>{let h=c();if(h!==null){if(s!==null&&h.epoch!==s){s=h.epoch,r=h.seconds,a=-1,p(h.updatedAtMs),l();return}r!==null&&h.seconds<=r||(s=h.epoch,r=h.seconds,p(h.updatedAtMs),l())}};f();let m=i.on("change",f),w=setInterval(l,1e3);return w.unref?.(),()=>{clearInterval(w),m()}}var Ft="activity",qt="visibility",zr=15e3,Je=["pointerdown","pointermove","keydown","wheel","touchstart"];function Ze(i){let e=i.now??Date.now,t=i.windowTarget!==void 0?i.windowTarget:typeof window<"u"?window:null,r=i.documentTarget!==void 0?i.documentTarget:typeof document<"u"?document:null,n=!1,o,s=()=>{if(n)return;let l=e();if(!(o!==void 0&&l-o<15e3)){o=l;try{i.awareness.setLocalStateField(Ft,{at:l})}catch{}}},a=()=>{if(!(n||!r||r.visibilityState===void 0))try{i.awareness.setLocalStateField(qt,r.visibilityState)}catch{}},c=()=>s(),u=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&s()};if(t)for(let l of Je)t.addEventListener(l,c,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",u);let d=null;return i.isProducing&&(d=setInterval(()=>{if(!n)try{i.isProducing?.()&&s()}catch{}},15e3),d.unref?.()),s(),a(),{touch:s,dispose(){if(!n){if(n=!0,t)for(let l of Je)t.removeEventListener(l,c,{capture:!0});r&&r.removeEventListener("visibilitychange",u),d&&(clearInterval(d),d=null)}}}}var Bt="user_activity",jt="focus",Yr=3e4;function $t(i){switch(i){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var ne=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($t(e.state));let t=e.on("stateChange",n=>{this._setState($t(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(jt,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(Bt,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 Qr=250;function et(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 tt(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 rt(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 Vt="video/mp4";function nt(i,e={}){let t=e.timesliceMs??1e3,r=null,n=null,o=!1,s=(a,c,u)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)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 l=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(Vt)?Vt:void 0),p=new MediaStream([a]),f=new d(p,l?{mimeType:l}:void 0);r=f;let m=Promise.resolve();f.ondataavailable=w=>{let h=w.data;o||!h||h.size===0||(m=m.then(async()=>{let b=new Uint8Array(await h.arrayBuffer());o||c(b)}))},f.onstop=()=>{m.then(()=>{o||u()})},f.onerror=()=>{m.then(()=>{o||u()})},f.start(t)};return{start(a,c){if(r||o)return;let u=i.track();if(u){s(u,a,c);return}n=i.onTrack(d=>{!d||r||o||(n?.(),n=null,s(d,a,c))})},stop(){if(o)return;o=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Xr(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 Ht(i,e){let t=null,r=!1,n=!1,o=new ReadableStream({pull(s){r||(r=!0,t=i(e),t.start(a=>{if(!n)try{s.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{s.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Xr(o)}import{encode as Jr,decode as Zr}from"@msgpack/msgpack";var Gt=65536;function st(i){let e=Jr(i),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var ie=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>Gt)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(Zr(n))}return t}},R=12,it=1,en=0,Ie=1,Kt=2;function se(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&it)===it,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function ot(i){let e=new Uint8Array(R),t=new DataView(e.buffer);return t.setUint32(0,i.groupId,!0),t.setUint32(4,i.frameSeq,!0),t.setUint8(8,i.keyframe?it:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??en),e}var tn=100,oe=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??tn}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<R)return;let t=se(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,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(R),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++)}}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((s,a)=>s+a.byteLength,0),n=new Uint8Array(r),o=0;for(let s of t.chunks)n.set(s,o),o+=s.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 rn=/^avc[13]\.[0-9a-fA-F]{6}$/;function nn(i){return rn.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 at(i,e){let t=nn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var zt=1,De=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!==zt)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=Ge(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),n===He&&(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 ct(i,e){let t=i.getReader();for(;;){let{value:r,done:n}=await t.read();if(n)return;r&&sn(r,e).catch(o=>{e.onLaneError(o instanceof Error?o:new Error(String(o)))})}}async function sn(i,e){let t=i.getReader(),r=new De;try{for(;;){let{value:n,done:o}=await t.read();if(o)break;if(!(!n||n.byteLength===0))for(let{name:s,payload:a}of r.push(n))e.onData(s,a)}r.finish()}catch(n){try{await t.cancel?.(n)}catch{}throw n}}var dt=40,lt=48e3,on=64,ut=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<R)return;let t=se(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,t.frameSeq<=this.newestDelivered||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>on;){let a=1/0;for(let c of this.pending.keys())c<a&&(a=c);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=r.fragCount||r.chunks[t.fragIndex]||(r.chunks[t.fragIndex]=e.subarray(R),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,c)=>a+(c?.byteLength??0),0),o=new Uint8Array(n),s=0;for(let a of r.chunks)o.set(a,s),s+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:r.timestamp,data:o})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},an=3,cn=1e4,Pe=class{constructor(e,t){this.config=e;this.seam=t;let r=this.seam.jitterBufferTargetMs??dt;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${dt}ms`),r=dt),this.targetS=Math.max(0,r)/1e3}config;seam;decoder=null;decoderErrorsAt=[];ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;deadCb=null;assembler=new ut(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}}onDead(e){this.deadCb=e}stop(){if(!this.stopped){this.stopped=!0,this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ctx?.close().catch(()=>{})}}initDecoder(e){this.decoder=new e({output:t=>this.schedule(t),error:t=>this.onDecoderError(t)}),this.decoder.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels})}decodeFrame(e){let t=globalThis.EncodedAudioChunk;!this.decoder||typeof t!="function"||this.stopped||this.decoder.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/lt)),data:e.data}))}schedule(e){let t=this.ctx,r=this.dest;if(!t||!r||this.stopped){e.close();return}if(!this.trackSurfaced){this.trackSurfaced=!0,t.resume?.().catch(()=>{});let d=r.stream.getAudioTracks()[0];d&&this.seam.onTrack(d)}let n=e.numberOfFrames,o=Math.max(1,e.numberOfChannels),s=t.createBuffer(o,n,e.sampleRate);for(let d=0;d<o;d++){let l=new Float32Array(n);e.copyTo(l,{planeIndex:d,format:"f32-planar"}),s.copyToChannel(l,d)}let a=n/e.sampleRate;e.close();let c=t.createBufferSource();c.buffer=s,c.connect(r);let u=Math.max(this.playhead,t.currentTime+this.targetS);c.start(u),this.playhead=u+a}onDecoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(n=>t-n<cn),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=an){let n=`audio decoder: ${e.message}`;console.warn(`[urun] WT audio lane dead (${n}) \u2014 audio reverts to the WebRTC track`),this.stop(),this.deadCb?.(n);return}console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=globalThis.AudioDecoder;typeof r=="function"&&this.initDecoder(r)}};var ae=1200,dn=3,un=1e4;function ln(i){return Math.round(i*(lt/1e6))%2**32>>>0}function pt(i,e,t,r,n){let o=r-R;if(o<=0)return null;let s=Math.max(1,Math.ceil(t.byteLength/o));if(s>255)return null;let a=[];for(let c=0;c<s;c++){let u=t.subarray(c*o,Math.min((c+1)*o,t.byteLength)),d=ot({groupId:e>>>0,frameSeq:i>>>0,keyframe:n?.keyframe??!0,fragIndex:c,fragCount:s,lane:n?.lane??Ie}),l=new Uint8Array(R+u.byteLength);l.set(d,0),l.set(u,R),a.push(l)}return a}var Ue=class{constructor(e){this.sink=e}sink;encoder=null;encoderConfig=null;encoderErrorsAt=[];frameSeq=0;stopped=!1;deadCb=null;generation=0;cancelCapture=null;nodeBridge=null;onDead(e){this.deadCb=e}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}let n;if(pn(e)){let c=e,u=c.context.createMediaStreamDestination();c.connect(u),this.nodeBridge={node:c,dest:u};let d=u.stream.getAudioTracks()[0];if(!d){this.die("AudioNode bridge produced no audio track");return}n=d}else n=e;let o=++this.generation,s=new r({track:n}).readable.getReader(),a=!1;this.cancelCapture=()=>{a=!0,s.cancel().catch(()=>{})},(async()=>{for(;!a&&!this.stopped&&o===this.generation;){let{value:c,done:u}=await s.read();if(u)break;if(c){if(a||this.stopped||o!==this.generation){c.close();break}this.encodeAudioData(c)}}})().catch(c=>{!a&&!this.stopped&&o===this.generation&&this.die(`capture: ${c instanceof Error?c.message:String(c)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){if(this.cancelCapture?.(),this.cancelCapture=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}this.generation++}encodeAudioData(e){if(!this.encoder){let r=globalThis.AudioEncoder;if(typeof r!="function"){e.close(),this.die("AudioEncoder is not available");return}this.encoderConfig={sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels};try{this.initEncoder(r)}catch(n){e.close(),this.encoder=null,this.die(`encoder configure: ${n instanceof Error?n.message:String(n)}`);return}}let t=this.encoder;if(!t){e.close();return}try{t.encode(e)}catch(r){this.onEncoderError(r instanceof Error?r:new Error(String(r)))}e.close()}initEncoder(e){let t=this.encoderConfig;this.encoder=new e({output:r=>this.sendFrame(r),error:r=>this.onEncoderError(r)}),this.encoder.configure({codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3})}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=pt(this.frameSeq,ln(e.timestamp),t,this.sink.maxDatagramSize()||ae);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}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(n=>t-n<un),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=dn){this.die(`audio encoder: ${e.message}`);return}console.warn("[urun] WT mic uplink encoder error \u2014 re-initializing the encoder:",e.message);try{this.encoder?.close()}catch{}this.encoder=null;let r=globalThis.AudioEncoder;if(!(typeof r!="function"||!this.encoderConfig))try{this.initEncoder(r)}catch(n){this.die(`encoder re-init: ${n instanceof Error?n.message:String(n)}`)}}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 pn(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var fn=9e4,mn="avc1.42E01F",hn=60,gn=3,vn=1e4;function wn(i){return Math.round(i*(fn/1e6))%2**32>>>0}var xe=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;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,o=new r({track:e}).readable.getReader(),s=!1;this.cancelCapture=()=>{s=!0,o.cancel().catch(()=>{})},(async()=>{for(;!s&&!this.stopped&&n===this.generation;){let{value:a,done:c}=await o.read();if(c)break;if(a){if(s||this.stopped||n!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!s&&!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 o=globalThis.VideoEncoder;if(typeof o!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new o({output:s=>this.sendFrame(s),error:s=>this.onEncoderError(s)})),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(s){e.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${s instanceof Error?s.message:String(s)}`);return}}let n=this.keyframeWanted||this.framesSinceKeyframe>=hn;this.keyframeWanted=!1,this.framesSinceKeyframe=n?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:n})}catch(o){this.onEncoderError(o instanceof Error?o:new Error(String(o)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=pt(this.frameSeq,wn(e.timestamp),t,this.sink.maxDatagramSize()||ae,{lane:Kt,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<vn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=gn){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 Me=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 o=this.streams.get(e);if(!o){let a=await this.transport.openUniStream(),c=new Uint8Array(2+r.byteLength);c[0]=1,c[1]=r.byteLength,c.set(r,2),await a.write(c),o={writer:a},this.streams.set(e,o)}let s=new Uint8Array(4+t.byteLength);new DataView(s.buffer).setUint32(0,t.byteLength,!0),s.set(t,4),await o.writer.write(s),bn(t)&&(this.streams.delete(e),await o.writer.close().catch(()=>{}))}catch(o){throw this.die(o instanceof Error?o.message:String(o)),o}});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 yn=250,kn=3,_n=1e4,ft=2500,ce=class{constructor(e,t,r,n,o,s,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=n;this.audioUplink=o;this.videoUplink=s;this.dataUplink=a;this.firstMedia=new Promise((c,u)=>{this.firstFrameResolve=c,this.firstFrameReject=u}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorsAt=[];writer;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;reassembler=new oe({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;firstFrameOutput=!1;hasVideoLane=!1;firstDecodeTimer=null;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&&at(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(d=>({algorithm:"sha-256",value:Uint8Array.from(atob(d),l=>l.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 o=n.readable.getReader(),s=new ie,a=[],c=await this.readControl(o,s,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");if(r&&(at(c.codec,"hello-ack"),this.initDecoder(c.codec,c.width,c.height)),this.offer.audio&&this.audioLane){let d=new Pe(this.offer.audio,this.audioLane);d.onDead(()=>{this.audioPlayout=null});try{d.start(),this.audioPlayout=d}catch(l){console.warn(`[urun] WT audio lane failed to start (${l instanceof Error?l.message:String(l)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),d.stop()}}let u=()=>{let d=this.wt.datagrams.writable;if(!d)throw new Error("WebTransport datagrams are not writable in this environment");let l=d.getWriter();return{send:p=>{l.write(p).catch(()=>{})},maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??ae}};if(this.offer.audioUp===!0&&this.audioUplink)try{let d=new Ue(u());d.onDead(l=>{this.audioUplinkLane=null,this.audioUplink.onUplinkLost(l)}),this.audioUplinkLane=d,this.audioUplink.onUplink(d)}catch(d){let l=d instanceof Error?d.message:String(d);console.warn(`[urun] WT mic uplink failed to engage (${l}) \u2014 keeping the WT session; the mic stays on the WebRTC produce path`),this.audioUplink.onUplinkLost(l)}if(this.offer.videoUp===!0&&this.videoUplink)try{let d=new xe(u());d.onDead(l=>{this.videoUplinkLane=null,this.videoUplink.onUplinkLost(l)}),this.videoUplinkLane=d,this.videoUplink.onUplink(d)}catch(d){let l=d instanceof Error?d.message:String(d);console.warn(`[urun] WT video uplink failed to engage (${l}) \u2014 keeping the WT session; the camera stays on the WebRTC produce path`),this.videoUplink.onUplinkLost(l)}if(this.offer.dataUp===!0&&this.dataUplink)try{let d=this.wt.createUnidirectionalStream?.bind(this.wt);if(!d)throw new Error("WebTransport uni streams are not creatable in this environment");let l=new Me({openUniStream:async()=>(await d()).getWriter()});l.onDead(p=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(p)}),this.dataUplinkSender=l,this.dataUplink.onUplink(l)}catch(d){let l=d instanceof Error?d.message:String(d);console.warn(`[urun] WT data uplink failed to engage (${l}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(l)}this.controlLoop(o,s,a).catch(d=>this.die(`control loop: ${d}`)),this.datagramLoop().catch(d=>this.die(`datagram loop: ${d}`)),this.feedbackLoop(),this.wt.closed.then(()=>this.die("connection closed")).catch(d=>this.die(`connection error: ${d}`))}async stop(){this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),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");try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}dropUplinks(e){let t=this.audioUplinkLane;t&&(this.audioUplinkLane=null,t.stop(),this.audioUplink?.onUplinkLost(e));let r=this.videoUplinkLane;r&&(this.videoUplinkLane=null,r.stop(),this.videoUplink?.onUplinkLost(e));let n=this.dataUplinkSender;n&&(this.dataUplinkSender=null,n.stop(e),this.dataUplink?.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,ct(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 o=this.canvas.getContext("2d");if(!o)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r},this.decoder=new n({output:s=>{this.firstFrameOutput=!0,this.firstDecodeTimer&&(clearTimeout(this.firstDecodeTimer),this.firstDecodeTimer=null),this.canvas.width=s.displayWidth,this.canvas.height=s.displayHeight,o.drawImage(s,0,0),s.close()},error:s=>this.onDecoderError(s)}),this.decoder.configure({codec:e,...t>0&&r>0?{codedWidth:t,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"})}onDecoderError(e){if(this.stopped||this.deadFired)return;let t=performance.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(n=>t-n<_n),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=kn){this.die(`decoder: ${e.message}`);return}console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=this.decoderConfig;if(!r){this.die(`decoder: ${e.message} (no config to re-init from)`);return}try{this.initDecoder(r.codec,r.width,r.height)}catch(n){this.die(`decoder re-init: ${n instanceof Error?n.message:String(n)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}armFirstDecodeDeadline(){if(this.firstDecodeTimer||this.firstFrameOutput||this.stopped||this.deadFired)return;let e=setTimeout(()=>{this.firstDecodeTimer=null,!(this.firstFrameOutput||this.stopped||this.deadFired)&&(console.error(`[urun] webtransport: media datagrams arriving but NO frame decoded within ${ft}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${ft}ms`))},ft);e.unref?.(),this.firstDecodeTimer=e}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>=R&&t[11]===Ie){this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;this.armFirstDecodeDeadline();let n=performance.now();if(this.lastArrivalTs>0){let o=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(o-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=n,this.reassembler.push(t)}}decodeFrame(e,t,r){let n=globalThis.EncodedVideoChunk;!this.decoder||typeof n!="function"||(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){await this.writer.write(st(e))}async readControl(e,t,r=[]){for(;;){let n=r.shift();if(n)return n;let{value:o,done:s}=await e.read();if(s)return null;o&&r.push(...t.push(o))}}async controlLoop(e,t,r){for(;!this.stopped;){let n=await this.readControl(e,t,r);if(!n)break;n.t==="ping"&&this.sendControl({t:"pong",ts:n.ts}).catch(()=>{}),n.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(),o=n.delivered+n.abandoned;this.lastStats={recvBps:r>0?n.bytes*8/r:0,lossPct:o>0?100*n.abandoned/o:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},yn)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks(e);try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var Yt=2500,Qt=["av01.0.08M.08","avc1.42E01F","avc1.640028"],de=class{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;get activeTransport(){return this.session?.kind??null}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,o={webtransport:t&&r&&n,webcodecs:r,codecs:Qt,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&&r&&n&&this.opts.audioUplink!==void 0&&typeof e.AudioEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="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:o});let s=o.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,c=s&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(c||this.opts.webRtcDial?.proceed(s?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),o.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),s){let u=null;try{return u=this.createWebTransportSession(),await Xt(u.start(),this.opts.quicDeadlineMs??Yt,"quic connect deadline"),this.engageQuicDataLane(u,o.wtData===!0),this.session=u,c&&(this.wtOnlyLeg=!0,this.opts.webRtcDial?.skip("fully-granted WT leg established")),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(d){if(u?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let l=String(d instanceof Error?d.message:d);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${l}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(l),d}console.warn("[urun] webtransport failed, falling back to webrtc:",d),this.opts.webRtcDial?.proceed(`wt failed: ${String(d instanceof Error?d.message:d)}`),this.notifyEstablished("webrtc",String(d instanceof Error?d.message:d))}}if(this.opts.allowWebRtcFallback===!1){let u=s?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${u} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(u),new Error(`[urun] WT required but unavailable: ${u}`)}return this.session=await this.startWebRtc(),s||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.quicDataLane=!1,await this.session?.stop(),this.session=null}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,o=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",s=this.opts.audioUplink!==void 0&&typeof e.AudioEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",a=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",c=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:Qt,wtData:n,wtAudio:o,wtAudioUp:s,wtVideoUp:a,wtDataUp:c}}),!this.offer.webtransport)return null;let u=this.createWebTransportSession();try{await Xt(u.start(),this.opts.quicDeadlineMs??Yt,"quic connect deadline")}catch(d){throw u.stop().catch(()=>{}),d}if(this.session!==r)return u.stop().catch(()=>{}),null;try{this.engageQuicDataLane(u,n)}catch(d){throw u.stop().catch(()=>{}),d}this.session=u;{let d=this.offer.webtransport;d&&(this.opts.audioLane===void 0||d.audio!==void 0)&&(this.opts.audioUplink===void 0||d.audioUp===!0)&&(this.opts.videoUplink===void 0||d.videoUp===!0)&&(this.opts.dataLane===void 0||d.data===!0)&&(this.opts.dataUplink===void 0||d.dataUp===!0)&&(this.wtOnlyLeg=!0,this.opts.webRtcDial?.skip("fully-granted WT leg re-established"))}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),u}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,o)=>r.onData(n,o),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 ce(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}async startWebRtc(){let e=this.opts.createWebRtcSession();return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}armFailover(){let e=this.session;e.onDead(t=>{if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; retrying WT`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.opts.onWtRequiredOutage?.(t);return}this.wtOnlyLeg&&(this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(`failover: ${t}`)),console.warn("[urun] quic died mid-session, failing over to webrtc:",t),this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),(async()=>{try{this.session=await this.startWebRtc(),this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(r){this.session=null,console.error("[urun] failover to webrtc also failed:",r)}})()})}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function Xt(i,e,t){return new Promise((r,n)=>{let o=setTimeout(()=>n(new Error(t)),e);i.then(s=>{clearTimeout(o),r(s)},s=>{clearTimeout(o),n(s)})})}var Sn=1e4,ue=class{constructor(e,t=Sn){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=ye();return new Promise((n,o)=>{let s=setTimeout(()=>{a(),o(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(s),a(),c.error){o(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:u,requestId:d,...l}=c;n(l)});this.carrier.sendSignal({type:e,requestId:r,...t})||(clearTimeout(s),a(),o(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 Tn="video",le=class{constructor(e,t=Tn){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))}};var An="video";function Jt(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 s=i.holdWebRtcDial?.(),a=n.createElement("canvas"),c=!1,u=null,d=!1,l=()=>{if(u){for(let y of u.getVideoTracks())try{y.stop()}catch{}u=null}d&&(d=!1,t.onOverrideTrack(null))},p=new de(new ue(i),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new le(i,t.streamName??An)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(y,T)=>i.dispatchQuicStreamData(y,T),onQuicLane:()=>i.markStreamDataLaneQuic(),onQuicLaneLost:y=>i.quicStreamDataLaneLost(y),onLaneError:y=>i.raiseQuicStreamDataError(y)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:y=>{c||t.onOverrideAudioTrack(y)}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:s,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>A(),onTransportChange:(y,T)=>{c||(y==="webrtc"&&(l(),A()),t.onTransportChange?.(y,T))}}),f=null,m=()=>{f!==null&&(clearTimeout(f),f=null)},w=t.wtRetryBaseMs??2e3,h=t.wtRetryCapMs??3e4,b=null,S=0,A=()=>{if(c||b!==null||p.activeTransport==="webtransport")return;let y=Math.min(w*2**S,h);b=setTimeout(()=>{b=null,S+=1,p.retryWebTransport().then(T=>{if(c){T&&p.disconnect().catch(()=>{});return}if(T)return console.debug(`[urun] webtransport upgraded in background (retry ${S})`),S=0,I(T);A()}).catch(T=>{c||(console.debug(`[urun] webtransport background retry ${S} failed:`,T),A())})},y)},U=()=>{b!==null&&(clearTimeout(b),b=null)},I=async y=>{if(c||y.kind!=="webtransport")return;let T=t.firstMediaWarnMs??1e4;if(m(),f=setTimeout(()=>{c||p.activeTransport!=="webtransport"||console.warn(`[urun] webtransport established but no QUIC media after ${T}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)},T),await y.firstMedia,m(),c||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;u=a.captureStream();let C=u.getVideoTracks()[0];C&&(d=!0,t.onOverrideTrack(C))};return(async()=>{let y=await p.connect();if(c){p.disconnect().catch(()=>{});return}await I(y)})().catch(y=>{if(m(),c){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),A();return}s?.proceed(`negotiation unavailable: ${y instanceof Error?y.message:String(y)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",y),A()}),{activeTransport:()=>p.activeTransport,dispose(){c=!0,m(),U(),l(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var En=new Set;function gt(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var Rn="rpc",tr=3e4,Zt=3e4,Cn="rpc-resp";function In(i){return`${Cn}:${i}`}function mt(){return ye()}function Dn(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 Pn(i,e,t,r,n,o,s,a,c,u){let d=[],l=null,p=!1,f=null,m=!1,w,h,b=new Promise((v,W)=>{w=v,h=W});b.catch(()=>{});let S=s(),A=null,U=null,I=null,y=null,T=null,C=null,N=!0,Q=()=>{I&&(clearTimeout(I),I=null),y&&(y(),y=null)},F=()=>{T&&(clearTimeout(T),T=null),C&&(C(),C=null)},q=!1,X=()=>{q||!m||(q=!0,i.set({rpc:{[e]:null}}))},O=()=>{N=!1,Q(),F(),A?.(),A=null,U?.(),U=null,a?.removeEventListener("abort",M),S.dispose(),X()},g=()=>{if(l){if(d.length>0){let v=l;l=null,v.resolve({value:d.shift(),done:!1})}else if(f!==null){let v=l;l=null,v.reject(f)}else if(p){let v=l;l=null,v.resolve({value:void 0,done:!0})}}},k=v=>{p||(d.push(v),g())},_=v=>{p||(f=v,p=!0,h(v),O(),g())},D=v=>{p||(p=!0,w(v),O(),g())},M=()=>{let v=a?.reason;_(v instanceof he?v:new ge(e))},x=v=>{if(!(p||!v||typeof v!="object"))switch(F(),X(),v.t){case"delta":typeof v.delta=="string"&&k(v.delta);break;case"response":D(v.body);break;case"error":{let{message:W,code:j}=Dn(v.body);_(new he(W,{requestId:e,code:v.code??j}));break}}},J=()=>{let v=S.messages()[Symbol.asyncIterator]();A=()=>{v.return?.(void 0)};let W=()=>{N&&v.next().then(j=>{if(N){if(j.done){p||D(void 0);return}x(j.value),W()}},j=>{N&&_(j)})};W()},Tt=()=>{if(!m){if(m=!0,a){if(a.aborted){_(new ge(e));return}a.addEventListener("abort",M,{once:!0})}U=c?.(v=>_(v))??null,J(),i.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:o}}}),u&&u>0&&!i.synced&&(I=setTimeout(()=>{I=null,!p&&!i.synced&&_(new Fe(u,e))},u),y=i.onSynced(()=>Q())),C=i.onSynced(()=>{C=null,!(p||q||T)&&(T=setTimeout(()=>{T=null,!(p||q)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(Zt/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).`)},Zt))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Tt(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(f!==null){let v=f;return f=null,Promise.reject(v)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((v,W)=>{l={resolve:v,reject:W}})},return(){return p||(p=!0,w(void 0),O()),Promise.resolve({value:void 0,done:!0})},throw(v){return p||(p=!0,h(v),O()),Promise.reject(v)}}}},body:b,start:Tt}}function er(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 Un(i,e){let r=i.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:n,rt:o,br:s}=r,a={};(n==="audio"||n==="video"||n==="data")&&(a.kind=n);let c=er(o);c&&(a.rt=c);let u=er(s);return u&&(a.br=u),a}var ht=class{constructor(e,t,r,n,o){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=n;this._onActivity=o;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let s=this._transport.getTrackByName(this._name)??null;s!==this._track&&this._setTrack(s)})}_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,o=null,s={push(c){if(!n)if(r){let u=r;r=null,u.resolve({value:c,done:!1})}else t.push(c)},end(){if(n=!0,r){let c=r;r=null,c.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(s);let a=()=>{n=!0,e._messageConsumers.delete(s)};return e._transport.mediaAvailability().then(c=>{if(!(c===null||n)&&(o=e._streamConsumeUnavailableError(c),a(),r)){let u=r;r=null,u.reject(o)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):o?Promise.reject(o):n?Promise.resolve({value:void 0,done:!0}):new Promise((c,u)=>{r={resolve:c,reject:u}})},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=Un(t,this._name),n=r?.br;if(n?.by==="runtime")throw new qe(this._name,"runtime","browser");if(n)return;let o={br:{epoch:1}};r?.rt&&(o.rt=r.rt);let s=r?.kind??e;s&&(o.kind=s),t.set({streams:{[this._name]:o}})}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??nt;return Ht(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)}},pe=class i{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new xt;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,r,n,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=n,this._artifactsAuth=o,this._streamData=Pt(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=et(()=>this.recover()),this._activity=Ze({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._presenceTracker=new ne({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this._activation=new ee({onPhase:s=>this.onPhase(s),hint:()=>this.doc(Ke).get(ze)??this.doc("control").get(Ye),onData:(s,a)=>this._streamData.onData(s,a)})}_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 Dt({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,o=new me,s=new ke({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new i(e,o,s,gt(t),te({...t,baseUrl:r.baseUrl}));s.on("connected",()=>{s.multiplexer&&o.setTarget(s.multiplexer)}),s.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),s.setEndsAt(r.endsAt),we()&&await be();let c=t.getAccessToken,u=c?async()=>await c()??n:n;return a.setDocTransport({wsUrl:r.wsUrl,token:u}),await s.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}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=Xe(this.doc("control"),r=>{for(let n of Array.from(this._generationTickHandlers))try{n(r)}catch(o){console.warn("[urun] generationTick handler failed:",o)}})),()=>{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 G(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 $(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new $(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}stream(e){let t=this._streams.get(e);return t||(t=new ht(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._activity?.touch(),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 Mt(e,this._sessionId,En.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Lt(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=_e(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(Ut({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=mt(),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 o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let c=t.timeout;o=setTimeout(()=>n.abort(new Ne(c,r)),c)}let s=this._consumeResponse(r,e,!1,n.signal);s.start();let a=this._presenceTracker?.workBegin();return s.body.finally(()=>{o&&clearTimeout(o),a?.()})}_consumeResponse(e,t,r,n,o){this._activity?.touch(),this._presenceTracker?.consumerRead();let s=this.doc(Rn),a=In(e);return Pn(s,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??tr)}requestStream(e,t={}){let r=mt();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=mt(),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=Jt(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}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.disconnect(),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new Z)}disconnect(){let e=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let r of e)try{r()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let t=Array.from(this._activeRequests);this._activeRequests.clear();for(let r of t)try{r(new $e)}catch{}for(let r of this._docs.values())r.dispose();this._docs.clear();for(let r of this._streams.values())r.dispose();this._streams.clear(),this._transport.disconnect()}};function rr(i){return`urun:logical:v1:${i.orgId}:${i.app}:${i.functionName}`}function vt(){try{return globalThis.sessionStorage??null}catch{return null}}function wt(i){let e=vt();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let r=JSON.parse(t);return typeof r?.logicalId!="string"||r.logicalId.length===0?null:{logicalId:r.logicalId}}catch{return null}}function nr(i,e){let t=vt();if(t)try{t.setItem(i,JSON.stringify({logicalId:e.logicalId}))}catch{}}function K(i){let e=vt();if(e)try{e.removeItem(i)}catch{}}var xn=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Mn(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(!(xn.has(r)||typeof r!="string"))return n=>{let o=n??{},s=rr({orgId:e.orgId,app:i,functionName:r}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,c=a(),u=e.jwt,d=e.getAccessToken?async g=>{let k=await e.getAccessToken(g);return k&&(u=k),k}:void 0,l={...e,getAccessToken:d},p=new me,f=new ke({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),m=new pe(c,p,f,gt(l),te(l)),w,h=!1,b=!1,S,A,U=new Promise(g=>{A=g}),I=g=>{S||(S="teardown",Ve({baseUrl:g.baseUrl,requestId:g.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))},y=g=>{w=g,A({status:"ready",handle:g}),b&&I(g)};m.setEndHandler(async()=>{let g=w?{status:"ready",handle:w}:await U;if(g.status==="unavailable")throw new Z("[urun] session allocation failed before a releasable request was created",{cause:g.cause});let k=w??g.handle;return K(s),S==="teardown"?{status:"ended",requestId:k.requestId}:(S="end",Ct({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider}))});let T=!1,C=!1,N=!1,Q=async g=>{let k=e.sessionKey?void 0:wt(s)?.logicalId;T=!e.sessionKey&&k!==void 0;let _=await It({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider,idempotencyKey:g,sessionKey:e.sessionKey??k,priority:e.priority,onAdmission:M=>f.reportAdmission(M),onRequest:y}),D=d?await d()??void 0:e.jwt;return h||(e.sessionKey||nr(s,{logicalId:_.sessionId}),m.setSessionId(_.sessionId),m.setArtifactsAuth(te({...l,baseUrl:_.baseUrl})),f.setEndsAt(_.endsAt)),{url:_.wsUrl,sessionId:_.sessionId,jwt:D,iceServers:_.response.ice_servers,endsAt:_.endsAt}},F,q=d?async()=>await d()??F:()=>F,X=()=>{let g=f.connectedUrl;return g?_e(g):void 0};f.setConnectionResolver(async()=>{let g=await Q(a());return F=g.jwt,g}),f.on("phase",g=>{if(!Be(g)||f.intentionalDisconnect||e.sessionKey)return;let k=wt(s)?.logicalId;k&&g.sessionId&&k!==g.sessionId||K(s)}),f.on("connected",()=>{f.multiplexer&&p.setTarget(f.multiplexer);let g=f.connectedUrl;g&&m.setDocTransport({wsUrl:g,token:q,resolveServerUrl:X})});let O=async g=>{let k;try{k=await Q(g)}catch(_){if(h){A({status:"unavailable",cause:_});return}if(console.error(`[urun] Failed to create session for ${r}:`,_),K(s),!C&&T&&Et(_))return C=!0,console.warn(`[urun] the resumed session for ${r} was already closed server-side (terminal create echo) \u2014 discarding the stored resumption id and creating a fresh session`),O(a());let D=_ instanceof Error?_:new Error(String(_)),M=_ instanceof ve?_.httpStatus:void 0,x=_ instanceof ve?_.code:void 0;f.reportAllocationFailure(D,M,x),A({status:"unavailable",cause:_});return}h||(f.setAuth({jwt:k.jwt,authProvider:e.authProvider,orgId:e.orgId}),f.setConnection({url:k.url,sessionId:k.sessionId,iceServers:k.iceServers}),we()&&await be(),F=k.jwt,m.setDocTransport({wsUrl:k.url,token:q,resolveServerUrl:X}),await f.connect({app:i,functionName:r,args:o}),m.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))};if(m.onPhase(g=>{let k=g?.name;if(k==="live"){N=!0;return}k!=="ended"&&k!=="expired"&&k!=="error"||f.intentionalDisconnect||k==="error"&&g?.error?.kind!=="runtime-failed"||(e.sessionKey||K(s),!N&&T&&!C&&(C=!0,console.warn(`[urun] resumed session ${m.id} for ${r} is closed server-side (${k}) \u2014 discarding the stored resumption id and creating a fresh session`),O(a()).catch(_=>{console.error(`[urun] fresh-session fall-through failed for ${r}:`,_)})))}),O(c).catch(g=>{console.error(`[urun] Failed to connect session for ${r}:`,g)}),e.releaseOnLeave!==!1){let g=tt(()=>{if(h=!0,e.sessionKey||K(s),f.leaveLeg())return;if(f.connectedUrl!==null){f.disconnect();return}f.disconnect();let x=w;x?I(x):b=!0});m.onDisconnect(g);let k,_,D=!1,M=()=>{D||(D=!0,k?.(),_?.())};U.then(x=>{x.status!=="ready"||D||(k=rt(()=>w!==void 0))}),_=m.onPhase(x=>{let J=x?.name;(J==="ended"||J==="expired"||J==="error")&&M()}),D&&_(),m.onDisconnect(M)}return m}}})}var ir="https://api.urun.sh",sr="URUN_DEV";function Ln(){if(typeof process>"u")return!1;let i=process.env?.[sr];if(typeof i!="string")return!1;let e=i.trim().toLowerCase();return e==="1"||e==="true"}var B=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function On(i,e={}){if(!i)throw new B("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=V(e.baseUrl??ir),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata),(e.dev??Ln())&&(n.dev=!0);let o;try{o=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(n)})}catch(p){throw new B(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let s={};try{s=await o.json()}catch{}if(!o.ok){let p=typeof s.message=="string"?s.message:`HTTP ${o.status}`;throw new B(`[urun] client token mint failed: ${p}`,o.status)}let a=typeof s.token=="string"?s.token:"",c=typeof s.org_id=="string"?s.org_id:"",u=typeof s.expires_at=="string"?Date.parse(s.expires_at):Number.NaN,d=typeof s.expires_in=="number"?s.expires_in:void 0;if(!a)throw new B("[urun] client token mint returned no token (control-plane contract violation)",o.status);let l=Number.isFinite(u)?new Date(u):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:l,orgId:c}}var or=3e4,ar="stream:",bt=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 o=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(o.timer),n.error?o.reject(new Error(n.error)):o.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=`${ar}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${ar}${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 o=String(++this._rpcId),s=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),n(new Error(`RPC request "${e}" timed out after ${or}ms`)))},or);this._pendingRpc.set(o,{resolve:r,reject:n,timer:s}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Wn(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 o=new At(n);return new bt(n,o)}var Nn='video/mp4; codecs="avc1.42E01E"';function Fn(i,e){let t=e?.codec??Nn,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,o=URL.createObjectURL(n);r.src=o,n.addEventListener("sourceopen",()=>{let p;try{p=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 p.updating?new Promise(h=>{p.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:h,value:b}=await f.read();if(h){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{p.appendBuffer(b)}catch(S){if(S instanceof DOMException&&S.name==="QuotaExceededError"){let A=p.buffered;if(A.length>0){let U=A.start(A.length-1);p.remove(0,U),await m(),p.appendBuffer(b)}else throw S}else throw S}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}w()}),r.play().catch(()=>{});let s=r,a=s.captureStream??s.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),u=c.getTracks(),d=0,l=u.length;if(l===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{d++,d>=l&&URL.revokeObjectURL(o)});return c}function qn(i){return i.status.startsWith("pending_")}var z=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)}},fe=class extends z{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function $n(i,e,t){let r=t||e||`HTTP ${i}`;return i===401?new fe(r,e??"unauthorized"):new z(r,{status:i,code:e??`http_${i}`})}var Le=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 z("[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),o=await this._resolveToken(),s=await this._fetch(n,e,o);if(s.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,s=await this._fetch(n,e,o))}if(!s.ok){let{code:a,message:c}=await this._readError(s);throw $n(s.status,a,c)}return this._readJson(s)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,s])=>`${encodeURIComponent(o)}=${encodeURIComponent(s)}`).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 fe("[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:o}=r;return{code:typeof n=="string"?n:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Bn(i){return new Le(i)}var Oe=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 cr(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function jn(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function Vn(i,e){let t=i.getTracks();if(t.length===1&&t[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function yt(i,e){for(let t of[...i.lostListeners])try{t(e)}catch{}}var We=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,yt(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 Oe;return t=>e.getUserMedia(t)}async converge(e){for(let s of this.claims.values())s.track&&(s.track.stop(),s.track=null,s.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(s){let a=`one-capture getUserMedia(${cr(r)}) failed`,c=s instanceof Error?s.message:String(s);for(let u of[...this.claims.values()])if(this.claims.delete(u.kind),u.released=!0,u!==e){let d=new Error(`${a} \u2014 ${u.kind} capture lost: ${c||s}`);d.cause=s,yt(u,d)}throw s}let o=[...this.claims.values()].sort((s,a)=>s===e?1:a===e?-1:0);for(let s of o){let a=jn(n,s.kind)[0]??null;if(s.released){a?.stop();continue}if(!a){this.claims.delete(s.kind),s.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${cr(r)}) returned no ${s.kind} track`),{name:"NotFoundError"});if(s===e)throw c;yt(s,c);continue}if(s.track=a,s.stream=Vn(n,a),s!==e)for(let c of[...s.trackListeners])try{c(a,s.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(o){return r.enqueue(async()=>{if(n.released)throw new Error(`${e} capture claim already released`);if(n.constraints=o,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(o){return n.trackListeners.add(o),()=>n.trackListeners.delete(o)},onLost(o){return n.lostListeners.add(o),()=>n.lostListeners.delete(o)}}};return n}},Hn=null;function Gn(){return Hn??=new We}var dr="input",Kn=30;function zn(i){let e=i.now??Date.now,t=i.field??dr,r=1e3/Math.max(i.hz??30,.001),n=new Set,o=0,s=0,a=0,c=0,u,d=null,l=!1,p=()=>{if(l)return;u=e(),c+=1;let m={keys:[...n],buttons:o,pointer:{x:s,y:a},seq:c,at:u};try{i.awareness.setLocalStateField(t,m)}catch{}},f=()=>{if(l)return;let m=e();if(u===void 0||m-u>=r){d&&(clearTimeout(d),d=null),p();return}if(d)return;let w=Math.max(r-(m-u),0);d=setTimeout(()=>{d=null,p()},w),d.unref?.()};return{keyDown(m){let w=String(m).toLowerCase();n.has(w)||(n.add(w),f())},keyUp(m){let w=String(m).toLowerCase();n.delete(w)&&f()},setButtons(m){let w=Number.isFinite(m)?Number(m):0;w!==o&&(o=w,f())},movePointer(m,w){let h=Number.isFinite(m)?Number(m):0,b=Number.isFinite(w)?Number(w):0;h===0&&b===0||(s+=h,a+=b,f())},heldKeys(){return[...n]},clear(){l||(n.clear(),o=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(l)return;let m=n.size>0||o!==0;n.clear(),o=0,d&&(clearTimeout(d),d=null),m&&p(),l=!0}}}var Yn=1024,Qn=.92,Xn=262144,Jn=256e3,kt=[.9,.8,.7,.6,.5],ur=.8,Zn=8;function St(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 ei(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 pr(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 lr(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 _t(i,e,t,r,n){let o=document.createElement("canvas");o.width=e,o.height=t;let s=o.getContext("2d");if(!s)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(s.fillStyle="#fff",s.fillRect(0,0,e,t)),s.drawImage(i,0,0,e,t),await pr(o,r,n)}async function ti(i,e,t,r){let{width:n,height:o}=e,s=await _t(i,n,o,t,r);if(s.size<=256e3)return{blob:s,width:n,height:o};if(t==="image/jpeg"){for(let c of kt)if(!(c>=r)&&(s=await _t(i,n,o,t,c),s.size<=256e3))return lr(`quality ${r} -> ${c}`,s.size),{blob:s,width:n,height:o}}let a=t==="image/jpeg"?kt[kt.length-1]:r;for(let c=0;c<Zn;c++)if(n=Math.max(16,Math.round(n*ur)),o=Math.max(16,Math.round(o*ur)),s=await _t(i,n,o,t,a),s.size<=256e3)return lr(`downscaled to ${n}x${o} @ q${a}`,s.size),{blob:s,width:n,height:o};throw new Error(`this image cannot be sent: even at ${n}x${o} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function ri(i,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:o}=e,s=await ei(i);try{let a=St(s.width,s.height,t),c=await ti(s,a,r,n);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:r,width:c.width,height:c.height,source:o}}finally{s.close()}}function ni(i){let e=i instanceof Error?i.name:"",t=i instanceof Error?i.message:String(i);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function ii(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function si(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:o="image/jpeg",quality:s=.92}=e??{},a=St(t,r,n),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let u=c.getContext("2d");if(!u)throw new Error("could not prepare the reference image (no 2d canvas context)");o==="image/jpeg"&&(u.fillStyle="#fff",u.fillRect(0,0,a.width,a.height)),u.drawImage(i,0,0,a.width,a.height);let d=await pr(c,o,s);return{bytes:new Uint8Array(await d.arrayBuffer()),type:o,width:a.width,height:a.height,source:"camera"}}var oi=new Set(["w","a","s","d"]),Y=(i,e)=>Math.min(e,Math.max(-e,i));function ai(i={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:n=900,frameRelax:o=.06,maxPan:s=.12,maxLogZoom:a=.22}=i,c=0,u=0,d=0,l=null,p=new Set;return{pointerDelta(f,m){c=Y(c-f*e,s),u=Y(u-m*e,s)},keyDown(f){let m=f.toLowerCase();oi.has(m)&&p.add(m)},keyUp(f){p.delete(f.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let f=1-o;c*=f,u*=f,d*=f},tick(f){if(l===null){l=f;return}let m=Math.max(0,Math.min(100,f-l))/1e3;l=f,p.has("w")&&(d=Y(d+t*m,a)),p.has("s")&&(d=Y(d-t*m,a)),p.has("a")&&(c=Y(c+r*m,s)),p.has("d")&&(c=Y(c-r*m,s));let w=Math.exp(-m*1e3/n);c*=w,u*=w,d*=w},transform(){return{translateX:c,translateY:u,scale:Math.exp(d)}},isIdentity(f=5e-4){return Math.abs(c)<f&&Math.abs(u)<f&&Math.abs(d)<f},reset(){c=0,u=0,d=0,p.clear()}}}export{Lr as ACTIVATION_COLD_BOOT_AFTER_MS,Or as ACTIVATION_DEGRADED_AFTER_MS,ze as ACTIVATION_HINT_PATH,Mr as ACTIVATION_STILL_AFTER_MS,Je as ACTIVITY_DOM_EVENTS,Ft as ACTIVITY_FIELD,zr as ACTIVITY_STAMP_MIN_INTERVAL_MS,ee as ActivationMonitor,Mn as App,Sr as BACKOFF_BASE_MS,Ar as BACKOFF_MAX_ATTEMPTS,Tr as BACKOFF_MAX_MS,We as CaptureController,Oe as CaptureUnavailableError,B as ClientTokenError,Le as CreditsClient,z as CreditsError,fe as CreditsUnauthorizedError,Xn as DATA_CHANNEL_MESSAGE_CEILING,tr as DEFAULT_DOC_SYNC_TIMEOUT_MS,ir as DEFAULT_GATEWAY_URL,mr as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Qn as DEFAULT_REFERENCE_JPEG_QUALITY,Yn as DEFAULT_REFERENCE_MAX_SIZE,kr as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Dr as DERIVED_LEG_SEP,R as DGRAM_HEADER_BYTES,jt as FOCUS_FIELD,Qr as FOREGROUND_COALESCE_MS,oe as FrameReassembler,Gr as GENERATION_TICK_EMIT_INTERVAL_MS,Kr as GENERATION_TICK_MAX_EXTRAPOLATION_MS,Kn as INPUT_PRESENCE_DEFAULT_HZ,dr as INPUT_PRESENCE_FIELD,H as InvalidDurationError,Ye as LEGACY_ACTIVATION_HINT_PATH,Ke as PLATFORM_DOC_NAME,Ce as PermanentLockedError,Re as PinRequiresActiveTempError,ne as PresenceTracker,hr as ProduceAckTimeoutError,Ae as RecordingNotFoundError,G as RecordingsClient,P as RecordingsError,re as RecordingsUnauthorizedError,ge as RequestAbortError,$e as RequestCancelledError,Fe as RequestDocSyncError,he as RequestError,Ne as RequestTimeoutError,Ee as RetainNotTempError,Te as RuntimeArtifactNotFoundError,$ as RuntimeArtifactsClient,E as RuntimeArtifactsError,Se as RuntimeArtifactsUnauthorizedError,xr as SIGNALING_PROTOCOL_VERSION,He as STREAM_END,pe as Session,ve as SessionAllocationError,fr as SessionEndError,Z as SessionEndUnavailableError,vr as SessionFailedError,qe as StreamDirectionConflict,de as TransportNegotiator,br as TransportSessionMismatchError,ue as TransportSessionSignaling,sr as URUN_DEV_ENV,Bt as USER_ACTIVITY_FIELD,Yr as USER_ACTIVITY_MIN_INTERVAL_MS,qt as VISIBILITY_FIELD,Jn as WIRE_MESSAGE_BUDGET,Gt as WT_CONTROL_FRAME_MAX,zt as WT_DATA_STREAM_VERSION,le as WebRtcSession,ce as WebTransportSession,ie as WtControlDecoder,De as WtDataStreamParser,Ot as activationHintFrom,ii as cameraCaptureAvailable,si as captureStillFromVideo,Er as computeBackoffDelay,ct as consumeWtDataStreams,Ze as createActivityTracker,ai as createCameraWarp,On as createClientToken,Bn as createCreditsClient,zn as createInputPresencePublisher,Hr as createRecordingsClient,Nr as createRuntimeArtifactsClient,Wn as createStore,Ge as decodeStreamEnvelope,Ur as derivedLegName,Pr as derivedLegRole,gr as describeSessionFailure,_r as describeSessionPhase,Ir as encodeStreamEnvelope,st as encodeWtControlFrame,St as fitWithin,Qe as isDurationString,qn as isPendingRecording,Rr as isRetryableSessionError,Be as isServerTerminalPhase,yr as isWakingPhase,nt as mediaRecorderChunkSource,ri as normalizeReferenceImage,jr as normalizeRetention,rt as observeLeaveConfirm,et as observePageLifecycle,tt as observePageTeardown,se as parseDgramHeader,Cr as prewake,ni as referenceImageErrorMessage,Ve as releaseSessionBeacon,wr as sessionFailureFromMediaError,Gn as sharedCaptureController,Fn as videoStream,Xe as watchGenerationTick,je as whenLive,ot as writeDgramHeader};
|
|
1
|
+
import{$ as Ut,A as Er,B as Rr,C as H,D as Rt,E as be,F as Ct,G as It,H as Dt,I as Cr,J as ye,M as ke,N as _e,O as Ge,P as Ir,Q as Ke,S as Pt,U as Dr,V as Pr,W as Ur,X as xr,Y as Se,_ as Te,a as At,aa as xt,b as he,ba as Mt,c as ee,ca as Lt,d as fr,e as ge,f as qe,g as $e,h as Be,i as mr,j as hr,k as ve,l as je,m as gr,n as vr,o as wr,p as br,q as we,r as Et,s as yr,t as Ve,u as kr,v as He,w as _r,x as Sr,y as Tr,z as Ar}from"./chunk-TYT5X4G2.mjs";var Mr=15e3,Lr=45e3,Or=12e4,ze="platform",Ye="activation",Qe="desired.activation";function Ot(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 Wr=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],te=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==="ended"||t?.name==="expired")&&this.dispose()}),this._stopped&&(this._offPhase(),this._offPhase=null)}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=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 Wr){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},o=Ot(this._options.hint());o!==void 0&&(n.hint=o),e.lastEvent=n;for(let s of Array.from(this._handlers))s(n)}};var E=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)}},Ae=class extends E{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Ee=class extends E{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function re(i){return{baseUrl:i.baseUrl,fallbackUrls:i.fallbackUrls,orgId:i.orgId,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}function Nr(i){return new $(i)}var $=class{_options;constructor(e){this._options=e}async list(e){let r=Nt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new E("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(Wt)}async getDownloadUrl(e,t){let r=Nt(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!qr(n))throw new E("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Wt(r.artifact),downloadUrl:n}}async _request(e,t){let r=Rt(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let o of r)try{return await this._requestFromBase(o,e,t)}catch(s){if(n=s instanceof Error?s:new Error(String(s)),n instanceof E&&$r(n.status))throw n}throw n??new E("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${H(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,o=await this._resolveToken(),s=await fetch(n,{method:"GET",headers:this._headers(o)});if(s.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,s=await fetch(n,{method:"GET",headers:this._headers(o)}))}if(!s.ok){let{code:a,message:c}=await this._readError(s,e);throw Br(s.status,a,c)}try{return await s.json()}catch(a){throw new E(`[urun] runtime artifacts: invalid JSON response from ${H(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=H(t);try{let o=(await e.json()).error;if(o&&typeof o=="object"){let{code:s,message:a}=o;return{code:typeof s=="string"&&s.length>0?s:`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 Wt(i){if(!i||typeof i!="object")throw new E("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=i,t=O(e,"artifact_id")||O(e,"id"),r=O(e,"filename"),n=O(e,"kind"),o=O(e,"status")||"ready",s=Fr(e,"size_bytes"),a=O(e,"sha256");if(!t||!r||!n||s==null||!a)throw new E("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:O(e,"content_type")||"application/octet-stream",sizeBytes:s,sha256:a,status:o,createdAt:O(e,"created_at"),expiresAt:O(e,"expires_at")}}function O(i,e){let t=i[e];return typeof t=="string"&&t.length>0?t:void 0}function Fr(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function qr(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function $r(i){return i===401||i===403}function Br(i,e,t){return i===401?new Ae(t,e):i===404?new Ee(t,e):new E(t,i,e)}function Nt(i){if(!i||typeof i!="object"||Array.isArray(i))throw new E("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var P=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)}},ne=class extends P{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Re=class extends P{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Ce=class extends P{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)}},Ie=class extends P{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)}},De=class extends P{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)}},G=class extends P{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 Xe(i){return/^(\d+[smhdw])+$/.test(i)}function jr(i){if(i==="pin")return{action:"pin"};if(Xe(i))return{action:"retain",duration:i};throw new G(`[urun] recordings: "${i}" is not a duration or "pin"`)}function Vr(i,e,t){let r=t||e||`HTTP ${i}`;if(i===401)return new ne(r,e??"unauthorized");if(i===404)return new Re(r,e??"not_found");if(i===400)return new G(r,e??"bad_request",400);if(i===409)switch(e){case"retain_not_temp":return new Ce(r,e);case"pin_requires_active_temp":return new Ie(r,e);case"permanent_locked":return new De(r,e)}return new P(r,{status:i,code:e??`http_${i}`})}var K=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(!Xe(t))throw new G(`[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 P("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),o=await this._resolveToken(),s=await this._fetch(n,e,o,r.body);if(s.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,s=await this._fetch(n,e,o,r.body))}if(!s.ok){let{code:a,message:c}=await this._readError(s);throw Vr(s.status,a,c)}return this._readJson(s)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,s])=>`${encodeURIComponent(o)}=${encodeURIComponent(s)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let o={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(o["X-Auth-Provider"]=this._options.authProvider);let s={method:t,headers:o};return n!==void 0&&(o["Content-Type"]="application/json",s.body=JSON.stringify(n)),fetch(e,s)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new ne("[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:o}=r;return{code:typeof n=="string"?n:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Hr(i){return new K(i)}var Gr=1e3,Kr=12e3;function Je(i,e,t={}){let r=null,n=0,o=0,s=null,a=-1,c=()=>{let h=i.get("desired.billing.generationSeconds");if(typeof h!="number"||!Number.isFinite(h)||h<=0)return null;let y=i.get("desired.billing.epoch"),S=i.get("desired.billing.updatedAtMs");return{seconds:h,epoch:typeof y=="number"&&Number.isFinite(y)?y:0,updatedAtMs:typeof S=="number"&&Number.isFinite(S)?S:null}},u=()=>{if(r===null)return null;let h=Math.min(Math.max(0,Date.now()-n),o);return r+h/1e3},d=()=>{let h=t.creditsPerSecond;if(typeof h=="number"&&Number.isFinite(h)&&h>0)return h;let y=i.get("desired.billing.creditsPerSecond");return typeof y=="number"&&Number.isFinite(y)&&y>0?y:null},l=()=>{let h=u();if(h===null)return;let y=Math.floor(h);if(y<=a)return;a=y;let S={seconds:y},T=d();T!==null&&(S.estimatedCredits=y*T),e(S)},p=h=>{n=Date.now();let y=h===null?0:Math.max(0,n-h);o=Math.max(0,12e3-y)},f=()=>{let h=c();if(h!==null){if(s!==null&&h.epoch!==s){s=h.epoch,r=h.seconds,a=-1,p(h.updatedAtMs),l();return}r!==null&&h.seconds<=r||(s=h.epoch,r=h.seconds,p(h.updatedAtMs),l())}};f();let m=i.on("change",f),v=setInterval(l,1e3);return v.unref?.(),()=>{clearInterval(v),m()}}var Ft="activity",qt="visibility",zr=15e3,Ze=["pointerdown","pointermove","keydown","wheel","touchstart"];function et(i){let e=i.now??Date.now,t=i.windowTarget!==void 0?i.windowTarget:typeof window<"u"?window:null,r=i.documentTarget!==void 0?i.documentTarget:typeof document<"u"?document:null,n=!1,o,s=()=>{if(n)return;let l=e();if(!(o!==void 0&&l-o<15e3)){o=l;try{i.awareness.setLocalStateField(Ft,{at:l})}catch{}}},a=()=>{if(!(n||!r||r.visibilityState===void 0))try{i.awareness.setLocalStateField(qt,r.visibilityState)}catch{}},c=()=>s(),u=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&s()};if(t)for(let l of Ze)t.addEventListener(l,c,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",u);let d=null;return i.isProducing&&(d=setInterval(()=>{if(!n)try{i.isProducing?.()&&s()}catch{}},15e3),d.unref?.()),s(),a(),{touch:s,dispose(){if(!n){if(n=!0,t)for(let l of Ze)t.removeEventListener(l,c,{capture:!0});r&&r.removeEventListener("visibilitychange",u),d&&(clearInterval(d),d=null)}}}}var Bt="user_activity",jt="focus",Yr=3e4;function $t(i){switch(i){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var ie=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($t(e.state));let t=e.on("stateChange",n=>{this._setState($t(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(jt,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(Bt,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 Qr=250;function tt(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 rt(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 nt(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 Vt="video/mp4";function it(i,e={}){let t=e.timesliceMs??1e3,r=null,n=null,o=!1,s=(a,c,u)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)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 l=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(Vt)?Vt:void 0),p=new MediaStream([a]),f=new d(p,l?{mimeType:l}:void 0);r=f;let m=Promise.resolve();f.ondataavailable=v=>{let h=v.data;o||!h||h.size===0||(m=m.then(async()=>{let y=new Uint8Array(await h.arrayBuffer());o||c(y)}))},f.onstop=()=>{m.then(()=>{o||u()})},f.onerror=()=>{m.then(()=>{o||u()})},f.start(t)};return{start(a,c){if(r||o)return;let u=i.track();if(u){s(u,a,c);return}n=i.onTrack(d=>{!d||r||o||(n?.(),n=null,s(d,a,c))})},stop(){if(o)return;o=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Xr(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 Ht(i,e){let t=null,r=!1,n=!1,o=new ReadableStream({pull(s){r||(r=!0,t=i(e),t.start(a=>{if(!n)try{s.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{s.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Xr(o)}import{encode as Jr,decode as Zr}from"@msgpack/msgpack";var Gt=65536;function ot(i){let e=Jr(i),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var se=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>Gt)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(Zr(n))}return t}},R=12,st=1,en=0,Pe=1,Kt=2;function oe(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&st)===st,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function at(i){let e=new Uint8Array(R),t=new DataView(e.buffer);return t.setUint32(0,i.groupId,!0),t.setUint32(4,i.frameSeq,!0),t.setUint8(8,i.keyframe?st:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??en),e}var tn=100,ae=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??tn}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<R)return;let t=oe(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,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(R),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++)}}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((s,a)=>s+a.byteLength,0),n=new Uint8Array(r),o=0;for(let s of t.chunks)n.set(s,o),o+=s.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 rn=/^avc[13]\.[0-9a-fA-F]{6}$/;function nn(i){return rn.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 ct(i,e){let t=nn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var zt=1,Ue=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!==zt)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=Ke(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),n===Ge&&(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 dt(i,e){let t=i.getReader();for(;;){let{value:r,done:n}=await t.read();if(n)return;r&&sn(r,e).catch(o=>{e.onLaneError(o instanceof Error?o:new Error(String(o)))})}}async function sn(i,e){let t=i.getReader(),r=new Ue;try{for(;;){let{value:n,done:o}=await t.read();if(o)break;if(!(!n||n.byteLength===0))for(let{name:s,payload:a}of r.push(n))e.onData(s,a)}r.finish()}catch(n){try{await t.cancel?.(n)}catch{}throw n}}var ut=40,pt=48e3,on=64,lt=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<R)return;let t=oe(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,t.frameSeq<=this.newestDelivered||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>on;){let a=1/0;for(let c of this.pending.keys())c<a&&(a=c);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=r.fragCount||r.chunks[t.fragIndex]||(r.chunks[t.fragIndex]=e.subarray(R),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,c)=>a+(c?.byteLength??0),0),o=new Uint8Array(n),s=0;for(let a of r.chunks)o.set(a,s),s+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:r.timestamp,data:o})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},an=3,cn=1e4,xe=class{constructor(e,t){this.config=e;this.seam=t;let r=this.seam.jitterBufferTargetMs??ut;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${ut}ms`),r=ut),this.targetS=Math.max(0,r)/1e3}config;seam;decoder=null;decoderErrorsAt=[];ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;deadCb=null;assembler=new lt(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}}onDead(e){this.deadCb=e}stop(){if(!this.stopped){this.stopped=!0,this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ctx?.close().catch(()=>{})}}initDecoder(e){this.decoder=new e({output:t=>this.schedule(t),error:t=>this.onDecoderError(t)}),this.decoder.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels})}decodeFrame(e){let t=globalThis.EncodedAudioChunk;!this.decoder||typeof t!="function"||this.stopped||this.decoder.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/pt)),data:e.data}))}schedule(e){let t=this.ctx,r=this.dest;if(!t||!r||this.stopped){e.close();return}if(!this.trackSurfaced){this.trackSurfaced=!0,t.resume?.().catch(()=>{});let d=r.stream.getAudioTracks()[0];d&&this.seam.onTrack(d)}let n=e.numberOfFrames,o=Math.max(1,e.numberOfChannels),s=t.createBuffer(o,n,e.sampleRate);for(let d=0;d<o;d++){let l=new Float32Array(n);e.copyTo(l,{planeIndex:d,format:"f32-planar"}),s.copyToChannel(l,d)}let a=n/e.sampleRate;e.close();let c=t.createBufferSource();c.buffer=s,c.connect(r);let u=Math.max(this.playhead,t.currentTime+this.targetS);c.start(u),this.playhead=u+a}onDecoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(n=>t-n<cn),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=an){let n=`audio decoder: ${e.message}`;console.warn(`[urun] WT audio lane dead (${n}) \u2014 audio reverts to the WebRTC track`),this.stop(),this.deadCb?.(n);return}console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=globalThis.AudioDecoder;typeof r=="function"&&this.initDecoder(r)}};var ce=1200,dn=3,un=1e4;function ln(i){return Math.round(i*(pt/1e6))%2**32>>>0}function ft(i,e,t,r,n){let o=r-R;if(o<=0)return null;let s=Math.max(1,Math.ceil(t.byteLength/o));if(s>255)return null;let a=[];for(let c=0;c<s;c++){let u=t.subarray(c*o,Math.min((c+1)*o,t.byteLength)),d=at({groupId:e>>>0,frameSeq:i>>>0,keyframe:n?.keyframe??!0,fragIndex:c,fragCount:s,lane:n?.lane??Pe}),l=new Uint8Array(R+u.byteLength);l.set(d,0),l.set(u,R),a.push(l)}return a}var Me=class{constructor(e){this.sink=e}sink;encoder=null;encoderConfig=null;encoderErrorsAt=[];frameSeq=0;stopped=!1;deadCb=null;generation=0;cancelCapture=null;nodeBridge=null;onDead(e){this.deadCb=e}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}let n;if(pn(e)){let c=e,u=c.context.createMediaStreamDestination();c.connect(u),this.nodeBridge={node:c,dest:u};let d=u.stream.getAudioTracks()[0];if(!d){this.die("AudioNode bridge produced no audio track");return}n=d}else n=e;let o=++this.generation,s=new r({track:n}).readable.getReader(),a=!1;this.cancelCapture=()=>{a=!0,s.cancel().catch(()=>{})},(async()=>{for(;!a&&!this.stopped&&o===this.generation;){let{value:c,done:u}=await s.read();if(u)break;if(c){if(a||this.stopped||o!==this.generation){c.close();break}this.encodeAudioData(c)}}})().catch(c=>{!a&&!this.stopped&&o===this.generation&&this.die(`capture: ${c instanceof Error?c.message:String(c)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){if(this.cancelCapture?.(),this.cancelCapture=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}this.generation++}encodeAudioData(e){if(!this.encoder){let r=globalThis.AudioEncoder;if(typeof r!="function"){e.close(),this.die("AudioEncoder is not available");return}this.encoderConfig={sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels};try{this.initEncoder(r)}catch(n){e.close(),this.encoder=null,this.die(`encoder configure: ${n instanceof Error?n.message:String(n)}`);return}}let t=this.encoder;if(!t){e.close();return}try{t.encode(e)}catch(r){this.onEncoderError(r instanceof Error?r:new Error(String(r)))}e.close()}initEncoder(e){let t=this.encoderConfig;this.encoder=new e({output:r=>this.sendFrame(r),error:r=>this.onEncoderError(r)}),this.encoder.configure({codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3})}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=ft(this.frameSeq,ln(e.timestamp),t,this.sink.maxDatagramSize()||ce);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}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(n=>t-n<un),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=dn){this.die(`audio encoder: ${e.message}`);return}console.warn("[urun] WT mic uplink encoder error \u2014 re-initializing the encoder:",e.message);try{this.encoder?.close()}catch{}this.encoder=null;let r=globalThis.AudioEncoder;if(!(typeof r!="function"||!this.encoderConfig))try{this.initEncoder(r)}catch(n){this.die(`encoder re-init: ${n instanceof Error?n.message:String(n)}`)}}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 pn(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var fn=9e4,mn="avc1.42E01F",hn=60,gn=3,vn=1e4;function wn(i){return Math.round(i*(fn/1e6))%2**32>>>0}var Le=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;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,o=new r({track:e}).readable.getReader(),s=!1;this.cancelCapture=()=>{s=!0,o.cancel().catch(()=>{})},(async()=>{for(;!s&&!this.stopped&&n===this.generation;){let{value:a,done:c}=await o.read();if(c)break;if(a){if(s||this.stopped||n!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!s&&!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 o=globalThis.VideoEncoder;if(typeof o!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new o({output:s=>this.sendFrame(s),error:s=>this.onEncoderError(s)})),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(s){e.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${s instanceof Error?s.message:String(s)}`);return}}let n=this.keyframeWanted||this.framesSinceKeyframe>=hn;this.keyframeWanted=!1,this.framesSinceKeyframe=n?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:n})}catch(o){this.onEncoderError(o instanceof Error?o:new Error(String(o)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=ft(this.frameSeq,wn(e.timestamp),t,this.sink.maxDatagramSize()||ce,{lane:Kt,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<vn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=gn){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 Oe=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 o=this.streams.get(e);if(!o){let a=await this.transport.openUniStream(),c=new Uint8Array(2+r.byteLength);c[0]=1,c[1]=r.byteLength,c.set(r,2),await a.write(c),o={writer:a},this.streams.set(e,o)}let s=new Uint8Array(4+t.byteLength);new DataView(s.buffer).setUint32(0,t.byteLength,!0),s.set(t,4),await o.writer.write(s),bn(t)&&(this.streams.delete(e),await o.writer.close().catch(()=>{}))}catch(o){throw this.die(o instanceof Error?o.message:String(o)),o}});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 yn=250,kn=3,_n=1e4,mt=2500,de=class{constructor(e,t,r,n,o,s,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=n;this.audioUplink=o;this.videoUplink=s;this.dataUplink=a;this.firstMedia=new Promise((c,u)=>{this.firstFrameResolve=c,this.firstFrameReject=u}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorsAt=[];writer;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;reassembler=new ae({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;firstFrameOutput=!1;hasVideoLane=!1;firstDecodeTimer=null;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&&ct(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(d=>({algorithm:"sha-256",value:Uint8Array.from(atob(d),l=>l.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 o=n.readable.getReader(),s=new se,a=[],c=await this.readControl(o,s,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");if(r&&(ct(c.codec,"hello-ack"),this.initDecoder(c.codec,c.width,c.height)),this.offer.audio&&this.audioLane){let d=new xe(this.offer.audio,this.audioLane);d.onDead(()=>{this.audioPlayout=null});try{d.start(),this.audioPlayout=d}catch(l){console.warn(`[urun] WT audio lane failed to start (${l instanceof Error?l.message:String(l)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),d.stop()}}let u=()=>{let d=this.wt.datagrams.writable;if(!d)throw new Error("WebTransport datagrams are not writable in this environment");let l=d.getWriter();return{send:p=>{l.write(p).catch(()=>{})},maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??ce}};if(this.offer.audioUp===!0&&this.audioUplink)try{let d=new Me(u());d.onDead(l=>{this.audioUplinkLane=null,this.audioUplink.onUplinkLost(l)}),this.audioUplinkLane=d,this.audioUplink.onUplink(d)}catch(d){let l=d instanceof Error?d.message:String(d);console.warn(`[urun] WT mic uplink failed to engage (${l}) \u2014 keeping the WT session; the mic stays on the WebRTC produce path`),this.audioUplink.onUplinkLost(l)}if(this.offer.videoUp===!0&&this.videoUplink)try{let d=new Le(u());d.onDead(l=>{this.videoUplinkLane=null,this.videoUplink.onUplinkLost(l)}),this.videoUplinkLane=d,this.videoUplink.onUplink(d)}catch(d){let l=d instanceof Error?d.message:String(d);console.warn(`[urun] WT video uplink failed to engage (${l}) \u2014 keeping the WT session; the camera stays on the WebRTC produce path`),this.videoUplink.onUplinkLost(l)}if(this.offer.dataUp===!0&&this.dataUplink)try{let d=this.wt.createUnidirectionalStream?.bind(this.wt);if(!d)throw new Error("WebTransport uni streams are not creatable in this environment");let l=new Oe({openUniStream:async()=>(await d()).getWriter()});l.onDead(p=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(p)}),this.dataUplinkSender=l,this.dataUplink.onUplink(l)}catch(d){let l=d instanceof Error?d.message:String(d);console.warn(`[urun] WT data uplink failed to engage (${l}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(l)}this.controlLoop(o,s,a).catch(d=>this.die(`control loop: ${d}`)),this.datagramLoop().catch(d=>this.die(`datagram loop: ${d}`)),this.feedbackLoop(),this.wt.closed.then(()=>this.die("connection closed")).catch(d=>this.die(`connection error: ${d}`))}async stop(){this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),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");try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}dropUplinks(e){let t=this.audioUplinkLane;t&&(this.audioUplinkLane=null,t.stop(),this.audioUplink?.onUplinkLost(e));let r=this.videoUplinkLane;r&&(this.videoUplinkLane=null,r.stop(),this.videoUplink?.onUplinkLost(e));let n=this.dataUplinkSender;n&&(this.dataUplinkSender=null,n.stop(e),this.dataUplink?.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,dt(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 o=this.canvas.getContext("2d");if(!o)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r},this.decoder=new n({output:s=>{this.firstFrameOutput=!0,this.firstDecodeTimer&&(clearTimeout(this.firstDecodeTimer),this.firstDecodeTimer=null),this.canvas.width=s.displayWidth,this.canvas.height=s.displayHeight,o.drawImage(s,0,0),s.close()},error:s=>this.onDecoderError(s)}),this.decoder.configure({codec:e,...t>0&&r>0?{codedWidth:t,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"})}onDecoderError(e){if(this.stopped||this.deadFired)return;let t=performance.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(n=>t-n<_n),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=kn){this.die(`decoder: ${e.message}`);return}console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=this.decoderConfig;if(!r){this.die(`decoder: ${e.message} (no config to re-init from)`);return}try{this.initDecoder(r.codec,r.width,r.height)}catch(n){this.die(`decoder re-init: ${n instanceof Error?n.message:String(n)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}armFirstDecodeDeadline(){if(this.firstDecodeTimer||this.firstFrameOutput||this.stopped||this.deadFired)return;let e=setTimeout(()=>{this.firstDecodeTimer=null,!(this.firstFrameOutput||this.stopped||this.deadFired)&&(console.error(`[urun] webtransport: media datagrams arriving but NO frame decoded within ${mt}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${mt}ms`))},mt);e.unref?.(),this.firstDecodeTimer=e}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>=R&&t[11]===Pe){this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;this.armFirstDecodeDeadline();let n=performance.now();if(this.lastArrivalTs>0){let o=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(o-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=n,this.reassembler.push(t)}}decodeFrame(e,t,r){let n=globalThis.EncodedVideoChunk;!this.decoder||typeof n!="function"||(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){await this.writer.write(ot(e))}async readControl(e,t,r=[]){for(;;){let n=r.shift();if(n)return n;let{value:o,done:s}=await e.read();if(s)return null;o&&r.push(...t.push(o))}}async controlLoop(e,t,r){for(;!this.stopped;){let n=await this.readControl(e,t,r);if(!n)break;n.t==="ping"&&this.sendControl({t:"pong",ts:n.ts}).catch(()=>{}),n.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(),o=n.delivered+n.abandoned;this.lastStats={recvBps:r>0?n.bytes*8/r:0,lossPct:o>0?100*n.abandoned/o:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},yn)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks(e);try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var Yt=2500,Qt=["av01.0.08M.08","avc1.42E01F","avc1.640028"],ue=class{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;get activeTransport(){return this.session?.kind??null}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,o={webtransport:t&&r&&n,webcodecs:r,codecs:Qt,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&&r&&n&&this.opts.audioUplink!==void 0&&typeof e.AudioEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="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:o});let s=o.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,c=s&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(c||this.opts.webRtcDial?.proceed(s?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),o.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),s){let u=null;try{return u=this.createWebTransportSession(),await Xt(u.start(),this.opts.quicDeadlineMs??Yt,"quic connect deadline"),this.engageQuicDataLane(u,o.wtData===!0),this.session=u,c&&(this.wtOnlyLeg=!0,this.opts.webRtcDial?.skip("fully-granted WT leg established")),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(d){if(u?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let l=String(d instanceof Error?d.message:d);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${l}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(l),d}console.warn("[urun] webtransport failed, falling back to webrtc:",d),this.opts.webRtcDial?.proceed(`wt failed: ${String(d instanceof Error?d.message:d)}`),this.notifyEstablished("webrtc",String(d instanceof Error?d.message:d))}}if(this.opts.allowWebRtcFallback===!1){let u=s?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${u} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(u),new Error(`[urun] WT required but unavailable: ${u}`)}return this.session=await this.startWebRtc(),s||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.quicDataLane=!1,await this.session?.stop(),this.session=null}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,o=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",s=this.opts.audioUplink!==void 0&&typeof e.AudioEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",a=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",c=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:Qt,wtData:n,wtAudio:o,wtAudioUp:s,wtVideoUp:a,wtDataUp:c}}),!this.offer.webtransport)return null;let u=this.createWebTransportSession();try{await Xt(u.start(),this.opts.quicDeadlineMs??Yt,"quic connect deadline")}catch(d){throw u.stop().catch(()=>{}),d}if(this.session!==r)return u.stop().catch(()=>{}),null;try{this.engageQuicDataLane(u,n)}catch(d){throw u.stop().catch(()=>{}),d}this.session=u;{let d=this.offer.webtransport;d&&(this.opts.audioLane===void 0||d.audio!==void 0)&&(this.opts.audioUplink===void 0||d.audioUp===!0)&&(this.opts.videoUplink===void 0||d.videoUp===!0)&&(this.opts.dataLane===void 0||d.data===!0)&&(this.opts.dataUplink===void 0||d.dataUp===!0)&&(this.wtOnlyLeg=!0,this.opts.webRtcDial?.skip("fully-granted WT leg re-established"))}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),u}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,o)=>r.onData(n,o),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 de(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}async startWebRtc(){let e=this.opts.createWebRtcSession();return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}armFailover(){let e=this.session;e.onDead(t=>{if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; retrying WT`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.opts.onWtRequiredOutage?.(t);return}this.wtOnlyLeg&&(this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(`failover: ${t}`)),console.warn("[urun] quic died mid-session, failing over to webrtc:",t),this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),(async()=>{try{this.session=await this.startWebRtc(),this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(r){this.session=null,console.error("[urun] failover to webrtc also failed:",r)}})()})}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function Xt(i,e,t){return new Promise((r,n)=>{let o=setTimeout(()=>n(new Error(t)),e);i.then(s=>{clearTimeout(o),r(s)},s=>{clearTimeout(o),n(s)})})}var Sn=1e4,le=class{constructor(e,t=Sn){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=_e();return new Promise((n,o)=>{let s=setTimeout(()=>{a(),o(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(s),a(),c.error){o(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:u,requestId:d,...l}=c;n(l)});this.carrier.sendSignal({type:e,requestId:r,...t})||(clearTimeout(s),a(),o(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 Tn="video",pe=class{constructor(e,t=Tn){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))}};var An="video";function Jt(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 s=i.holdWebRtcDial?.(),a=n.createElement("canvas"),c=!1,u=null,d=!1,l=()=>{if(u){for(let k of u.getVideoTracks())try{k.stop()}catch{}u=null}d&&(d=!1,t.onOverrideTrack(null))},p=new ue(new le(i),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new pe(i,t.streamName??An)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(k,A)=>i.dispatchQuicStreamData(k,A),onQuicLane:()=>i.markStreamDataLaneQuic(),onQuicLaneLost:k=>i.quicStreamDataLaneLost(k),onLaneError:k=>i.raiseQuicStreamDataError(k)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:k=>{c||t.onOverrideAudioTrack(k)}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:s,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>T(),onTransportChange:(k,A)=>{c||(k==="webrtc"&&(l(),T()),t.onTransportChange?.(k,A))}}),f=null,m=()=>{f!==null&&(clearTimeout(f),f=null)},v=t.wtRetryBaseMs??2e3,h=t.wtRetryCapMs??3e4,y=null,S=0,T=()=>{if(c||y!==null||p.activeTransport==="webtransport")return;let k=Math.min(v*2**S,h);y=setTimeout(()=>{y=null,S+=1,p.retryWebTransport().then(A=>{if(c){A&&p.disconnect().catch(()=>{});return}if(A)return console.debug(`[urun] webtransport upgraded in background (retry ${S})`),S=0,I(A);T()}).catch(A=>{c||(console.debug(`[urun] webtransport background retry ${S} failed:`,A),T())})},k)},U=()=>{y!==null&&(clearTimeout(y),y=null)},I=async k=>{if(c||k.kind!=="webtransport")return;let A=t.firstMediaWarnMs??1e4;if(m(),f=setTimeout(()=>{c||p.activeTransport!=="webtransport"||console.warn(`[urun] webtransport established but no QUIC media after ${A}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)},A),await k.firstMedia,m(),c||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;u=a.captureStream();let C=u.getVideoTracks()[0];C&&(d=!0,t.onOverrideTrack(C))};return(async()=>{let k=await p.connect();if(c){p.disconnect().catch(()=>{});return}await I(k)})().catch(k=>{if(m(),c){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",k);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",k),T();return}s?.proceed(`negotiation unavailable: ${k instanceof Error?k.message:String(k)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",k),T()}),{activeTransport:()=>p.activeTransport,dispose(){c=!0,m(),U(),l(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var En=new Set;function vt(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var Rn="rpc",tr=3e4,Zt=3e4,Cn="rpc-resp";function In(i){return`${Cn}:${i}`}function ht(){return _e()}function Dn(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 Pn(i,e,t,r,n,o,s,a,c,u){let d=[],l=null,p=!1,f=null,m=!1,v,h,y=new Promise((b,N)=>{v=b,h=N});y.catch(()=>{});let S=s(),T=null,U=null,I=null,k=null,A=null,C=null,M=!0,X=()=>{I&&(clearTimeout(I),I=null),k&&(k(),k=null)},J=()=>{A&&(clearTimeout(A),A=null),C&&(C(),C=null)},L=!1,Z=()=>{L||!m||(L=!0,i.set({rpc:{[e]:null}}))},F=()=>{M=!1,X(),J(),T?.(),T=null,U?.(),U=null,a?.removeEventListener("abort",D),S.dispose(),Z()},q=()=>{if(l){if(d.length>0){let b=l;l=null,b.resolve({value:d.shift(),done:!1})}else if(f!==null){let b=l;l=null,b.reject(f)}else if(p){let b=l;l=null,b.resolve({value:void 0,done:!0})}}},g=b=>{p||(d.push(b),q())},w=b=>{p||(f=b,p=!0,h(b),F(),q())},_=b=>{p||(p=!0,v(b),F(),q())},D=()=>{let b=a?.reason;w(b instanceof ge?b:new ve(e))},W=b=>{if(!(p||!b||typeof b!="object"))switch(J(),Z(),b.t){case"delta":typeof b.delta=="string"&&g(b.delta);break;case"response":_(b.body);break;case"error":{let{message:N,code:V}=Dn(b.body);w(new ge(N,{requestId:e,code:b.code??V}));break}}},x=()=>{let b=S.messages()[Symbol.asyncIterator]();T=()=>{b.return?.(void 0)};let N=()=>{M&&b.next().then(V=>{if(M){if(V.done){p||_(void 0);return}W(V.value),N()}},V=>{M&&w(V)})};N()},j=()=>{if(!m){if(m=!0,a){if(a.aborted){w(new ve(e));return}a.addEventListener("abort",D,{once:!0})}U=c?.(b=>w(b))??null,x(),i.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:o}}}),u&&u>0&&!i.synced&&(I=setTimeout(()=>{I=null,!p&&!i.synced&&w(new $e(u,e))},u),k=i.onSynced(()=>X())),C=i.onSynced(()=>{C=null,!(p||L||A)&&(A=setTimeout(()=>{A=null,!(p||L)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(Zt/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).`)},Zt))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(j(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(f!==null){let b=f;return f=null,Promise.reject(b)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((b,N)=>{l={resolve:b,reject:N}})},return(){return p||(p=!0,v(void 0),F()),Promise.resolve({value:void 0,done:!0})},throw(b){return p||(p=!0,h(b),F()),Promise.reject(b)}}}},body:y,start:j}}function er(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 Un(i,e){let r=i.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:n,rt:o,br:s}=r,a={};(n==="audio"||n==="video"||n==="data")&&(a.kind=n);let c=er(o);c&&(a.rt=c);let u=er(s);return u&&(a.br=u),a}var gt=class{constructor(e,t,r,n,o){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=n;this._onActivity=o;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let s=this._transport.getTrackByName(this._name)??null;s!==this._track&&this._setTrack(s)})}_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,o=null,s={push(c){if(!n)if(r){let u=r;r=null,u.resolve({value:c,done:!1})}else t.push(c)},end(){if(n=!0,r){let c=r;r=null,c.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(s);let a=()=>{n=!0,e._messageConsumers.delete(s)};return e._transport.mediaAvailability().then(c=>{if(!(c===null||n)&&(o=e._streamConsumeUnavailableError(c),a(),r)){let u=r;r=null,u.reject(o)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):o?Promise.reject(o):n?Promise.resolve({value:void 0,done:!0}):new Promise((c,u)=>{r={resolve:c,reject:u}})},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=Un(t,this._name),n=r?.br;if(n?.by==="runtime")throw new Be(this._name,"runtime","browser");if(n)return;let o={br:{epoch:1}};r?.rt&&(o.rt=r.rt);let s=r?.kind??e;s&&(o.kind=s),t.set({streams:{[this._name]:o}})}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??it;return Ht(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)}},fe=class i{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new xt;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,r,n,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=n,this._artifactsAuth=o,this._streamData=Pt(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=tt(()=>this.recover()),this._activity=et({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._presenceTracker=new ie({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this._activation=new te({onPhase:s=>this.onPhase(s),hint:()=>this.doc(ze).get(Ye)??this.doc("control").get(Qe),onData:(s,a)=>this._streamData.onData(s,a)})}_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 Dt({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,o=new he,s=new Se({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new i(e,o,s,vt(t),re({...t,baseUrl:r.baseUrl}));s.on("connected",()=>{s.multiplexer&&o.setTarget(s.multiplexer)}),s.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),s.setEndsAt(r.endsAt),ye()&&await ke();let c=t.getAccessToken,u=c?async()=>await c()??n:n;return a.setDocTransport({wsUrl:r.wsUrl,token:u}),await s.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}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 He(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=Je(this.doc("control"),r=>{for(let n of Array.from(this._generationTickHandlers))try{n(r)}catch(o){console.warn("[urun] generationTick handler failed:",o)}})),()=>{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 K(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 $(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new $(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}stream(e){let t=this._streams.get(e);return t||(t=new gt(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._activity?.touch(),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 Mt(e,this._sessionId,En.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Lt(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=Te(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(Ut({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=ht(),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 o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let c=t.timeout;o=setTimeout(()=>n.abort(new qe(c,r)),c)}let s=this._consumeResponse(r,e,!1,n.signal);s.start();let a=this._presenceTracker?.workBegin();return s.body.finally(()=>{o&&clearTimeout(o),a?.()})}_consumeResponse(e,t,r,n,o){this._activity?.touch(),this._presenceTracker?.consumerRead();let s=this.doc(Rn),a=In(e);return Pn(s,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??tr)}requestStream(e,t={}){let r=ht();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=ht(),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=Jt(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}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.disconnect(),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new ee)}disconnect(){let e=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let r of e)try{r()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let t=Array.from(this._activeRequests);this._activeRequests.clear();for(let r of t)try{r(new je)}catch{}for(let r of this._docs.values())r.dispose();this._docs.clear();for(let r of this._streams.values())r.dispose();this._streams.clear(),this._transport.disconnect()}};function rr(i){return`urun:logical:v1:${i.orgId}:${i.app}:${i.functionName}`}function wt(){try{return globalThis.sessionStorage??null}catch{return null}}function bt(i){let e=wt();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let r=JSON.parse(t);return typeof r?.logicalId!="string"||r.logicalId.length===0?null:{logicalId:r.logicalId}}catch{return null}}function nr(i,e){let t=wt();if(t)try{t.setItem(i,JSON.stringify({logicalId:e.logicalId}))}catch{}}function z(i){let e=wt();if(e)try{e.removeItem(i)}catch{}}var xn=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Mn(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(!(xn.has(r)||typeof r!="string"))return n=>{let o=n??{},s=rr({orgId:e.orgId,app:i,functionName:r}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,c=a(),u=e.jwt,d=e.getAccessToken?async g=>{let w=await e.getAccessToken(g);return w&&(u=w),w}:void 0,l={...e,getAccessToken:d},p=new he,f=new Se({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),m=new fe(c,p,f,vt(l),re(l)),v,h=!1,y=!1,S,T,U=new Promise(g=>{T=g}),I=g=>{S||(S="teardown",be({baseUrl:g.baseUrl,requestId:g.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))},k=g=>{S||(S="abandon",be({baseUrl:g.baseUrl,requestId:g.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider,reason:"client_abandoned"}))},A=g=>{v=g,T({status:"ready",handle:g}),y&&I(g)};m.setEndHandler(async()=>{let g=v?{status:"ready",handle:v}:await U;if(g.status==="unavailable")throw new ee("[urun] session allocation failed before a releasable request was created",{cause:g.cause});let w=v??g.handle;return z(s),S==="teardown"?{status:"ended",requestId:w.requestId}:(S="end",Ct({baseUrl:w.baseUrl,requestId:w.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider}))});let C=!1,M=!1,X=!1,J=async g=>{let w=e.sessionKey?void 0:bt(s)?.logicalId;C=!e.sessionKey&&w!==void 0;let _=await It({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider,idempotencyKey:g,sessionKey:e.sessionKey??w,priority:e.priority,onAdmission:W=>f.reportAdmission(W),onRequest:A}),D=d?await d()??void 0:e.jwt;return h||(e.sessionKey||nr(s,{logicalId:_.sessionId}),m.setSessionId(_.sessionId),m.setArtifactsAuth(re({...l,baseUrl:_.baseUrl})),f.setEndsAt(_.endsAt)),{url:_.wsUrl,sessionId:_.sessionId,jwt:D,iceServers:_.response.ice_servers,endsAt:_.endsAt}},L,Z=d?async()=>await d()??L:()=>L,F=()=>{let g=f.connectedUrl;return g?Te(g):void 0};f.setConnectionResolver(async()=>{let g=await J(a());return L=g.jwt,g}),f.on("phase",g=>{if(!Ve(g)||f.intentionalDisconnect||e.sessionKey)return;let w=bt(s)?.logicalId;w&&g.sessionId&&w!==g.sessionId||z(s)}),f.on("connected",()=>{f.multiplexer&&p.setTarget(f.multiplexer);let g=f.connectedUrl;g&&m.setDocTransport({wsUrl:g,token:Z,resolveServerUrl:F})});let q=async g=>{let w;try{w=await J(g)}catch(_){if(h){T({status:"unavailable",cause:_});return}if(console.error(`[urun] Failed to create session for ${r}:`,_),z(s),!M&&C&&Et(_))return M=!0,console.warn(`[urun] the resumed session for ${r} was already closed server-side (terminal create echo) \u2014 discarding the stored resumption id and creating a fresh session`),q(a());v&&k(v);let D=_ instanceof Error?_:new Error(String(_)),W=_ instanceof we?_.httpStatus:void 0,x=_ instanceof we?_.code:void 0;f.reportAllocationFailure(D,W,x),T({status:"unavailable",cause:_});return}h||(f.setAuth({jwt:w.jwt,authProvider:e.authProvider,orgId:e.orgId}),f.setConnection({url:w.url,sessionId:w.sessionId,iceServers:w.iceServers}),ye()&&await ke(),L=w.jwt,m.setDocTransport({wsUrl:w.url,token:Z,resolveServerUrl:F}),await f.connect({app:i,functionName:r,args:o}),m.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))};if(m.onPhase(g=>{let w=g?.name;if(w==="live"){X=!0;return}w!=="ended"&&w!=="expired"&&w!=="error"||f.intentionalDisconnect||w==="error"&&g?.error?.kind!=="runtime-failed"||(e.sessionKey||z(s),!X&&C&&!M&&(M=!0,console.warn(`[urun] resumed session ${m.id} for ${r} is closed server-side (${w}) \u2014 discarding the stored resumption id and creating a fresh session`),q(a()).catch(_=>{console.error(`[urun] fresh-session fall-through failed for ${r}:`,_)})))}),q(c).catch(g=>{console.error(`[urun] Failed to connect session for ${r}:`,g)}),e.releaseOnLeave!==!1){let g=rt(()=>{if(h=!0,e.sessionKey||z(s),f.leaveLeg())return;if(f.connectedUrl!==null){f.disconnect();return}f.disconnect();let x=v;x?I(x):y=!0});m.onDisconnect(g);let w,_,D=!1,W=()=>{D||(D=!0,w?.(),_?.())};U.then(x=>{x.status!=="ready"||D||(w=nt(()=>v!==void 0))}),_=m.onPhase(x=>{let j=x?.name;(j==="ended"||j==="expired"||j==="error")&&W()}),D&&_(),m.onDisconnect(W)}return m}}})}var ir="https://api.urun.sh",sr="URUN_DEV";function Ln(){if(typeof process>"u")return!1;let i=process.env?.[sr];if(typeof i!="string")return!1;let e=i.trim().toLowerCase();return e==="1"||e==="true"}var B=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function On(i,e={}){if(!i)throw new B("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=H(e.baseUrl??ir),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata),(e.dev??Ln())&&(n.dev=!0);let o;try{o=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(n)})}catch(p){throw new B(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let s={};try{s=await o.json()}catch{}if(!o.ok){let p=typeof s.message=="string"?s.message:`HTTP ${o.status}`;throw new B(`[urun] client token mint failed: ${p}`,o.status)}let a=typeof s.token=="string"?s.token:"",c=typeof s.org_id=="string"?s.org_id:"",u=typeof s.expires_at=="string"?Date.parse(s.expires_at):Number.NaN,d=typeof s.expires_in=="number"?s.expires_in:void 0;if(!a)throw new B("[urun] client token mint returned no token (control-plane contract violation)",o.status);let l=Number.isFinite(u)?new Date(u):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:l,orgId:c}}var or=3e4,ar="stream:",yt=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 o=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(o.timer),n.error?o.reject(new Error(n.error)):o.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=`${ar}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${ar}${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 o=String(++this._rpcId),s=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),n(new Error(`RPC request "${e}" timed out after ${or}ms`)))},or);this._pendingRpc.set(o,{resolve:r,reject:n,timer:s}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Wn(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 o=new At(n);return new yt(n,o)}var Nn='video/mp4; codecs="avc1.42E01E"';function Fn(i,e){let t=e?.codec??Nn,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,o=URL.createObjectURL(n);r.src=o,n.addEventListener("sourceopen",()=>{let p;try{p=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 p.updating?new Promise(h=>{p.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function v(){try{for(;;){let{done:h,value:y}=await f.read();if(h){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{p.appendBuffer(y)}catch(S){if(S instanceof DOMException&&S.name==="QuotaExceededError"){let T=p.buffered;if(T.length>0){let U=T.start(T.length-1);p.remove(0,U),await m(),p.appendBuffer(y)}else throw S}else throw S}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}v()}),r.play().catch(()=>{});let s=r,a=s.captureStream??s.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),u=c.getTracks(),d=0,l=u.length;if(l===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{d++,d>=l&&URL.revokeObjectURL(o)});return c}function qn(i){return i.status.startsWith("pending_")}var Y=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)}},me=class extends Y{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function $n(i,e,t){let r=t||e||`HTTP ${i}`;return i===401?new me(r,e??"unauthorized"):new Y(r,{status:i,code:e??`http_${i}`})}var We=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let e=await this._request("GET","/balance");if(!e||typeof e!="object"||typeof e.org_id!="string")throw new Y("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let 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),o=await this._resolveToken(),s=await this._fetch(n,e,o);if(s.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,s=await this._fetch(n,e,o))}if(!s.ok){let{code:a,message:c}=await this._readError(s);throw $n(s.status,a,c)}return this._readJson(s)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,s])=>`${encodeURIComponent(o)}=${encodeURIComponent(s)}`).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 me("[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:o}=r;return{code:typeof n=="string"?n:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Bn(i){return new We(i)}var Ne=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 cr(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function jn(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function Vn(i,e){let t=i.getTracks();if(t.length===1&&t[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function kt(i,e){for(let t of[...i.lostListeners])try{t(e)}catch{}}var Fe=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,kt(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 Ne;return t=>e.getUserMedia(t)}async converge(e){for(let s of this.claims.values())s.track&&(s.track.stop(),s.track=null,s.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(s){let a=`one-capture getUserMedia(${cr(r)}) failed`,c=s instanceof Error?s.message:String(s);for(let u of[...this.claims.values()])if(this.claims.delete(u.kind),u.released=!0,u!==e){let d=new Error(`${a} \u2014 ${u.kind} capture lost: ${c||s}`);d.cause=s,kt(u,d)}throw s}let o=[...this.claims.values()].sort((s,a)=>s===e?1:a===e?-1:0);for(let s of o){let a=jn(n,s.kind)[0]??null;if(s.released){a?.stop();continue}if(!a){this.claims.delete(s.kind),s.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${cr(r)}) returned no ${s.kind} track`),{name:"NotFoundError"});if(s===e)throw c;kt(s,c);continue}if(s.track=a,s.stream=Vn(n,a),s!==e)for(let c of[...s.trackListeners])try{c(a,s.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(o){return r.enqueue(async()=>{if(n.released)throw new Error(`${e} capture claim already released`);if(n.constraints=o,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(o){return n.trackListeners.add(o),()=>n.trackListeners.delete(o)},onLost(o){return n.lostListeners.add(o),()=>n.lostListeners.delete(o)}}};return n}},Hn=null;function Gn(){return Hn??=new Fe}var dr="input",Kn=30;function zn(i){let e=i.now??Date.now,t=i.field??dr,r=1e3/Math.max(i.hz??30,.001),n=new Set,o=0,s=0,a=0,c=0,u,d=null,l=!1,p=()=>{if(l)return;u=e(),c+=1;let m={keys:[...n],buttons:o,pointer:{x:s,y:a},seq:c,at:u};try{i.awareness.setLocalStateField(t,m)}catch{}},f=()=>{if(l)return;let m=e();if(u===void 0||m-u>=r){d&&(clearTimeout(d),d=null),p();return}if(d)return;let v=Math.max(r-(m-u),0);d=setTimeout(()=>{d=null,p()},v),d.unref?.()};return{keyDown(m){let v=String(m).toLowerCase();n.has(v)||(n.add(v),f())},keyUp(m){let v=String(m).toLowerCase();n.delete(v)&&f()},setButtons(m){let v=Number.isFinite(m)?Number(m):0;v!==o&&(o=v,f())},movePointer(m,v){let h=Number.isFinite(m)?Number(m):0,y=Number.isFinite(v)?Number(v):0;h===0&&y===0||(s+=h,a+=y,f())},heldKeys(){return[...n]},clear(){l||(n.clear(),o=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(l)return;let m=n.size>0||o!==0;n.clear(),o=0,d&&(clearTimeout(d),d=null),m&&p(),l=!0}}}var Yn=1024,Qn=.92,Xn=262144,Jn=256e3,_t=[.9,.8,.7,.6,.5],ur=.8,Zn=8;function Tt(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 ei(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 pr(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 lr(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 St(i,e,t,r,n){let o=document.createElement("canvas");o.width=e,o.height=t;let s=o.getContext("2d");if(!s)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(s.fillStyle="#fff",s.fillRect(0,0,e,t)),s.drawImage(i,0,0,e,t),await pr(o,r,n)}async function ti(i,e,t,r){let{width:n,height:o}=e,s=await St(i,n,o,t,r);if(s.size<=256e3)return{blob:s,width:n,height:o};if(t==="image/jpeg"){for(let c of _t)if(!(c>=r)&&(s=await St(i,n,o,t,c),s.size<=256e3))return lr(`quality ${r} -> ${c}`,s.size),{blob:s,width:n,height:o}}let a=t==="image/jpeg"?_t[_t.length-1]:r;for(let c=0;c<Zn;c++)if(n=Math.max(16,Math.round(n*ur)),o=Math.max(16,Math.round(o*ur)),s=await St(i,n,o,t,a),s.size<=256e3)return lr(`downscaled to ${n}x${o} @ q${a}`,s.size),{blob:s,width:n,height:o};throw new Error(`this image cannot be sent: even at ${n}x${o} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function ri(i,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:o}=e,s=await ei(i);try{let a=Tt(s.width,s.height,t),c=await ti(s,a,r,n);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:r,width:c.width,height:c.height,source:o}}finally{s.close()}}function ni(i){let e=i instanceof Error?i.name:"",t=i instanceof Error?i.message:String(i);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function ii(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function si(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:o="image/jpeg",quality:s=.92}=e??{},a=Tt(t,r,n),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let u=c.getContext("2d");if(!u)throw new Error("could not prepare the reference image (no 2d canvas context)");o==="image/jpeg"&&(u.fillStyle="#fff",u.fillRect(0,0,a.width,a.height)),u.drawImage(i,0,0,a.width,a.height);let d=await pr(c,o,s);return{bytes:new Uint8Array(await d.arrayBuffer()),type:o,width:a.width,height:a.height,source:"camera"}}var oi=new Set(["w","a","s","d"]),Q=(i,e)=>Math.min(e,Math.max(-e,i));function ai(i={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:n=900,frameRelax:o=.06,maxPan:s=.12,maxLogZoom:a=.22}=i,c=0,u=0,d=0,l=null,p=new Set;return{pointerDelta(f,m){c=Q(c-f*e,s),u=Q(u-m*e,s)},keyDown(f){let m=f.toLowerCase();oi.has(m)&&p.add(m)},keyUp(f){p.delete(f.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let f=1-o;c*=f,u*=f,d*=f},tick(f){if(l===null){l=f;return}let m=Math.max(0,Math.min(100,f-l))/1e3;l=f,p.has("w")&&(d=Q(d+t*m,a)),p.has("s")&&(d=Q(d-t*m,a)),p.has("a")&&(c=Q(c+r*m,s)),p.has("d")&&(c=Q(c-r*m,s));let v=Math.exp(-m*1e3/n);c*=v,u*=v,d*=v},transform(){return{translateX:c,translateY:u,scale:Math.exp(d)}},isIdentity(f=5e-4){return Math.abs(c)<f&&Math.abs(u)<f&&Math.abs(d)<f},reset(){c=0,u=0,d=0,p.clear()}}}export{Lr as ACTIVATION_COLD_BOOT_AFTER_MS,Or as ACTIVATION_DEGRADED_AFTER_MS,Ye as ACTIVATION_HINT_PATH,Mr as ACTIVATION_STILL_AFTER_MS,Ze as ACTIVITY_DOM_EVENTS,Ft as ACTIVITY_FIELD,zr as ACTIVITY_STAMP_MIN_INTERVAL_MS,te as ActivationMonitor,Mn as App,Sr as BACKOFF_BASE_MS,Ar as BACKOFF_MAX_ATTEMPTS,Tr as BACKOFF_MAX_MS,Fe as CaptureController,Ne as CaptureUnavailableError,B as ClientTokenError,We as CreditsClient,Y as CreditsError,me as CreditsUnauthorizedError,Xn as DATA_CHANNEL_MESSAGE_CEILING,tr as DEFAULT_DOC_SYNC_TIMEOUT_MS,ir as DEFAULT_GATEWAY_URL,mr as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Qn as DEFAULT_REFERENCE_JPEG_QUALITY,Yn as DEFAULT_REFERENCE_MAX_SIZE,kr as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Dr as DERIVED_LEG_SEP,R as DGRAM_HEADER_BYTES,jt as FOCUS_FIELD,Qr as FOREGROUND_COALESCE_MS,ae as FrameReassembler,Gr as GENERATION_TICK_EMIT_INTERVAL_MS,Kr as GENERATION_TICK_MAX_EXTRAPOLATION_MS,Kn as INPUT_PRESENCE_DEFAULT_HZ,dr as INPUT_PRESENCE_FIELD,G as InvalidDurationError,Qe as LEGACY_ACTIVATION_HINT_PATH,ze as PLATFORM_DOC_NAME,De as PermanentLockedError,Ie as PinRequiresActiveTempError,ie as PresenceTracker,hr as ProduceAckTimeoutError,Re as RecordingNotFoundError,K as RecordingsClient,P as RecordingsError,ne as RecordingsUnauthorizedError,ve as RequestAbortError,je as RequestCancelledError,$e as RequestDocSyncError,ge as RequestError,qe as RequestTimeoutError,Ce as RetainNotTempError,Ee as RuntimeArtifactNotFoundError,$ as RuntimeArtifactsClient,E as RuntimeArtifactsError,Ae as RuntimeArtifactsUnauthorizedError,xr as SIGNALING_PROTOCOL_VERSION,Ge as STREAM_END,fe as Session,we as SessionAllocationError,fr as SessionEndError,ee as SessionEndUnavailableError,vr as SessionFailedError,Be as StreamDirectionConflict,ue as TransportNegotiator,br as TransportSessionMismatchError,le as TransportSessionSignaling,sr as URUN_DEV_ENV,Bt as USER_ACTIVITY_FIELD,Yr as USER_ACTIVITY_MIN_INTERVAL_MS,qt as VISIBILITY_FIELD,Jn as WIRE_MESSAGE_BUDGET,Gt as WT_CONTROL_FRAME_MAX,zt as WT_DATA_STREAM_VERSION,pe as WebRtcSession,de as WebTransportSession,se as WtControlDecoder,Ue as WtDataStreamParser,Ot as activationHintFrom,ii as cameraCaptureAvailable,si as captureStillFromVideo,Er as computeBackoffDelay,dt as consumeWtDataStreams,et as createActivityTracker,ai as createCameraWarp,On as createClientToken,Bn as createCreditsClient,zn as createInputPresencePublisher,Hr as createRecordingsClient,Nr as createRuntimeArtifactsClient,Wn as createStore,Ke as decodeStreamEnvelope,Ur as derivedLegName,Pr as derivedLegRole,gr as describeSessionFailure,_r as describeSessionPhase,Ir as encodeStreamEnvelope,ot as encodeWtControlFrame,Tt as fitWithin,Xe as isDurationString,qn as isPendingRecording,Rr as isRetryableSessionError,Ve as isServerTerminalPhase,yr as isWakingPhase,it as mediaRecorderChunkSource,ri as normalizeReferenceImage,jr as normalizeRetention,nt as observeLeaveConfirm,tt as observePageLifecycle,rt as observePageTeardown,oe as parseDgramHeader,Cr as prewake,ni as referenceImageErrorMessage,be as releaseSessionBeacon,wr as sessionFailureFromMediaError,Gn as sharedCaptureController,Fn as videoStream,Je as watchGenerationTick,He as whenLive,at as writeDgramHeader};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { g as AppOptions, f as App$1, ae as SessionPhase, ak as SessionStatus, ag as SessionPhaseName, A as AccessTokenOptions, $ as RuntimeArtifact, a0 as RuntimeArtifactDownload, T as Recording, aA as TransportState, a8 as Session$1, C as ChannelEndpoint, ax as TransportSession, h as AttachOptions, a9 as SessionDiagnostic, b as ActivationEvent, aj as SessionStatsSample, z as GenerationTick, X as RecordingsAccessor, a1 as RuntimeArtifactsAccessor, ac as SessionEndResult, al as SessionStream$1, as as StreamDataTransport, ab as SessionDocumentImpl, ar as StreamChunkOptions, m as ChunkReadable, P as Presence, v as DocConnector, x as DocTokenSupplier, w as DocServerUrlResolver, Z as RequestOptions, _ as RequestStreamOptions, aq as StoreOptions, ap as Store, k as ChannelMultiplexer, ad as SessionFailureKind, H as MediaSession, aw as TransportOfferResponse, aF as WtAudioLaneSeam, aG as WtAudioUplinkSeam, aN as WtVideoUplinkSeam, aM as WtDataUplinkSender, aK as WtDataLaneSink } from './stream-data-
|
|
2
|
-
export { c as ActivationState, i as AudioPlayoutOptions, D as DERIVED_LEG_SEP, n as DGRAM_HEADER_BYTES, r as DerivedLegRole, s as DgramHeader, u as DocConnectionState, G as GENERATION_TICK_EMIT_INTERVAL_MS, y as GENERATION_TICK_MAX_EXTRAPOLATION_MS, I as InboundStatsSample, M as MediaChunkBinding, B as MediaChunkSource, E as MediaChunkSourceFactory, F as MediaRecorderChunkSourceOptions, N as NegotiatorDataLaneSeam, J as NegotiatorOptions, K as PresenceState, O as PrewakeOptions, Q as PrewakeResult, R as PrewakeStatus, S as QuicStreamDataTransport, U as RecordingBucket, V as RecordingLifecycle, W as RecordingStatus, Y as ReleaseSessionBeaconOptions, a2 as RuntimeAvailability, a3 as RuntimeWakeDetail, a4 as RuntimeWakeGolden, a5 as RuntimeWakeReasonCode, a6 as SIGNALING_PROTOCOL_VERSION, a7 as STREAM_END, aa as SessionDocument, af as SessionPhaseError, ai as SessionStatsOptions, am as SessionText, an as SignalCarrier, ao as Signaling, at as TransportEstablishedNotify, au as TransportNegotiator, av as TransportOfferRequest, az as TransportSessionSignaling, aB as VideoPlayoutOptions, aC as WT_CONTROL_FRAME_MAX, aD as WT_DATA_STREAM_VERSION, aE as WatchGenerationTickOptions, aH as WtControlDecoder, aI as WtControlMessage, aJ as WtDataEnvelope, aL as WtDataStreamParser, aP as consumeWtDataStreams, aS as decodeStreamEnvelope, aU as derivedLegName, aV as derivedLegRole, aW as encodeStreamEnvelope, aX as encodeWtControlFrame, aY as isPendingRecording, aZ as mediaRecorderChunkSource, a_ as parseDgramHeader, a$ as prewake, b0 as releaseSessionBeacon, b3 as watchGenerationTick, b4 as writeDgramHeader } from './stream-data-
|
|
1
|
+
import { g as AppOptions, f as App$1, ae as SessionPhase, ak as SessionStatus, ag as SessionPhaseName, A as AccessTokenOptions, $ as RuntimeArtifact, a0 as RuntimeArtifactDownload, T as Recording, aA as TransportState, a8 as Session$1, C as ChannelEndpoint, ax as TransportSession, h as AttachOptions, a9 as SessionDiagnostic, b as ActivationEvent, aj as SessionStatsSample, z as GenerationTick, X as RecordingsAccessor, a1 as RuntimeArtifactsAccessor, ac as SessionEndResult, al as SessionStream$1, as as StreamDataTransport, ab as SessionDocumentImpl, ar as StreamChunkOptions, m as ChunkReadable, P as Presence, v as DocConnector, x as DocTokenSupplier, w as DocServerUrlResolver, Z as RequestOptions, _ as RequestStreamOptions, aq as StoreOptions, ap as Store, k as ChannelMultiplexer, ad as SessionFailureKind, H as MediaSession, aw as TransportOfferResponse, aF as WtAudioLaneSeam, aG as WtAudioUplinkSeam, aN as WtVideoUplinkSeam, aM as WtDataUplinkSender, aK as WtDataLaneSink } from './stream-data-Bl4UHVAa.mjs';
|
|
2
|
+
export { c as ActivationState, i as AudioPlayoutOptions, D as DERIVED_LEG_SEP, n as DGRAM_HEADER_BYTES, r as DerivedLegRole, s as DgramHeader, u as DocConnectionState, G as GENERATION_TICK_EMIT_INTERVAL_MS, y as GENERATION_TICK_MAX_EXTRAPOLATION_MS, I as InboundStatsSample, M as MediaChunkBinding, B as MediaChunkSource, E as MediaChunkSourceFactory, F as MediaRecorderChunkSourceOptions, N as NegotiatorDataLaneSeam, J as NegotiatorOptions, K as PresenceState, O as PrewakeOptions, Q as PrewakeResult, R as PrewakeStatus, S as QuicStreamDataTransport, U as RecordingBucket, V as RecordingLifecycle, W as RecordingStatus, Y as ReleaseSessionBeaconOptions, a2 as RuntimeAvailability, a3 as RuntimeWakeDetail, a4 as RuntimeWakeGolden, a5 as RuntimeWakeReasonCode, a6 as SIGNALING_PROTOCOL_VERSION, a7 as STREAM_END, aa as SessionDocument, af as SessionPhaseError, ai as SessionStatsOptions, am as SessionText, an as SignalCarrier, ao as Signaling, at as TransportEstablishedNotify, au as TransportNegotiator, av as TransportOfferRequest, az as TransportSessionSignaling, aB as VideoPlayoutOptions, aC as WT_CONTROL_FRAME_MAX, aD as WT_DATA_STREAM_VERSION, aE as WatchGenerationTickOptions, aH as WtControlDecoder, aI as WtControlMessage, aJ as WtDataEnvelope, aL as WtDataStreamParser, aP as consumeWtDataStreams, aS as decodeStreamEnvelope, aU as derivedLegName, aV as derivedLegRole, aW as encodeStreamEnvelope, aX as encodeWtControlFrame, aY as isPendingRecording, aZ as mediaRecorderChunkSource, a_ as parseDgramHeader, a$ as prewake, b0 as releaseSessionBeacon, b3 as watchGenerationTick, b4 as writeDgramHeader } from './stream-data-Bl4UHVAa.mjs';
|
|
3
3
|
import 'yjs';
|
|
4
4
|
import 'y-protocols/awareness';
|
|
5
5
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { g as AppOptions, f as App$1, ae as SessionPhase, ak as SessionStatus, ag as SessionPhaseName, A as AccessTokenOptions, $ as RuntimeArtifact, a0 as RuntimeArtifactDownload, T as Recording, aA as TransportState, a8 as Session$1, C as ChannelEndpoint, ax as TransportSession, h as AttachOptions, a9 as SessionDiagnostic, b as ActivationEvent, aj as SessionStatsSample, z as GenerationTick, X as RecordingsAccessor, a1 as RuntimeArtifactsAccessor, ac as SessionEndResult, al as SessionStream$1, as as StreamDataTransport, ab as SessionDocumentImpl, ar as StreamChunkOptions, m as ChunkReadable, P as Presence, v as DocConnector, x as DocTokenSupplier, w as DocServerUrlResolver, Z as RequestOptions, _ as RequestStreamOptions, aq as StoreOptions, ap as Store, k as ChannelMultiplexer, ad as SessionFailureKind, H as MediaSession, aw as TransportOfferResponse, aF as WtAudioLaneSeam, aG as WtAudioUplinkSeam, aN as WtVideoUplinkSeam, aM as WtDataUplinkSender, aK as WtDataLaneSink } from './stream-data-
|
|
2
|
-
export { c as ActivationState, i as AudioPlayoutOptions, D as DERIVED_LEG_SEP, n as DGRAM_HEADER_BYTES, r as DerivedLegRole, s as DgramHeader, u as DocConnectionState, G as GENERATION_TICK_EMIT_INTERVAL_MS, y as GENERATION_TICK_MAX_EXTRAPOLATION_MS, I as InboundStatsSample, M as MediaChunkBinding, B as MediaChunkSource, E as MediaChunkSourceFactory, F as MediaRecorderChunkSourceOptions, N as NegotiatorDataLaneSeam, J as NegotiatorOptions, K as PresenceState, O as PrewakeOptions, Q as PrewakeResult, R as PrewakeStatus, S as QuicStreamDataTransport, U as RecordingBucket, V as RecordingLifecycle, W as RecordingStatus, Y as ReleaseSessionBeaconOptions, a2 as RuntimeAvailability, a3 as RuntimeWakeDetail, a4 as RuntimeWakeGolden, a5 as RuntimeWakeReasonCode, a6 as SIGNALING_PROTOCOL_VERSION, a7 as STREAM_END, aa as SessionDocument, af as SessionPhaseError, ai as SessionStatsOptions, am as SessionText, an as SignalCarrier, ao as Signaling, at as TransportEstablishedNotify, au as TransportNegotiator, av as TransportOfferRequest, az as TransportSessionSignaling, aB as VideoPlayoutOptions, aC as WT_CONTROL_FRAME_MAX, aD as WT_DATA_STREAM_VERSION, aE as WatchGenerationTickOptions, aH as WtControlDecoder, aI as WtControlMessage, aJ as WtDataEnvelope, aL as WtDataStreamParser, aP as consumeWtDataStreams, aS as decodeStreamEnvelope, aU as derivedLegName, aV as derivedLegRole, aW as encodeStreamEnvelope, aX as encodeWtControlFrame, aY as isPendingRecording, aZ as mediaRecorderChunkSource, a_ as parseDgramHeader, a$ as prewake, b0 as releaseSessionBeacon, b3 as watchGenerationTick, b4 as writeDgramHeader } from './stream-data-
|
|
1
|
+
import { g as AppOptions, f as App$1, ae as SessionPhase, ak as SessionStatus, ag as SessionPhaseName, A as AccessTokenOptions, $ as RuntimeArtifact, a0 as RuntimeArtifactDownload, T as Recording, aA as TransportState, a8 as Session$1, C as ChannelEndpoint, ax as TransportSession, h as AttachOptions, a9 as SessionDiagnostic, b as ActivationEvent, aj as SessionStatsSample, z as GenerationTick, X as RecordingsAccessor, a1 as RuntimeArtifactsAccessor, ac as SessionEndResult, al as SessionStream$1, as as StreamDataTransport, ab as SessionDocumentImpl, ar as StreamChunkOptions, m as ChunkReadable, P as Presence, v as DocConnector, x as DocTokenSupplier, w as DocServerUrlResolver, Z as RequestOptions, _ as RequestStreamOptions, aq as StoreOptions, ap as Store, k as ChannelMultiplexer, ad as SessionFailureKind, H as MediaSession, aw as TransportOfferResponse, aF as WtAudioLaneSeam, aG as WtAudioUplinkSeam, aN as WtVideoUplinkSeam, aM as WtDataUplinkSender, aK as WtDataLaneSink } from './stream-data-Bl4UHVAa.js';
|
|
2
|
+
export { c as ActivationState, i as AudioPlayoutOptions, D as DERIVED_LEG_SEP, n as DGRAM_HEADER_BYTES, r as DerivedLegRole, s as DgramHeader, u as DocConnectionState, G as GENERATION_TICK_EMIT_INTERVAL_MS, y as GENERATION_TICK_MAX_EXTRAPOLATION_MS, I as InboundStatsSample, M as MediaChunkBinding, B as MediaChunkSource, E as MediaChunkSourceFactory, F as MediaRecorderChunkSourceOptions, N as NegotiatorDataLaneSeam, J as NegotiatorOptions, K as PresenceState, O as PrewakeOptions, Q as PrewakeResult, R as PrewakeStatus, S as QuicStreamDataTransport, U as RecordingBucket, V as RecordingLifecycle, W as RecordingStatus, Y as ReleaseSessionBeaconOptions, a2 as RuntimeAvailability, a3 as RuntimeWakeDetail, a4 as RuntimeWakeGolden, a5 as RuntimeWakeReasonCode, a6 as SIGNALING_PROTOCOL_VERSION, a7 as STREAM_END, aa as SessionDocument, af as SessionPhaseError, ai as SessionStatsOptions, am as SessionText, an as SignalCarrier, ao as Signaling, at as TransportEstablishedNotify, au as TransportNegotiator, av as TransportOfferRequest, az as TransportSessionSignaling, aB as VideoPlayoutOptions, aC as WT_CONTROL_FRAME_MAX, aD as WT_DATA_STREAM_VERSION, aE as WatchGenerationTickOptions, aH as WtControlDecoder, aI as WtControlMessage, aJ as WtDataEnvelope, aL as WtDataStreamParser, aP as consumeWtDataStreams, aS as decodeStreamEnvelope, aU as derivedLegName, aV as derivedLegRole, aW as encodeStreamEnvelope, aX as encodeWtControlFrame, aY as isPendingRecording, aZ as mediaRecorderChunkSource, a_ as parseDgramHeader, a$ as prewake, b0 as releaseSessionBeacon, b3 as watchGenerationTick, b4 as writeDgramHeader } from './stream-data-Bl4UHVAa.js';
|
|
3
3
|
import 'yjs';
|
|
4
4
|
import 'y-protocols/awareness';
|
|
5
5
|
|