@urun-sh/core 0.2.15 → 0.2.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{B as Ee,C as xe,D as Me,E as Oe,F as Ue,a as Pe,b as F,c as B,d as ie,e as oe,f as ae,g as et,h as tt,i as G,j as ce,k as rt,l as nt,m as st,n as T,o as it,p as ot,q as ue,r as at,s as K,u as z,v as Ce,x as Ie,z as V}from"./chunk-DK75BVOK.mjs";var ct="session-api.prod.cloud.urun.sh",ut=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function b(r){return r.trim().replace(/\/+$/,"")}function Y(r,e){let t=[],n=s=>{if(!s)return;let i=b(s);i&&!t.includes(i)&&t.push(i)};n(r);for(let s of e??[])n(s);for(let s of At(r))n(s);return t}function Le(r){if(typeof r!="string"||r.length===0)return null;let e=new Date(r);return Number.isFinite(e.getTime())?e:null}var dt=120,lt=1e3,pt=20,mt=5,ft=500,De=1e4,gt=3;function ht(r){if(!r)return null;try{let e=new URL(r),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return b(`${e.origin}${t}`)}catch{return null}}async function qe(r){let e=Y(r.baseUrl,r.fallbackUrls),t=null,n=e.length>1;for(let s of e)try{return await wt(s,r,{pollAttempts:dt,retryAfterLimitMs:n?lt:void 0})}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof P)throw t}throw t??new Error("[urun] session allocation failed")}async function wt(r,e,t){let n,s,i,o=r,a=0,m=new Set,u=Date.now()+t.pollAttempts*De;for(let c=0;c<t.pollAttempts;c++){s=i??await W(e),i=void 0;let h=Math.max(1,Math.min(pt,Math.floor((u-Date.now())/1e3))),l=!!n,g=Date.now(),d=n?await fetch(`${o}/api/session-requests/${encodeURIComponent(n)}?wait_s=${h}`,{headers:H(e,s),signal:bt((h+mt)*1e3)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...H(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(yt(e))});if(!n&&(d.status===307||d.status===308)){let y=ht(d.headers.get("location"));if(y&&y!==o&&a<gt){a+=1,o=y;continue}throw new T(`[urun] session create redirected from ${o} without a usable target`,{httpStatus:d.status})}let p=await de(d);if(d.ok&&(p.status==="allocated"||!p.status&&!!p.session_id)&&!!p.session_id){let y=p.session_id;if(!p.ws_url)throw new P(`[urun] gateway allocated session ${y} without ws_url`);if(!Ne(p.ws_url))throw new P(`[urun] gateway allocated session ${y} with non-absolute ws_url`);return{baseUrl:o,sessionId:y,wsUrl:p.ws_url,endsAt:Le(p.ends_at),response:p}}if(d.status===202||p.status==="pending"||p.status==="queued"||p.queued){if(n=p.request_id||n,!n)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(_t(p,n))}catch{}let y=Date.now()-g<ft;l&&y&&await kt(St(d,p,t.retryAfterLimitMs));continue}if((d.status===401||d.status===403)&&e.getAccessToken){let y=s??"";m.add(y);let S=await W(e,{forceRefresh:!0,reason:"unauthorized"});if(S&&!m.has(S)){i=S,n=void 0;continue}}let _=p.error_message||p.error_code||`HTTP ${d.status}`;throw new T(`[urun] session allocation failed at ${o}: ${_}`,{httpStatus:d.status})}throw new T(`[urun] timed out waiting for session allocation at ${o}`)}function H(r,e){let t={"X-Tenant-Id":r.orgId,"X-Auth-Provider":r.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function W(r,e){return r.getAccessToken?await r.getAccessToken(e)??void 0:r.jwt}function yt(r){return{app:r.app,function:r.functionName,gpus:1,idempotency_key:r.idempotencyKey}}async function je(r){let e=Y(r.baseUrl,r.fallbackUrls),t=null;for(let n of e)try{let s={baseUrl:n,app:"",functionName:"",orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider,idempotencyKey:""},i=await W(s),o=await fetch(`${b(n)}/api/sessions/${encodeURIComponent(r.sessionId)}/viewer-connect`,{headers:H(s,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${r.sessionId} failed: HTTP ${o.status}`);let a=await de(o);if(!a.ws_url||!Ne(a.ws_url))throw new P(`[urun] viewer-connect returned no usable ws_url for ${r.sessionId}`);return{baseUrl:b(n),sessionId:r.sessionId,wsUrl:a.ws_url,endsAt:Le(a.ends_at),response:a}}catch(s){if(t=s instanceof Error?s:new Error(String(s)),t instanceof P)throw t}throw t??new Error("[urun] viewer-connect failed")}async function vt(r){try{let e=b(r.baseUrl),t=await W(r),n=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...H(r,t),"Content-Type":"application/json"},body:JSON.stringify({app:r.app,function:r.functionName})});if(n.status===404)return{status:"unknown-app"};if(!n.ok)return{status:"unavailable"};let s=await de(n),i={status:s.status==="prebound"?"prebound":"warming"};return typeof s.expires_at=="string"&&(i.expiresAt=s.expires_at),typeof s.warm_capable=="boolean"&&(i.warmCapable=s.warm_capable),i}catch(e){return console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function de(r){try{let e=await r.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function _t(r,e){let t={status:r.status==="queued"||r.queued?"queued":"pending",requestId:e};typeof r.queue_position=="number"&&typeof r.queue_depth=="number"&&(t.queue={position:r.queue_position,depth:r.queue_depth});let n=r.runtime_state;return(n==="unavailable"||n==="starting"||n==="busy")&&(t.runtime={state:n},typeof r.runtime_reason=="string"&&r.runtime_reason.length>0&&(t.runtime.reason=r.runtime_reason)),t}function St(r,e,t){let n=Number(r.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??n),i=t??De;return Number.isFinite(s)&&s>0?Math.min(s*1e3,i):1e3}function kt(r){return new Promise(e=>setTimeout(e,r))}function bt(r){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(r):void 0}var P=class extends Error{};function Ne(r){try{let e=new URL(r);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function At(r){try{return new URL(r).hostname!==ct?[]:ut}catch{return[]}}var v=class extends Error{status;code;constructor(e,t,n=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=n,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},J=class extends v{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},X=class extends v{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function L(r){return{baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}function Rt(r){return new C(r)}var C=class{_options;constructor(e){this._options=e}async list(e){let n=Fe(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new v("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map($e)}async getDownloadUrl(e,t){let n=Fe(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=n.download_url;if(typeof s!="string"||!Pt(s))throw new v("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:$e(n.artifact),downloadUrl:s}}async _request(e,t){let n=Y(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let i of n)try{return await this._requestFromBase(i,e,t)}catch(o){if(s=o instanceof Error?o:new Error(String(o)),s instanceof v&&Ct(s.status))throw s}throw s??new v("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let s=`${b(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${n}`,i=await this._resolveToken(),o=await fetch(s,{method:"GET",headers:this._headers(i)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await fetch(s,{method:"GET",headers:this._headers(i)}))}if(!o.ok){let{code:a,message:m}=await this._readError(o,e);throw It(o.status,a,m)}try{return await o.json()}catch(a){throw new v(`[urun] runtime artifacts: invalid JSON response from ${b(e)}`,0,"bad_response",a)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let n=b(t);try{let i=(await e.json()).error;if(i&&typeof i=="object"){let{code:o,message:a}=i;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${n}: ${a}`:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}};function $e(r){if(!r||typeof r!="object")throw new v("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=r,t=A(e,"artifact_id")||A(e,"id"),n=A(e,"filename"),s=A(e,"kind"),i=A(e,"status")||"ready",o=Tt(e,"size_bytes"),a=A(e,"sha256");if(!t||!n||!s||o==null||!a)throw new v("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:n,contentType:A(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:A(e,"created_at"),expiresAt:A(e,"expires_at")}}function A(r,e){let t=r[e];return typeof t=="string"&&t.length>0?t:void 0}function Tt(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function Pt(r){try{return new URL(r).protocol==="https:"}catch{return!1}}function Ct(r){return r===401||r===403}function It(r,e,t){return r===401?new J(t,e):r===404?new X(t,e):new v(t,r,e)}function Fe(r){if(!r||typeof r!="object"||Array.isArray(r))throw new v("[urun] runtime artifacts: malformed response",0,"bad_response");return r}var k=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)}},D=class extends k{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Z=class extends k{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Q=class extends k{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)}},ee=class extends k{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)}},te=class extends k{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)}},x=class extends k{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",n=400){super(e,{status:n,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function le(r){return/^(\d+[smhdw])+$/.test(r)}function Et(r){if(r==="pin")return{action:"pin"};if(le(r))return{action:"retain",duration:r};throw new x(`[urun] recordings: "${r}" is not a duration or "pin"`)}function xt(r,e,t){let n=t||e||`HTTP ${r}`;if(r===401)return new D(n,e??"unauthorized");if(r===404)return new Z(n,e??"not_found");if(r===400)return new x(n,e??"bad_request",400);if(r===409)switch(e){case"retain_not_temp":return new Q(n,e);case"pin_requires_active_temp":return new ee(n,e);case"permanent_locked":return new te(n,e)}return new k(n,{status:r,code:e??`http_${r}`})}var M=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let n=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(n)?n:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!le(t))throw new x(`[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 k("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let s=this._buildUrl(t,n.params),i=await this._resolveToken(),o=await this._fetch(s,e,i,n.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i,n.body))}if(!o.ok){let{code:a,message:m}=await this._readError(o);throw xt(o.status,a,m)}return this._readJson(o)}_buildUrl(e,t){let n=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(n+=`?${s}`),n}_fetch(e,t,n,s){let i={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(i["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:i};return s!==void 0&&(i["Content-Type"]="application/json",o.body=JSON.stringify(s)),fetch(e,o)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new D("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let n=(await e.json()).error;if(n&&typeof n=="object"){let{code:s,message:i}=n;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Mt(r){return new M(r)}var Be="activity",Ot=15e3,pe=["pointerdown","pointermove","keydown","wheel","touchstart"];function me(r){let e=r.now??Date.now,t=r.windowTarget!==void 0?r.windowTarget:typeof window<"u"?window:null,n=r.documentTarget!==void 0?r.documentTarget:typeof document<"u"?document:null,s=!1,i,o=()=>{if(s)return;let c=e();if(!(i!==void 0&&c-i<15e3)){i=c;try{r.awareness.setLocalStateField(Be,{at:c})}catch{}}},a=()=>o(),m=()=>{(!n||n.visibilityState===void 0||n.visibilityState==="visible")&&o()};if(t)for(let c of pe)t.addEventListener(c,a,{passive:!0,capture:!0});n&&n.addEventListener("visibilitychange",m);let u=null;return r.isProducing&&(u=setInterval(()=>{if(!s)try{r.isProducing?.()&&o()}catch{}},15e3),u.unref?.()),o(),{touch:o,dispose(){if(!s){if(s=!0,t)for(let c of pe)t.removeEventListener(c,a,{capture:!0});n&&n.removeEventListener("visibilitychange",m),u&&(clearInterval(u),u=null)}}}}var Ut=250;function fe(r){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let n=Date.now();n-e<250||(e=n,r())};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)}}var Ge="video/mp4";function ge(r,e={}){let t=e.timesliceMs??1e3,n=null,s=null,i=!1,o=(a,m,u)=>{let c=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!c)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let h=e.mimeType??(typeof c.isTypeSupported=="function"&&c.isTypeSupported(Ge)?Ge:void 0),l=new MediaStream([a]),g=new c(l,h?{mimeType:h}:void 0);n=g;let d=Promise.resolve();g.ondataavailable=p=>{let w=p.data;i||!w||w.size===0||(d=d.then(async()=>{let _=new Uint8Array(await w.arrayBuffer());i||m(_)}))},g.onstop=()=>{d.then(()=>{i||u()})},g.onerror=()=>{d.then(()=>{i||u()})},g.start(t)};return{start(a,m){if(n||i)return;let u=r.track();if(u){o(u,a,m);return}s=r.onTrack(c=>{!c||n||i||(s?.(),s=null,o(c,a,m))})},stop(){if(i)return;i=!0,s?.(),s=null;let a=n;if(n=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Lt(r){let e=r;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=r.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 Ke(r,e){let t=null,n=!1,s=!1,i=new ReadableStream({pull(o){n||(n=!0,t=r(e),t.start(a=>{if(!s)try{o.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{o.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Lt(i)}var Dt=new Set;function ye(r){if(r.functionsUrl)return{functionsUrl:r.functionsUrl,orgId:r.orgId,apiKey:r.apiKey,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}var qt="rpc",Ve=3e4,jt="rpc-resp";function Nt(r){return`${jt}:${r}`}function he(){return Ce()}function $t(r){if(r&&typeof r=="object"){let e=r.error;if(e&&typeof e=="object"){let{message:t,code:n}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof n=="string"?n:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof r=="string"?r:JSON.stringify(r)}}function Ft(r,e,t,n,s,i,o,a,m,u){let c=[],h=null,l=!1,g=null,d=!1,p,w,_=new Promise((f,R)=>{p=f,w=R});_.catch(()=>{});let y=o(),S=null,O=null,U=null,j=null,N=!0,Se=()=>{U&&(clearTimeout(U),U=null),j&&(j(),j=null)},ke=!1,be=()=>{ke||!d||(ke=!0,r.set({rpc:{[e]:null}}))},$=()=>{N=!1,Se(),S?.(),S=null,O?.(),O=null,a?.removeEventListener("abort",Re),y.dispose(),be()},se=()=>{if(h){if(c.length>0){let f=h;h=null,f.resolve({value:c.shift(),done:!1})}else if(g!==null){let f=h;h=null,f.reject(g)}else if(l){let f=h;h=null,f.resolve({value:void 0,done:!0})}}},Xe=f=>{l||(c.push(f),se())},I=f=>{l||(g=f,l=!0,w(f),$(),se())},Ae=f=>{l||(l=!0,p(f),$(),se())},Re=()=>{let f=a?.reason;I(f instanceof B?f:new G(e))},Ze=f=>{if(!(l||!f||typeof f!="object"))switch(be(),f.t){case"delta":typeof f.delta=="string"&&Xe(f.delta);break;case"response":Ae(f.body);break;case"error":{let{message:R,code:E}=$t(f.body);I(new B(R,{requestId:e,code:f.code??E}));break}}},Qe=()=>{let f=y.messages()[Symbol.asyncIterator]();S=()=>{f.return?.(void 0)};let R=()=>{N&&f.next().then(E=>{if(N){if(E.done){l||Ae(void 0);return}Ze(E.value),R()}},E=>{N&&I(E)})};R()},Te=()=>{if(!d){if(d=!0,a){if(a.aborted){I(new G(e));return}a.addEventListener("abort",Re,{once:!0})}O=m?.(f=>I(f))??null,Qe(),r.set({rpc:{[e]:{args:t,respond_on:n,consumer_id:s,stream:i}}}),u&&u>0&&!r.synced&&(U=setTimeout(()=>{U=null,!l&&!r.synced&&I(new oe(u,e))},u),j=r.onSynced(()=>Se()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Te(),c.length>0)return Promise.resolve({value:c.shift(),done:!1});if(g!==null){let f=g;return g=null,Promise.reject(f)}return l?Promise.resolve({value:void 0,done:!0}):new Promise((f,R)=>{h={resolve:f,reject:R}})},return(){return l||(l=!0,p(void 0),$()),Promise.resolve({value:void 0,done:!0})},throw(f){return l||(l=!0,w(f),$()),Promise.reject(f)}}}},body:_,start:Te}}function ze(r){if(r&&typeof r=="object"){let{epoch:e,by:t}=r,n={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(n.by=t),n}}function Bt(r,e){let n=r.get("streams")?.[e];if(!n||typeof n!="object")return null;let{kind:s,rt:i,br:o}=n,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let m=ze(i);m&&(a.rt=m);let u=ze(o);return u&&(a.br=u),a}var we=class{constructor(e,t,n,s,i){this._name=e;this._transport=t;this._streamData=n;this._controlDoc=s;this._onActivity=i;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],n=null,s=!1,i={push(a){if(!s)if(n){let m=n;n=null,m({value:a,done:!1})}else t.push(a)},end(){if(s=!0,n){let a=n;n=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(i);let o=()=>{s=!0,e._messageConsumers.delete(i)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{n=a})},return(){return o(),Promise.resolve({value:void 0,done:!0})}}}}}_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._track}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),n=Bt(t,this._name),s=n?.br;if(s?.by==="runtime")throw new ae(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};n?.rt&&(i.rt=n.rt);let o=n?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??ge;return Ke(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,n)=>{t===this._name&&e(n)})}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n?.delete(t),n?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0});let t=this._handlers.get("track");if(t)for(let n of t)n(e)}},q=class r{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Me;_streamData;_presence=null;_activity=null;_activeRequests=new Set;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_lifecycleUnsub=null;constructor(e,t,n,s,i){this._sessionId=e,this._multiplexer=t,this._transport=n,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=Ie(n),this._wireControlDocIncarnation(),this._lifecycleUnsub=fe(()=>this.recover()),this._activity=me({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let n=await je({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new F,o=new V({url:n.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:n.response.ice_servers}),a=new r(e,i,o,ye(t),L({...t,baseUrl:n.baseUrl}));return o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:n.wsUrl,sessionId:e,iceServers:n.response.ice_servers}),o.setEndsAt(n.endsAt),K()&&await z(),a.setDocTransport({wsUrl:n.wsUrl,token:s}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}whenLive(e){return ue(this,e)}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 M(e);return this._recordingsAccessor={list:n=>t.list(n??this._sessionId),get:n=>t.get(n),retain:(n,s)=>t.retain(n,s),pin:n=>t.pin(n),unpin:n=>t.unpin(n),permanent:n=>t.permanent(n),delete:n=>t.delete(n)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new C(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new C(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let n of this._docs.values())n.setSessionId(e)}stream(e){let t=this._streams.get(e);return t||(t=new we(e,this._transport,this._streamData,()=>this.doc("control"),()=>this._activity?.touch()),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new Oe(e,this._sessionId,Dt.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Ue(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){this.connectDocs(xe({serverUrl:Ee(e.wsUrl),sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket}))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let n=he(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;i=setTimeout(()=>s.abort(new ie(a,n)),a)}let o=this._consumeResponse(n,e,!1,s.signal);return o.start(),o.body.finally(()=>{i&&clearTimeout(i)})}_consumeResponse(e,t,n,s,i){this._activity?.touch();let o=this.doc(qt),a=Nt(e);return Ft(o,e,t,a,this._streamData.consumerId,n,()=>this.stream(a),s,m=>(this._activeRequests.add(m),()=>this._activeRequests.delete(m)),i??Ve)}requestStream(e,t={}){let n=he();return this._consumeResponse(n,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let n=he(),s=this._consumeResponse(n,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}disconnect(){this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._activity?.dispose(),this._activity=null,this._recoveryHooks.clear();let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new ce)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};var Gt=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Kt(r,e){return new Proxy({},{get(t,n){if(!(Gt.has(n)||typeof n!="string"))return s=>{let i=s??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),m=new F,u=new V({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),c=new q(a,m,u,ye(e),L(e)),h=async l=>{let g=await qe({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:r,functionName:n,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:l,onAdmission:p=>u.reportAdmission(p)}),d=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return c.setSessionId(g.sessionId),c.setArtifactsAuth(L({...e,baseUrl:g.baseUrl})),u.setEndsAt(g.endsAt),{url:g.wsUrl,sessionId:g.sessionId,jwt:d,iceServers:g.response.ice_servers,endsAt:g.endsAt}};return u.setConnectionResolver(()=>h(o())),u.on("connected",()=>{u.multiplexer&&m.setTarget(u.multiplexer)}),(async()=>{let l;try{l=await h(a)}catch(g){console.error(`[urun] Failed to create session for ${n}:`,g);let d=g instanceof Error?g:new Error(String(g)),p=g instanceof T?g.httpStatus:void 0;u.reportAllocationFailure(d,p);return}u.setAuth({jwt:l.jwt,authProvider:e.authProvider,orgId:e.orgId}),u.setConnection({url:l.url,sessionId:l.sessionId,iceServers:l.iceServers}),K()&&await z(),c.setDocTransport({wsUrl:l.url,token:l.jwt}),await u.connect({app:r,functionName:n,args:i})})().catch(l=>{console.error(`[urun] Failed to connect session for ${n}:`,l)}),c}}})}var He=3e4,We="stream:",ve=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",n=>{let s;try{s=JSON.parse(typeof n.data=="string"?n.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let i=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(i.timer),s.error?i.reject(new Error(s.error)):i.resolve(s.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let n=`${We}${e}`;return this._multiplexer.on(n,s=>{t(s)})}emit(e,t){let n=`${We}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(n,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((n,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),s(new Error(`RPC request "${e}" timed out after ${He}ms`)))},He);this._pendingRpc.set(i,{resolve:n,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function zt(r){let n=`${r.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(r.orgId)}`,s=new WebSocket(n);(r.jwt||r.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:r.orgId,jwt:r.jwt,authProvider:r.authProvider,apiKey:r.apiKey}))});let i=new Pe(s);return new ve(s,i)}var Vt='video/mp4; codecs="avc1.42E01E"';function Ht(r,e){let t=e?.codec??Vt,n=document.createElement("video");n.muted=!0,n.playsInline=!0;let s=new MediaSource,i=URL.createObjectURL(s);n.src=i,s.addEventListener("sourceopen",()=>{let l;try{l=s.addSourceBuffer(t)}catch(w){throw w instanceof DOMException&&w.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).`):w}let g=r.getReader();function d(){return l.updating?new Promise(w=>{l.addEventListener("updateend",()=>w(),{once:!0})}):Promise.resolve()}async function p(){try{for(;;){let{done:w,value:_}=await g.read();if(w){await d(),s.readyState==="open"&&s.endOfStream();return}await d();try{l.appendBuffer(_)}catch(y){if(y instanceof DOMException&&y.name==="QuotaExceededError"){let S=l.buffered;if(S.length>0){let O=S.start(S.length-1);l.remove(0,O),await d(),l.appendBuffer(_)}else throw y}else throw y}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}p()}),n.play().catch(()=>{});let o=n,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let m=a.call(n),u=m.getTracks(),c=0,h=u.length;if(h===0)n.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let l of u)l.addEventListener("ended",()=>{c++,c>=h&&URL.revokeObjectURL(i)});return m}function Wt(r){return r.status.startsWith("pending_")}var re=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 Ye(r){let e=[];return r.audio&&e.push("audio"),r.video&&e.push("video"),e.join("+")}function Yt(r,e){return e==="audio"?r.getAudioTracks():r.getVideoTracks()}function Jt(r,e){let t=r.getTracks();if(t.length===1&&t[0]===e)return r;try{return new MediaStream([e])}catch{return r}}function _e(r,e){for(let t of[...r.lostListeners])try{t(e)}catch{}}var ne=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let n=this.claims.get(e);n&&(this.claims.delete(e),n.released=!0,n.track=null,n.stream=null,_e(n,new Error(`${e} capture claim superseded by a newer claim`)));let s=this.createState(e,t);return this.claims.set(e,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new re;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),n={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await t(n)}catch(o){let a=`one-capture getUserMedia(${Ye(n)}) failed`,m=o instanceof Error?o.message:String(o);for(let u of[...this.claims.values()])if(this.claims.delete(u.kind),u.released=!0,u!==e){let c=new Error(`${a} \u2014 ${u.kind} capture lost: ${m||o}`);c.cause=o,_e(u,c)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of i){let a=Yt(s,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let m=Object.assign(new Error(`one-capture getUserMedia(${Ye(n)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw m;_e(o,m);continue}if(o.track=a,o.stream=Jt(s,a),o!==e)for(let m of[...o.trackListeners])try{m(a,o.stream)}catch{}}}createState(e,t){let n=this,s={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return s.track},get stream(){return s.stream},update(i){return n.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=i,await n.converge(s),!s.track)throw new Error(`${e} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,n.claims.get(e)===s&&n.claims.delete(e),s.track?.stop(),s.track=null,s.stream=null)},onTrack(i){return s.trackListeners.add(i),()=>s.trackListeners.delete(i)},onLost(i){return s.lostListeners.add(i),()=>s.lostListeners.delete(i)}}};return s}},Xt=null;function Zt(){return Xt??=new ne}var Je="input",Qt=30;function er(r){let e=r.now??Date.now,t=r.field??Je,n=1e3/Math.max(r.hz??30,.001),s=new Set,i=0,o=0,a=0,m=0,u,c=null,h=!1,l=()=>{if(h)return;u=e(),m+=1;let d={keys:[...s],buttons:i,pointer:{x:o,y:a},seq:m,at:u};try{r.awareness.setLocalStateField(t,d)}catch{}},g=()=>{if(h)return;let d=e();if(u===void 0||d-u>=n){c&&(clearTimeout(c),c=null),l();return}if(c)return;let p=Math.max(n-(d-u),0);c=setTimeout(()=>{c=null,l()},p),c.unref?.()};return{keyDown(d){let p=String(d).toLowerCase();s.has(p)||(s.add(p),g())},keyUp(d){let p=String(d).toLowerCase();s.delete(p)&&g()},setButtons(d){let p=Number.isFinite(d)?Number(d):0;p!==i&&(i=p,g())},movePointer(d,p){let w=Number.isFinite(d)?Number(d):0,_=Number.isFinite(p)?Number(p):0;w===0&&_===0||(o+=w,a+=_,g())},heldKeys(){return[...s]},clear(){h||(s.clear(),i=0,c&&(clearTimeout(c),c=null),l())},dispose(){if(h)return;let d=s.size>0||i!==0;s.clear(),i=0,c&&(clearTimeout(c),c=null),d&&l(),h=!0}}}export{pe as ACTIVITY_DOM_EVENTS,Be as ACTIVITY_FIELD,Ot as ACTIVITY_STAMP_MIN_INTERVAL_MS,Kt as App,ne as CaptureController,re as CaptureUnavailableError,Ve as DEFAULT_DOC_SYNC_TIMEOUT_MS,et as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,ot as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Ut as FOREGROUND_COALESCE_MS,Qt as INPUT_PRESENCE_DEFAULT_HZ,Je as INPUT_PRESENCE_FIELD,x as InvalidDurationError,te as PermanentLockedError,ee as PinRequiresActiveTempError,tt as ProduceAckTimeoutError,Z as RecordingNotFoundError,M as RecordingsClient,k as RecordingsError,D as RecordingsUnauthorizedError,G as RequestAbortError,ce as RequestCancelledError,oe as RequestDocSyncError,B as RequestError,ie as RequestTimeoutError,Q as RetainNotTempError,X as RuntimeArtifactNotFoundError,C as RuntimeArtifactsClient,v as RuntimeArtifactsError,J as RuntimeArtifactsUnauthorizedError,q as Session,T as SessionAllocationError,nt as SessionFailedError,ae as StreamDirectionConflict,me as createActivityTracker,er as createInputPresencePublisher,Mt as createRecordingsClient,Rt as createRuntimeArtifactsClient,zt as createStore,rt as describeSessionFailure,at as describeSessionPhase,le as isDurationString,Wt as isPendingRecording,it as isWakingPhase,ge as mediaRecorderChunkSource,Et as normalizeRetention,fe as observePageLifecycle,vt as prewake,st as sessionFailureFromMediaError,Zt as sharedCaptureController,Ht as videoStream,ue as whenLive};
1
+ import{B as te,D as We,E as Be,F as He,G as Ke,H as Ve,a as Ne,b as Y,c as L,d as M,e as J,f as me,g as fe,h as he,i as ft,j as ht,k as X,l as ge,m as gt,n as wt,o as vt,p as P,q as yt,r as bt,s as we,t as St,u as Q,w as Z,x as ee,z as $e}from"./chunk-UNVRVZHL.mjs";var kt="session-api.prod.cloud.urun.sh",_t=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function _(n){return n.trim().replace(/\/+$/,"")}function re(n,e){let t=[],r=s=>{if(!s)return;let i=_(s);i&&!t.includes(i)&&t.push(i)};r(n);for(let s of e??[])r(s);for(let s of Ft(n))r(s);return t}async function Ge(n){try{let e=await F(n),t=await fetch(`${_(n.baseUrl)}/api/session-requests/${encodeURIComponent(n.requestId)}/release`,{method:"POST",headers:q(n,e)}),r=await ne(t);if(!t.ok)throw new M(r.error_message||r.error_code||`[urun] session release failed: HTTP ${t.status}`,{requestId:n.requestId,code:r.error_code,httpStatus:t.status});let s=String(r.status??"");if(s!=="closed"&&s!=="cancelled"&&s!=="canceled")throw new M("[urun] session release returned an unrecognized terminal status",{requestId:n.requestId,code:"invalid_release_response",httpStatus:t.status});return{status:s==="closed"?"ended":"canceled",requestId:n.requestId}}catch(e){throw e instanceof M?e:new M("[urun] session release request failed",{requestId:n.requestId,cause:e})}}function ze(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}var Rt=120,Tt=1e3,At=20,Pt=5,Ct=500,Ye=1e4,It=3;function Et(n){if(!n)return null;try{let e=new URL(n),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return _(`${e.origin}${t}`)}catch{return null}}async function Je(n){let e=re(n.baseUrl,n.fallbackUrls),t=null,r=e.length>1;for(let s of e)try{return await xt(s,n,{pollAttempts:Rt,retryAfterLimitMs:r?Tt:void 0})}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof C)throw t}throw t??new Error("[urun] session allocation failed")}async function xt(n,e,t){let r,s,i,o=n,a=0,c=new Set,u=Date.now()+t.pollAttempts*Ye;for(let d=0;d<t.pollAttempts;d++){s=i??await F(e),i=void 0;let w=Math.max(1,Math.min(At,Math.floor((u-Date.now())/1e3))),g=!!r,y=Date.now(),l=r?await fetch(`${o}/api/session-requests/${encodeURIComponent(r)}?wait_s=${w}`,{headers:q(e,s),signal:qt((w+Pt)*1e3)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...q(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(Mt(e))});if(!r&&(l.status===307||l.status===308)){let f=Et(l.headers.get("location"));if(f&&f!==o&&a<It){a+=1,o=f;continue}throw new P(`[urun] session create redirected from ${o} without a usable target`,{httpStatus:l.status})}let p=await ne(l);if(p.request_id)try{e.onRequest?.({requestId:p.request_id,baseUrl:o})}catch{}if(l.ok&&(p.status==="allocated"||!p.status&&!!p.session_id)&&!!p.session_id){let f=p.session_id;if(!p.ws_url)throw new C(`[urun] gateway allocated session ${f} without ws_url`);if(!Qe(p.ws_url))throw new C(`[urun] gateway allocated session ${f} with non-absolute ws_url`);return{baseUrl:o,sessionId:f,wsUrl:p.ws_url,endsAt:ze(p.ends_at),response:p}}if(l.status===202||p.status==="pending"||p.status==="queued"||p.queued){if(r=p.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(Ot(p,r))}catch{}let f=Date.now()-y<Ct;g&&f&&await Lt(Dt(l,p,t.retryAfterLimitMs));continue}if((l.status===401||l.status===403)&&e.getAccessToken){let f=s??"";c.add(f);let b=await F(e,{forceRefresh:!0,reason:"unauthorized"});if(b&&!c.has(b)){i=b,r=void 0;continue}}let m=p.error_message||p.error_code||`HTTP ${l.status}`;throw new P(`[urun] session allocation failed at ${o}: ${m}`,{httpStatus:l.status})}throw new P(`[urun] timed out waiting for session allocation at ${o}`)}function q(n,e){let t={"X-Tenant-Id":n.orgId,"X-Auth-Provider":n.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function F(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function Mt(n){return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey}}async function Xe(n){let e=re(n.baseUrl,n.fallbackUrls),t=null;for(let r of e)try{let s={baseUrl:r,app:"",functionName:"",orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider,idempotencyKey:""},i=await F(s),o=await fetch(`${_(r)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,{headers:q(s,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${n.sessionId} failed: HTTP ${o.status}`);let a=await ne(o);if(!a.ws_url||!Qe(a.ws_url))throw new C(`[urun] viewer-connect returned no usable ws_url for ${n.sessionId}`);return{baseUrl:_(r),sessionId:n.sessionId,wsUrl:a.ws_url,endsAt:ze(a.ends_at),response:a}}catch(s){if(t=s instanceof Error?s:new Error(String(s)),t instanceof C)throw t}throw t??new Error("[urun] viewer-connect failed")}async function Ut(n){try{let e=_(n.baseUrl),t=await F(n),r=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...q(n,t),"Content-Type":"application/json"},body:JSON.stringify({app:n.app,function:n.functionName})});if(r.status===404)return{status:"unknown-app"};if(!r.ok)return{status:"unavailable"};let s=await ne(r),i={status:s.status==="prebound"?"prebound":"warming"};return typeof s.expires_at=="string"&&(i.expiresAt=s.expires_at),typeof s.warm_capable=="boolean"&&(i.warmCapable=s.warm_capable),i}catch(e){return console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function ne(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function Ot(n,e){let t={status:n.status==="queued"||n.queued?"queued":"pending",requestId:e};typeof n.queue_position=="number"&&typeof n.queue_depth=="number"&&(t.queue={position:n.queue_position,depth:n.queue_depth});let r=n.runtime_state;return(r==="unavailable"||r==="starting"||r==="busy")&&(t.runtime={state:r},typeof n.runtime_reason=="string"&&n.runtime_reason.length>0&&(t.runtime.reason=n.runtime_reason)),t}function Dt(n,e,t){let r=Number(n.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??r),i=t??Ye;return Number.isFinite(s)&&s>0?Math.min(s*1e3,i):1e3}function Lt(n){return new Promise(e=>setTimeout(e,n))}function qt(n){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(n):void 0}var C=class extends Error{};function Qe(n){try{let e=new URL(n);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function Ft(n){try{return new URL(n).hostname!==kt?[]:_t}catch{return[]}}var S=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},se=class extends S{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},ie=class extends S{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function j(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function jt(n){return new I(n)}var I=class{_options;constructor(e){this._options=e}async list(e){let r=et(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new S("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(Ze)}async getDownloadUrl(e,t){let r=et(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!$t(s))throw new S("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Ze(r.artifact),downloadUrl:s}}async _request(e,t){let r=re(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let i of r)try{return await this._requestFromBase(i,e,t)}catch(o){if(s=o instanceof Error?o:new Error(String(o)),s instanceof S&&Wt(s.status))throw s}throw s??new S("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let s=`${_(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,i=await this._resolveToken(),o=await fetch(s,{method:"GET",headers:this._headers(i)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await fetch(s,{method:"GET",headers:this._headers(i)}))}if(!o.ok){let{code:a,message:c}=await this._readError(o,e);throw Bt(o.status,a,c)}try{return await o.json()}catch(a){throw new S(`[urun] runtime artifacts: invalid JSON response from ${_(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=_(t);try{let i=(await e.json()).error;if(i&&typeof i=="object"){let{code:o,message:a}=i;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${r}: ${a}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}};function Ze(n){if(!n||typeof n!="object")throw new S("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=n,t=T(e,"artifact_id")||T(e,"id"),r=T(e,"filename"),s=T(e,"kind"),i=T(e,"status")||"ready",o=Nt(e,"size_bytes"),a=T(e,"sha256");if(!t||!r||!s||o==null||!a)throw new S("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:r,contentType:T(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:T(e,"created_at"),expiresAt:T(e,"expires_at")}}function T(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function Nt(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function $t(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function Wt(n){return n===401||n===403}function Bt(n,e,t){return n===401?new se(t,e):n===404?new ie(t,e):new S(t,n,e)}function et(n){if(!n||typeof n!="object"||Array.isArray(n))throw new S("[urun] runtime artifacts: malformed response",0,"bad_response");return n}var k=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)}},N=class extends k{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},oe=class extends k{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},ae=class extends k{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)}},ce=class extends k{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)}},ue=class extends k{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)}},U=class extends k{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 ve(n){return/^(\d+[smhdw])+$/.test(n)}function Ht(n){if(n==="pin")return{action:"pin"};if(ve(n))return{action:"retain",duration:n};throw new U(`[urun] recordings: "${n}" is not a duration or "pin"`)}function Kt(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new N(r,e??"unauthorized");if(n===404)return new oe(r,e??"not_found");if(n===400)return new U(r,e??"bad_request",400);if(n===409)switch(e){case"retain_not_temp":return new ae(r,e);case"pin_requires_active_temp":return new ce(r,e);case"permanent_locked":return new ue(r,e)}return new k(r,{status:n,code:e??`http_${n}`})}var O=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(!ve(t))throw new U(`[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 k("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),i=await this._resolveToken(),o=await this._fetch(s,e,i,r.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i,r.body))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw Kt(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r,s){let i={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(i["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:i};return s!==void 0&&(i["Content-Type"]="application/json",o.body=JSON.stringify(s)),fetch(e,o)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new N("[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:s,message:i}=r;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Vt(n){return new O(n)}var tt="activity",Gt=15e3,ye=["pointerdown","pointermove","keydown","wheel","touchstart"];function be(n){let e=n.now??Date.now,t=n.windowTarget!==void 0?n.windowTarget:typeof window<"u"?window:null,r=n.documentTarget!==void 0?n.documentTarget:typeof document<"u"?document:null,s=!1,i,o=()=>{if(s)return;let d=e();if(!(i!==void 0&&d-i<15e3)){i=d;try{n.awareness.setLocalStateField(tt,{at:d})}catch{}}},a=()=>o(),c=()=>{(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&o()};if(t)for(let d of ye)t.addEventListener(d,a,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",c);let u=null;return n.isProducing&&(u=setInterval(()=>{if(!s)try{n.isProducing?.()&&o()}catch{}},15e3),u.unref?.()),o(),{touch:o,dispose(){if(!s){if(s=!0,t)for(let d of ye)t.removeEventListener(d,a,{capture:!0});r&&r.removeEventListener("visibilitychange",c),u&&(clearInterval(u),u=null)}}}}var zt=250;function Se(n){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,n())};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)}}var rt="video/mp4";function ke(n,e={}){let t=e.timesliceMs??1e3,r=null,s=null,i=!1,o=(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 w=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(rt)?rt:void 0),g=new MediaStream([a]),y=new d(g,w?{mimeType:w}:void 0);r=y;let l=Promise.resolve();y.ondataavailable=p=>{let v=p.data;i||!v||v.size===0||(l=l.then(async()=>{let m=new Uint8Array(await v.arrayBuffer());i||c(m)}))},y.onstop=()=>{l.then(()=>{i||u()})},y.onerror=()=>{l.then(()=>{i||u()})},y.start(t)};return{start(a,c){if(r||i)return;let u=n.track();if(u){o(u,a,c);return}s=n.onTrack(d=>{!d||r||i||(s?.(),s=null,o(d,a,c))})},stop(){if(i)return;i=!0,s?.(),s=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Yt(n){let e=n;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=n.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 nt(n,e){let t=null,r=!1,s=!1,i=new ReadableStream({pull(o){r||(r=!0,t=n(e),t.start(a=>{if(!s)try{o.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{o.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Yt(i)}var Jt=new Set;function Te(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var Xt="rpc",it=3e4,Qt="rpc-resp";function Zt(n){return`${Qt}:${n}`}function _e(){return ee()}function er(n){if(n&&typeof n=="object"){let e=n.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof n=="string"?n:JSON.stringify(n)}}function tr(n,e,t,r,s,i,o,a,c,u){let d=[],w=null,g=!1,y=null,l=!1,p,v,m=new Promise((h,A)=>{p=h,v=A});m.catch(()=>{});let f=o(),b=null,R=null,D=null,V=null,G=!0,Oe=()=>{D&&(clearTimeout(D),D=null),V&&(V(),V=null)},De=!1,Le=()=>{De||!l||(De=!0,n.set({rpc:{[e]:null}}))},z=()=>{G=!1,Oe(),b?.(),b=null,R?.(),R=null,a?.removeEventListener("abort",Fe),f.dispose(),Le()},pe=()=>{if(w){if(d.length>0){let h=w;w=null,h.resolve({value:d.shift(),done:!1})}else if(y!==null){let h=w;w=null,h.reject(y)}else if(g){let h=w;w=null,h.resolve({value:void 0,done:!0})}}},lt=h=>{g||(d.push(h),pe())},E=h=>{g||(y=h,g=!0,v(h),z(),pe())},qe=h=>{g||(g=!0,p(h),z(),pe())},Fe=()=>{let h=a?.reason;E(h instanceof J?h:new X(e))},pt=h=>{if(!(g||!h||typeof h!="object"))switch(Le(),h.t){case"delta":typeof h.delta=="string"&&lt(h.delta);break;case"response":qe(h.body);break;case"error":{let{message:A,code:x}=er(h.body);E(new J(A,{requestId:e,code:h.code??x}));break}}},mt=()=>{let h=f.messages()[Symbol.asyncIterator]();b=()=>{h.return?.(void 0)};let A=()=>{G&&h.next().then(x=>{if(G){if(x.done){g||qe(void 0);return}pt(x.value),A()}},x=>{G&&E(x)})};A()},je=()=>{if(!l){if(l=!0,a){if(a.aborted){E(new X(e));return}a.addEventListener("abort",Fe,{once:!0})}R=c?.(h=>E(h))??null,mt(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:i}}}),u&&u>0&&!n.synced&&(D=setTimeout(()=>{D=null,!g&&!n.synced&&E(new fe(u,e))},u),V=n.onSynced(()=>Oe()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(je(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(y!==null){let h=y;return y=null,Promise.reject(h)}return g?Promise.resolve({value:void 0,done:!0}):new Promise((h,A)=>{w={resolve:h,reject:A}})},return(){return g||(g=!0,p(void 0),z()),Promise.resolve({value:void 0,done:!0})},throw(h){return g||(g=!0,v(h),z()),Promise.reject(h)}}}},body:m,start:je}}function st(n){if(n&&typeof n=="object"){let{epoch:e,by:t}=n,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function rr(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:i,br:o}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let c=st(i);c&&(a.rt=c);let u=st(o);return u&&(a.br=u),a}var Re=class{constructor(e,t,r,s,i){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;this._onActivity=i;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,s=!1,i={push(a){if(!s)if(r){let c=r;r=null,c({value:a,done:!1})}else t.push(a)},end(){if(s=!0,r){let a=r;r=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(i);let o=()=>{s=!0,e._messageConsumers.delete(i)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{r=a})},return(){return o(),Promise.resolve({value:void 0,done:!0})}}}}}_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._track}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=rr(t,this._name),s=r?.br;if(s?.by==="runtime")throw new he(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};r?.rt&&(i.rt=r.rt);let o=r?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??ke;return nt(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0});let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},$=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new He;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activeRequests=new Set;_endHandler;_endPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_lifecycleUnsub=null;constructor(e,t,r,s,i){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=$e(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Se(()=>this.recover()),this._activity=be({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0})}_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 Xe({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new Y,o=new te({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,i,o,Te(t),j({...t,baseUrl:r.baseUrl}));return o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),o.setEndsAt(r.endsAt),Q()&&await Z(),a.setDocTransport({wsUrl:r.wsUrl,token:s}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}whenLive(e){return we(this,e)}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 O(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,s)=>t.retain(r,s),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new I(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new I(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 Re(e,this._transport,this._streamData,()=>this.doc("control"),()=>this._activity?.touch()),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new Ke(e,this._sessionId,Jt.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Ve(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=We(e.wsUrl),r=`${t}\0${e.token??""}\0${this._sessionId}`;r!==this._docEndpointKey&&(this._docEndpointKey=r,this.connectDocs(Be({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket})))}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=_e(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;i=setTimeout(()=>s.abort(new me(a,r)),a)}let o=this._consumeResponse(r,e,!1,s.signal);return o.start(),o.body.finally(()=>{i&&clearTimeout(i)})}_consumeResponse(e,t,r,s,i){this._activity?.touch();let o=this.doc(Xt),a=Zt(e);return tr(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??it)}requestStream(e,t={}){let r=_e();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=_e(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.disconnect(),e)),this._endPromise):Promise.reject(new L)}disconnect(){this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._activity?.dispose(),this._activity=null,this._recoveryHooks.clear();let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new ge)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};var nr=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function sr(n,e){return new Proxy({},{get(t,r){if(!(nr.has(r)||typeof r!="string"))return s=>{let i=s??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),c=new Y,u=new te({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),d=new $(a,c,u,Te(e),j(e)),w,g,y=new Promise(m=>{g=m}),l=m=>{w=m,g({status:"ready",handle:m})};d.setEndHandler(async()=>{let m=w?{status:"ready",handle:w}:await y;if(m.status==="unavailable")throw new L("[urun] session allocation failed before a releasable request was created",{cause:m.cause});let f=m.handle;return Ge({baseUrl:f.baseUrl,requestId:f.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})});let p=async m=>{let f=await Je({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:m,onAdmission:R=>u.reportAdmission(R),onRequest:l}),b=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return d.setSessionId(f.sessionId),d.setArtifactsAuth(j({...e,baseUrl:f.baseUrl})),u.setEndsAt(f.endsAt),{url:f.wsUrl,sessionId:f.sessionId,jwt:b,iceServers:f.response.ice_servers,endsAt:f.endsAt}},v;return u.setConnectionResolver(async()=>{let m=await p(o());return v=m.jwt,m}),u.on("connected",()=>{u.multiplexer&&c.setTarget(u.multiplexer);let m=u.connectedUrl;m&&d.setDocTransport({wsUrl:m,token:v})}),(async()=>{let m;try{m=await p(a)}catch(f){console.error(`[urun] Failed to create session for ${r}:`,f);let b=f instanceof Error?f:new Error(String(f)),R=f instanceof P?f.httpStatus:void 0;u.reportAllocationFailure(b,R),g({status:"unavailable",cause:f});return}u.setAuth({jwt:m.jwt,authProvider:e.authProvider,orgId:e.orgId}),u.setConnection({url:m.url,sessionId:m.sessionId,iceServers:m.iceServers}),Q()&&await Z(),v=m.jwt,d.setDocTransport({wsUrl:m.url,token:m.jwt}),await u.connect({app:n,functionName:r,args:i})})().catch(m=>{console.error(`[urun] Failed to connect session for ${r}:`,m)}),d}}})}var ot=3e4,at="stream:",Ae=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let i=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(i.timer),s.error?i.reject(new Error(s.error)):i.resolve(s.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${at}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${at}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),s(new Error(`RPC request "${e}" timed out after ${ot}ms`)))},ot);this._pendingRpc.set(i,{resolve:r,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function ir(n){let r=`${n.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(n.orgId)}`,s=new WebSocket(r);(n.jwt||n.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:n.orgId,jwt:n.jwt,authProvider:n.authProvider,apiKey:n.apiKey}))});let i=new Ne(s);return new Ae(s,i)}var or='video/mp4; codecs="avc1.42E01E"';function ar(n,e){let t=e?.codec??or,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let s=new MediaSource,i=URL.createObjectURL(s);r.src=i,s.addEventListener("sourceopen",()=>{let g;try{g=s.addSourceBuffer(t)}catch(v){throw v instanceof DOMException&&v.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).`):v}let y=n.getReader();function l(){return g.updating?new Promise(v=>{g.addEventListener("updateend",()=>v(),{once:!0})}):Promise.resolve()}async function p(){try{for(;;){let{done:v,value:m}=await y.read();if(v){await l(),s.readyState==="open"&&s.endOfStream();return}await l();try{g.appendBuffer(m)}catch(f){if(f instanceof DOMException&&f.name==="QuotaExceededError"){let b=g.buffered;if(b.length>0){let R=b.start(b.length-1);g.remove(0,R),await l(),g.appendBuffer(m)}else throw f}else throw f}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}p()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),u=c.getTracks(),d=0,w=u.length;if(w===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let g of u)g.addEventListener("ended",()=>{d++,d>=w&&URL.revokeObjectURL(i)});return c}function cr(n){return n.status.startsWith("pending_")}var de=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 ct(n){let e=[];return n.audio&&e.push("audio"),n.video&&e.push("video"),e.join("+")}function ur(n,e){return e==="audio"?n.getAudioTracks():n.getVideoTracks()}function dr(n,e){let t=n.getTracks();if(t.length===1&&t[0]===e)return n;try{return new MediaStream([e])}catch{return n}}function Pe(n,e){for(let t of[...n.lostListeners])try{t(e)}catch{}}var le=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,Pe(r,new Error(`${e} capture claim superseded by a newer claim`)));let s=this.createState(e,t);return this.claims.set(e,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new de;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await t(r)}catch(o){let a=`one-capture getUserMedia(${ct(r)}) failed`,c=o instanceof Error?o.message:String(o);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||o}`);d.cause=o,Pe(u,d)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of i){let a=ur(s,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${ct(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw c;Pe(o,c);continue}if(o.track=a,o.stream=dr(s,a),o!==e)for(let c of[...o.trackListeners])try{c(a,o.stream)}catch{}}}createState(e,t){let r=this,s={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return s.track},get stream(){return s.stream},update(i){return r.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=i,await r.converge(s),!s.track)throw new Error(`${e} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(e)===s&&r.claims.delete(e),s.track?.stop(),s.track=null,s.stream=null)},onTrack(i){return s.trackListeners.add(i),()=>s.trackListeners.delete(i)},onLost(i){return s.lostListeners.add(i),()=>s.lostListeners.delete(i)}}};return s}},lr=null;function pr(){return lr??=new le}var ut="input",mr=30;function fr(n){let e=n.now??Date.now,t=n.field??ut,r=1e3/Math.max(n.hz??30,.001),s=new Set,i=0,o=0,a=0,c=0,u,d=null,w=!1,g=()=>{if(w)return;u=e(),c+=1;let l={keys:[...s],buttons:i,pointer:{x:o,y:a},seq:c,at:u};try{n.awareness.setLocalStateField(t,l)}catch{}},y=()=>{if(w)return;let l=e();if(u===void 0||l-u>=r){d&&(clearTimeout(d),d=null),g();return}if(d)return;let p=Math.max(r-(l-u),0);d=setTimeout(()=>{d=null,g()},p),d.unref?.()};return{keyDown(l){let p=String(l).toLowerCase();s.has(p)||(s.add(p),y())},keyUp(l){let p=String(l).toLowerCase();s.delete(p)&&y()},setButtons(l){let p=Number.isFinite(l)?Number(l):0;p!==i&&(i=p,y())},movePointer(l,p){let v=Number.isFinite(l)?Number(l):0,m=Number.isFinite(p)?Number(p):0;v===0&&m===0||(o+=v,a+=m,y())},heldKeys(){return[...s]},clear(){w||(s.clear(),i=0,d&&(clearTimeout(d),d=null),g())},dispose(){if(w)return;let l=s.size>0||i!==0;s.clear(),i=0,d&&(clearTimeout(d),d=null),l&&g(),w=!0}}}import{encode as hr,decode as gr}from"@msgpack/msgpack";var dt=65536;function Ie(n){let e=hr(n),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var W=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>dt)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let s=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(gr(s))}return t}},B=12,Ce=1;function Ee(n){let e=n.getUint8(8);return{groupId:n.getUint32(0,!0),frameSeq:n.getUint32(4,!0),keyframe:(e&Ce)===Ce,fragIndex:n.getUint8(9),fragCount:n.getUint8(10)}}function wr(n){let e=new Uint8Array(B),t=new DataView(e.buffer);return t.setUint32(0,n.groupId,!0),t.setUint32(4,n.frameSeq,!0),t.setUint8(8,n.keyframe?Ce:0),t.setUint8(9,n.fragIndex),t.setUint8(10,n.fragCount),t.setUint8(11,0),e}var vr=100,H=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??vr}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<B)return;let t=Ee(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(B),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let s of this.pending.keys())s<t.frameSeq-1&&(this.pending.delete(s),this.framesAbandoned++)}}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let r=t.chunks.reduce((o,a)=>o+a.byteLength,0),s=new Uint8Array(r),i=0;for(let o of t.chunks)s.set(o,i),i+=o.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:s})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var yr=250,K=class{constructor(e,t,r){this.offer=e;this.sessionId=t;this.canvas=r}offer;sessionId;canvas;kind="webtransport";wt;decoder=null;writer;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;reassembler=new H({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};firstFrameResolve=null;firstFrameReject=null;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=new Promise((c,u)=>{this.firstFrameResolve=c,this.firstFrameReject=u});this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(c=>({algorithm:"sha-256",value:Uint8Array.from(atob(c),u=>u.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let r=await this.wt.createBidirectionalStream();this.writer=r.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let s=r.readable.getReader(),i=new W,o=[],a=await this.readControl(s,i,o);if(a?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");this.initDecoder(a.codec,a.width,a.height),this.controlLoop(s,i,o).catch(c=>this.die(`control loop: ${c}`)),this.datagramLoop().catch(c=>this.die(`datagram loop: ${c}`)),this.feedbackLoop(),this.wt.closed.then(()=>this.die("connection closed")).catch(c=>this.die(`connection error: ${c}`)),await t}async stop(){this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}onDead(e){this.deadCb=e}stats(){return this.lastStats}initDecoder(e,t,r){let s=globalThis.VideoDecoder;if(typeof s!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let i=this.canvas.getContext("2d");if(!i)throw new Error("[urun] canvas 2d context unavailable");this.decoder=new s({output:o=>{this.canvas.width=o.displayWidth,this.canvas.height=o.displayHeight,i.drawImage(o,0,0),o.close()},error:o=>this.die(`decoder: ${o.message}`)}),this.decoder.configure({codec:e,codedWidth:t,codedHeight:r,optimizeForLatency:!0,hardwareAcceleration:"prefer-hardware"})}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;let s=performance.now();if(this.lastArrivalTs>0){let i=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(i-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=s,this.reassembler.push(t)}}decodeFrame(e,t,r){let s=globalThis.EncodedVideoChunk;!this.decoder||typeof s!="function"||(this.decoder.decode(new s({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}async sendControl(e){await this.writer.write(Ie(e))}async readControl(e,t,r=[]){for(;;){let s=r.shift();if(s)return s;let{value:i,done:o}=await e.read();if(o)return null;i&&r.push(...t.push(i))}}async controlLoop(e,t,r){for(;!this.stopped;){let s=await this.readControl(e,t,r);if(!s)break;s.t==="ping"&&this.sendControl({t:"pong",ts:s.ts}).catch(()=>{})}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),r=(t-e)/1e3;e=t;let s=this.reassembler.drainWindow(),i=s.delivered+s.abandoned;this.lastStats={recvBps:r>0?s.bytes*8/r:0,lossPct:i>0?100*s.abandoned/i:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},yr)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var br=2500,Sr=["av01.0.08M.08","avc1.640028"],xe=class{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;get activeTransport(){return this.session?.kind??null}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",s=this.opts.allowWebTransport??!0,i={webtransport:t&&r&&s,webcodecs:r,codecs:Sr};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:i});let o=i.webtransport&&!!this.offer.webtransport;if(o){let a=null;try{return a=this.createWebTransportSession(),await kr(a.start(),this.opts.quicDeadlineMs??br,"quic connect deadline"),this.session=a,this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(c){console.warn("[urun] webtransport failed, falling back to webrtc:",c),a?.stop().catch(()=>{}),this.notifyEstablished("webrtc",String(c instanceof Error?c.message:c))}}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){await this.session?.stop(),this.session=null}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 K(e,this.sessionId,this.opts.canvas)}async startWebRtc(){let e=this.opts.createWebRtcSession();return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}armFailover(){this.session.onDead(e=>{console.warn("[urun] quic died mid-session, failing over to webrtc:",e),(async()=>{try{this.session=await this.startWebRtc(),this.notifyEstablished("webrtc",`failover: ${e}`),this.opts.onTransportChange?.("webrtc",e)}catch(t){this.session=null,console.error("[urun] failover to webrtc also failed:",t)}})()})}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function kr(n,e,t){return new Promise((r,s)=>{let i=setTimeout(()=>s(new Error(t)),e);n.then(o=>{clearTimeout(i),r(o)},o=>{clearTimeout(i),s(o)})})}var _r="video",Me=class{constructor(e,t=_r){this.transport=e;this.streamName=t}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];async start(){this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),!this.transport.getTrackByName(this.streamName)&&await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),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.deadCb?.(e))}};var Rr=1e4,Ue=class{constructor(e,t=Rr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=ee();return new Promise((s,i)=>{let o=setTimeout(()=>{a(),i(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(o),a(),c.error){i(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:u,requestId:d,...w}=c;s(w)});this.carrier.sendSignal({type:e,requestId:r,...t})})}notify(e,t){this.carrier.sendSignal({type:e,...t})}on(e,t){return this.carrier.onSignal(r=>{r.type===e&&t(r)})}};export{ye as ACTIVITY_DOM_EVENTS,tt as ACTIVITY_FIELD,Gt as ACTIVITY_STAMP_MIN_INTERVAL_MS,sr as App,le as CaptureController,de as CaptureUnavailableError,it as DEFAULT_DOC_SYNC_TIMEOUT_MS,ft as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,bt as DEFAULT_WHEN_LIVE_TIMEOUT_MS,B as DGRAM_HEADER_BYTES,zt as FOREGROUND_COALESCE_MS,H as FrameReassembler,mr as INPUT_PRESENCE_DEFAULT_HZ,ut as INPUT_PRESENCE_FIELD,U as InvalidDurationError,ue as PermanentLockedError,ce as PinRequiresActiveTempError,ht as ProduceAckTimeoutError,oe as RecordingNotFoundError,O as RecordingsClient,k as RecordingsError,N as RecordingsUnauthorizedError,X as RequestAbortError,ge as RequestCancelledError,fe as RequestDocSyncError,J as RequestError,me as RequestTimeoutError,ae as RetainNotTempError,ie as RuntimeArtifactNotFoundError,I as RuntimeArtifactsClient,S as RuntimeArtifactsError,se as RuntimeArtifactsUnauthorizedError,$ as Session,P as SessionAllocationError,M as SessionEndError,L as SessionEndUnavailableError,wt as SessionFailedError,he as StreamDirectionConflict,xe as TransportNegotiator,Ue as TransportSessionSignaling,dt as WT_CONTROL_FRAME_MAX,Me as WebRtcSession,K as WebTransportSession,W as WtControlDecoder,be as createActivityTracker,fr as createInputPresencePublisher,Vt as createRecordingsClient,jt as createRuntimeArtifactsClient,ir as createStore,gt as describeSessionFailure,St as describeSessionPhase,Ie as encodeWtControlFrame,ve as isDurationString,cr as isPendingRecording,yt as isWakingPhase,ke as mediaRecorderChunkSource,Ht as normalizeRetention,Se as observePageLifecycle,Ee as parseDgramHeader,Ut as prewake,vt as sessionFailureFromMediaError,pr as sharedCaptureController,ar as videoStream,we as whenLive,wr as writeDgramHeader};
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { b as AppOptions, a as App$1, K as SessionPhase, T as SessionStatus, O as SessionPhaseName, A as AccessTokenOptions$1, y as RuntimeArtifact, z as RuntimeArtifactDownload, R as Recording, G as Session$1, C as ChannelEndpoint, _ as TransportSession, c as AttachOptions, v as RecordingsAccessor, B as RuntimeArtifactsAccessor, U as SessionStream$1, Z as StreamDataTransport, I as SessionDocumentImpl, Y as StreamChunkOptions, g as ChunkReadable, P as Presence, k as DocConnector, w as RequestOptions, x as RequestStreamOptions, X as StoreOptions, W as Store, e as ChannelMultiplexer, J as SessionFailureKind } from './stream-data-b249LZR2.mjs';
2
- export { L as Layer, l as LayoutConfig, m as LayoutContext, M as MediaChunkBinding, o as MediaChunkSource, p as MediaChunkSourceFactory, q as MediaRecorderChunkSourceOptions, r as PresenceState, s as RecordingBucket, t as RecordingLifecycle, u as RecordingStatus, E as RuntimeAvailability, S as SceneContext, F as SceneGraph, H as SessionDocument, N as SessionPhaseError, V as SessionText, a0 as TransportState, a4 as isPendingRecording, a5 as mediaRecorderChunkSource } from './stream-data-b249LZR2.mjs';
1
+ import { b as AppOptions, a as App$1, N as SessionPhase, U as SessionStatus, Q as SessionPhaseName, A as AccessTokenOptions$1, y as RuntimeArtifact, z as RuntimeArtifactDownload, R as Recording, G as Session$1, C as ChannelEndpoint, $ as TransportSession, c as AttachOptions, v as RecordingsAccessor, B as RuntimeArtifactsAccessor, J as SessionEndResult, V as SessionStream$1, _ as StreamDataTransport, I as SessionDocumentImpl, Z as StreamChunkOptions, g as ChunkReadable, P as Presence, k as DocConnector, w as RequestOptions, x as RequestStreamOptions, Y as StoreOptions, X as Store, e as ChannelMultiplexer, K as SessionFailureKind, a1 as TransportState } from './stream-data-rqyqR75F.mjs';
2
+ export { L as Layer, l as LayoutConfig, m as LayoutContext, M as MediaChunkBinding, o as MediaChunkSource, p as MediaChunkSourceFactory, q as MediaRecorderChunkSourceOptions, r as PresenceState, s as RecordingBucket, t as RecordingLifecycle, u as RecordingStatus, E as RuntimeAvailability, S as SceneContext, F as SceneGraph, H as SessionDocument, O as SessionPhaseError, W as SessionText, a5 as isPendingRecording, a6 as mediaRecorderChunkSource } from './stream-data-rqyqR75F.mjs';
3
3
  import 'yjs';
4
4
  import 'y-protocols/awareness';
5
5
 
@@ -247,6 +247,8 @@ declare class Session implements Session$1 {
247
247
 
248
248
  private _docConnector;
249
249
 
250
+ private _docEndpointKey;
251
+
250
252
  private _streamData;
251
253
 
252
254
  private _presence;
@@ -254,6 +256,8 @@ declare class Session implements Session$1 {
254
256
  private _activity;
255
257
 
256
258
  private _activeRequests;
259
+ private _endHandler?;
260
+ private _endPromise?;
257
261
 
258
262
  private _recordingsAuth?;
259
263
 
@@ -287,6 +291,8 @@ declare class Session implements Session$1 {
287
291
  setArtifactsAuth(auth: RuntimeArtifactsClientOptions): void;
288
292
  private _requireArtifactsAuth;
289
293
  setSessionId(sessionId: string): void;
294
+
295
+ setEndHandler(handler: () => Promise<SessionEndResult>): void;
290
296
  stream(name: string): SessionStream;
291
297
 
292
298
  doc(key: string): SessionDocumentImpl;
@@ -320,6 +326,7 @@ declare class Session implements Session$1 {
320
326
  recover(): void;
321
327
 
322
328
  onRecovery(hook: () => void): () => void;
329
+ end(): Promise<SessionEndResult>;
323
330
  disconnect(): void;
324
331
  }
325
332
 
@@ -341,6 +348,25 @@ interface VideoStreamOptions {
341
348
 
342
349
  declare function videoStream(source: ReadableStream<Uint8Array>, options?: VideoStreamOptions): MediaStream;
343
350
 
351
+ declare class SessionEndUnavailableError extends Error {
352
+ readonly code = "session_end_unavailable";
353
+ constructor(message?: string, options?: {
354
+ cause?: unknown;
355
+ });
356
+ }
357
+
358
+ declare class SessionEndError extends Error {
359
+ readonly code: string;
360
+ readonly httpStatus?: number;
361
+ readonly requestId: string;
362
+ constructor(message: string, options: {
363
+ requestId: string;
364
+ code?: string;
365
+ httpStatus?: number;
366
+ cause?: unknown;
367
+ });
368
+ }
369
+
344
370
  declare class RequestError extends Error {
345
371
 
346
372
  readonly requestId?: string;
@@ -548,4 +574,254 @@ interface InputPresencePublisher {
548
574
 
549
575
  declare function createInputPresencePublisher(options: InputPresencePublisherOptions): InputPresencePublisher;
550
576
 
551
- export { ACTIVITY_DOM_EVENTS, ACTIVITY_FIELD, ACTIVITY_STAMP_MIN_INTERVAL_MS, type ActivityAwareness, type ActivityTracker, type ActivityTrackerOptions, App, App$1 as AppInterface, AppOptions, AttachOptions, type CaptureClaim, CaptureController, type CaptureControllerOptions, type CaptureKind, CaptureUnavailableError, ChunkReadable, DEFAULT_DOC_SYNC_TIMEOUT_MS, DEFAULT_PRODUCE_ACK_TIMEOUT_MS, DEFAULT_WHEN_LIVE_TIMEOUT_MS, FOREGROUND_COALESCE_MS, INPUT_PRESENCE_DEFAULT_HZ, INPUT_PRESENCE_FIELD, type InputPresenceAwareness, type InputPresencePublisher, type InputPresencePublisherOptions, type InputPresenceState, InvalidDurationError, PermanentLockedError, type PhaseObservable, PinRequiresActiveTempError, Presence, type PrewakeOptions, type PrewakeResult, type PrewakeStatus, ProduceAckTimeoutError, Recording, RecordingNotFoundError, RecordingsAccessor, RecordingsClient, type RecordingsClientOptions, RecordingsError, RecordingsUnauthorizedError, RequestAbortError, RequestCancelledError, RequestDocSyncError, RequestError, RequestOptions, RequestStreamOptions, RequestTimeoutError, RetainNotTempError, type RetentionIntent, RuntimeArtifact, RuntimeArtifactDownload, RuntimeArtifactNotFoundError, RuntimeArtifactsAccessor, RuntimeArtifactsClient, type RuntimeArtifactsClientOptions, RuntimeArtifactsError, RuntimeArtifactsUnauthorizedError, Session, SessionAllocationError, SessionFailedError, SessionFailureKind, Session$1 as SessionInterface, SessionPhase, SessionPhaseName, SessionStatus, SessionStream$1 as SessionStream, Store, StoreOptions, StreamChunkOptions, StreamDirectionConflict, type VideoStreamOptions, type WhenLiveOptions, createActivityTracker, createInputPresencePublisher, createRecordingsClient, createRuntimeArtifactsClient, createStore, describeSessionFailure, describeSessionPhase, isDurationString, isWakingPhase, normalizeRetention, observePageLifecycle, prewake, sessionFailureFromMediaError, sharedCaptureController, videoStream, whenLive };
577
+ interface MediaSession {
578
+ readonly kind: 'webtransport' | 'webrtc';
579
+ start(): Promise<void>;
580
+ stop(): Promise<void>;
581
+
582
+ onDead(cb: (reason: string) => void): void;
583
+
584
+ stats(): {
585
+ recvBps: number;
586
+ lossPct: number;
587
+ jitterMs: number;
588
+ };
589
+ }
590
+
591
+ interface Signaling {
592
+ request<T = unknown>(method: string, params?: unknown): Promise<T>;
593
+ notify(method: string, params?: unknown): void;
594
+
595
+ on(method: string, handler: (params: Record<string, unknown>) => void): () => void;
596
+ }
597
+
598
+ interface SignalCarrier {
599
+
600
+ sendSignal(msg: Record<string, unknown>): void;
601
+
602
+ onSignal(handler: (msg: Record<string, unknown>) => void): () => void;
603
+ }
604
+ declare class TransportSessionSignaling implements Signaling {
605
+ private carrier;
606
+ private requestTimeoutMs;
607
+ constructor(carrier: SignalCarrier, requestTimeoutMs?: number);
608
+ request<T = unknown>(method: string, params?: unknown): Promise<T>;
609
+ notify(method: string, params?: unknown): void;
610
+ on(method: string, handler: (params: Record<string, unknown>) => void): () => void;
611
+ }
612
+
613
+ interface TransportOfferRequest {
614
+ sessionId: string;
615
+ capabilities: {
616
+
617
+ webtransport: boolean;
618
+
619
+ webcodecs: boolean;
620
+
621
+ codecs: string[];
622
+ };
623
+ }
624
+ interface TransportOfferResponse {
625
+
626
+ webrtc: {
627
+ routerRtpCapabilities: unknown;
628
+ };
629
+
630
+ webtransport?: {
631
+ url: string;
632
+
633
+ certHashes: string[];
634
+
635
+ token: string;
636
+ codec: string;
637
+ };
638
+ }
639
+ interface TransportEstablishedNotify {
640
+ sessionId: string;
641
+ transport: 'webtransport' | 'webrtc';
642
+
643
+ fallbackReason?: string;
644
+ }
645
+ type WtControlMessage = {
646
+ t: 'hello';
647
+ token: string;
648
+ sessionId: string;
649
+ } | {
650
+ t: 'hello-ack';
651
+ codec: string;
652
+ width: number;
653
+ height: number;
654
+ } | {
655
+ t: 'ping';
656
+ ts: number;
657
+ } | {
658
+ t: 'pong';
659
+ ts: number;
660
+ } | {
661
+ t: 'keyframe-request';
662
+ } | {
663
+ t: 'feedback';
664
+ recvBps: number;
665
+ lossPct: number;
666
+ jitterMs: number;
667
+ };
668
+
669
+ declare const WT_CONTROL_FRAME_MAX: number;
670
+
671
+ declare function encodeWtControlFrame(msg: WtControlMessage): Uint8Array;
672
+
673
+ declare class WtControlDecoder {
674
+ private buf;
675
+ push(bytes: Uint8Array): WtControlMessage[];
676
+ }
677
+ declare const DGRAM_HEADER_BYTES = 12;
678
+ interface DgramHeader {
679
+ groupId: number;
680
+ frameSeq: number;
681
+ keyframe: boolean;
682
+ fragIndex: number;
683
+ fragCount: number;
684
+ }
685
+
686
+ declare function parseDgramHeader(view: DataView): DgramHeader;
687
+
688
+ declare function writeDgramHeader(h: DgramHeader): Uint8Array;
689
+
690
+ interface NegotiatorOptions {
691
+
692
+ quicDeadlineMs?: number;
693
+
694
+ allowWebTransport?: boolean;
695
+ onTransportChange?: (kind: MediaSession['kind'], reason?: string) => void;
696
+
697
+ canvas?: HTMLCanvasElement;
698
+
699
+ createWebRtcSession: () => MediaSession;
700
+ createWebTransportSession?: (offer: NonNullable<TransportOfferResponse['webtransport']>) => MediaSession;
701
+ }
702
+ declare class TransportNegotiator {
703
+ private signaling;
704
+ private sessionId;
705
+ private opts;
706
+ private session;
707
+ private offer;
708
+ constructor(signaling: Signaling, sessionId: string, opts: NegotiatorOptions);
709
+ get activeTransport(): MediaSession['kind'] | null;
710
+ connect(): Promise<MediaSession>;
711
+ disconnect(): Promise<void>;
712
+ private createWebTransportSession;
713
+ private startWebRtc;
714
+
715
+ private armFailover;
716
+ private notifyEstablished;
717
+ }
718
+
719
+ declare class WebTransportSession implements MediaSession {
720
+ private offer;
721
+ private sessionId;
722
+ private canvas;
723
+ readonly kind: "webtransport";
724
+ private wt;
725
+ private decoder;
726
+ private writer;
727
+ private deadCb;
728
+ private deadFired;
729
+ private stopped;
730
+ private feedbackTimer;
731
+ private reassembler;
732
+ private lastArrivalTs;
733
+ private jitterEwmaMs;
734
+ private lastStats;
735
+ private firstFrameResolve;
736
+ private firstFrameReject;
737
+ constructor(offer: NonNullable<TransportOfferResponse['webtransport']>, sessionId: string, canvas: HTMLCanvasElement);
738
+
739
+ start(): Promise<void>;
740
+ stop(): Promise<void>;
741
+ onDead(cb: (reason: string) => void): void;
742
+ stats(): {
743
+ recvBps: number;
744
+ lossPct: number;
745
+ jitterMs: number;
746
+ };
747
+ private initDecoder;
748
+ private datagramLoop;
749
+ private decodeFrame;
750
+ private sendControl;
751
+ private readControl;
752
+ private controlLoop;
753
+
754
+ private feedbackLoop;
755
+ private die;
756
+ }
757
+
758
+ interface ConsumingTransport {
759
+ getTrackByName(name: string): MediaStreamTrack | undefined;
760
+ on(event: 'track', handler: (track: MediaStreamTrack) => void): () => void;
761
+ on(event: 'stateChange', handler: (state: TransportState) => void): () => void;
762
+ }
763
+ declare class WebRtcSession implements MediaSession {
764
+ private transport;
765
+ private streamName;
766
+ readonly kind: "webrtc";
767
+ private deadCb;
768
+ private deadFired;
769
+ private unsubscribers;
770
+ constructor(transport: ConsumingTransport, streamName?: string);
771
+
772
+ start(): Promise<void>;
773
+
774
+ stop(): Promise<void>;
775
+ onDead(cb: (reason: string) => void): void;
776
+ stats(): {
777
+ recvBps: number;
778
+ lossPct: number;
779
+ jitterMs: number;
780
+ };
781
+ private die;
782
+ }
783
+
784
+ interface ReassembledFrame {
785
+ seq: number;
786
+ groupId: number;
787
+ keyframe: boolean;
788
+ data: Uint8Array;
789
+ }
790
+ interface ReassemblerCallbacks {
791
+
792
+ onFrame(frame: ReassembledFrame): void;
793
+
794
+ onKeyframeNeeded(): void;
795
+ }
796
+ interface ReassemblerOptions {
797
+
798
+ now?: () => number;
799
+
800
+ keyframeRequestDebounceMs?: number;
801
+ }
802
+ declare class FrameReassembler {
803
+ private cb;
804
+ private pending;
805
+ private newestGroupSeen;
806
+ private newestFrameDelivered;
807
+ private needKeyframe;
808
+ private kfRequestedAt;
809
+ private now;
810
+ private debounceMs;
811
+ private bytesInWindow;
812
+ private framesDelivered;
813
+ private framesAbandoned;
814
+ constructor(cb: ReassemblerCallbacks, opts?: ReassemblerOptions);
815
+
816
+ push(chunk: Uint8Array): void;
817
+
818
+ drainWindow(): {
819
+ bytes: number;
820
+ delivered: number;
821
+ abandoned: number;
822
+ };
823
+ private deliver;
824
+ private requestKeyframe;
825
+ }
826
+
827
+ export { ACTIVITY_DOM_EVENTS, ACTIVITY_FIELD, ACTIVITY_STAMP_MIN_INTERVAL_MS, type ActivityAwareness, type ActivityTracker, type ActivityTrackerOptions, App, App$1 as AppInterface, AppOptions, AttachOptions, type CaptureClaim, CaptureController, type CaptureControllerOptions, type CaptureKind, CaptureUnavailableError, ChunkReadable, type ConsumingTransport, DEFAULT_DOC_SYNC_TIMEOUT_MS, DEFAULT_PRODUCE_ACK_TIMEOUT_MS, DEFAULT_WHEN_LIVE_TIMEOUT_MS, DGRAM_HEADER_BYTES, type DgramHeader, FOREGROUND_COALESCE_MS, FrameReassembler, INPUT_PRESENCE_DEFAULT_HZ, INPUT_PRESENCE_FIELD, type InputPresenceAwareness, type InputPresencePublisher, type InputPresencePublisherOptions, type InputPresenceState, InvalidDurationError, type MediaSession, type NegotiatorOptions, PermanentLockedError, type PhaseObservable, PinRequiresActiveTempError, Presence, type PrewakeOptions, type PrewakeResult, type PrewakeStatus, ProduceAckTimeoutError, type ReassembledFrame, type ReassemblerCallbacks, type ReassemblerOptions, Recording, RecordingNotFoundError, RecordingsAccessor, RecordingsClient, type RecordingsClientOptions, RecordingsError, RecordingsUnauthorizedError, RequestAbortError, RequestCancelledError, RequestDocSyncError, RequestError, RequestOptions, RequestStreamOptions, RequestTimeoutError, RetainNotTempError, type RetentionIntent, RuntimeArtifact, RuntimeArtifactDownload, RuntimeArtifactNotFoundError, RuntimeArtifactsAccessor, RuntimeArtifactsClient, type RuntimeArtifactsClientOptions, RuntimeArtifactsError, RuntimeArtifactsUnauthorizedError, Session, SessionAllocationError, SessionEndError, SessionEndResult, SessionEndUnavailableError, SessionFailedError, SessionFailureKind, Session$1 as SessionInterface, SessionPhase, SessionPhaseName, SessionStatus, SessionStream$1 as SessionStream, type SignalCarrier, type Signaling, Store, StoreOptions, StreamChunkOptions, StreamDirectionConflict, type TransportEstablishedNotify, TransportNegotiator, type TransportOfferRequest, type TransportOfferResponse, TransportSessionSignaling, TransportState, type VideoStreamOptions, WT_CONTROL_FRAME_MAX, WebRtcSession, WebTransportSession, type WhenLiveOptions, WtControlDecoder, type WtControlMessage, createActivityTracker, createInputPresencePublisher, createRecordingsClient, createRuntimeArtifactsClient, createStore, describeSessionFailure, describeSessionPhase, encodeWtControlFrame, isDurationString, isWakingPhase, normalizeRetention, observePageLifecycle, parseDgramHeader, prewake, sessionFailureFromMediaError, sharedCaptureController, videoStream, whenLive, writeDgramHeader };