@urun-sh/core 0.2.31 → 0.2.32

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 ae,D as ot,E as at,F as ct,G as dt,H as ut,a as st,b as te,c as j,d as U,e as re,f as ke,g as Te,h as Ae,i as $t,j as Ht,k as ne,l as Re,m as Bt,n as Kt,o as Vt,p as R,q as Gt,r as zt,s as Ee,t as Yt,u as se,w as ie,x as oe,z as it}from"./chunk-RITHWXCZ.mjs";var Jt=15e3,Xt=45e3,Qt=12e4,Ie="platform",Ce="activation",Pe="desired.activation";function lt(n){if(typeof n=="string"&&n.length>0)return n;if(n&&typeof n=="object"){let e=n.note;if(typeof e=="string"&&e.length>0)return e}}var Zt=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],W=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(t?.name==="error"||t?.name==="ended"||t?.name==="expired")&&this.dispose()}),this._stopped&&(this._offPhase(),this._offPhase=null)}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;watch(e,t){if(this._stopped||this._watches.has(e))return;let r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let s=()=>this._firstMedia(e);r.addEventListener("unmute",s,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",s));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of Zt){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let s={state:t,elapsedMs:r,stream:e.name},o=lt(this._options.hint());o!==void 0&&(s.hint=o),e.lastEvent=s;for(let i of Array.from(this._handlers))i(s)}};var pt=500,ft=15e3,L=6;function de(n,e=Math.random){if(!Number.isFinite(n)||n<0)throw new Error(`[urun] computeBackoffDelay: attempt must be a non-negative number, got ${n}`);let t=Math.min(ft,pt*2**n);return Math.round(e()*t)}function ue(n){if(n instanceof R){let e=n.httpStatus;return e===408||e===429||e!==void 0&&e>=500}return n instanceof Error?n.name==="TypeError"||n.name==="TimeoutError"||n.name==="AbortError":!1}var mt=10,er=.5,ce=mt;function Me(){return ce<1?!1:(ce-=1,!0)}function xe(){ce=Math.min(mt,ce+er)}var tr="session-api.prod.cloud.urun.sh",rr=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function S(n){return n.trim().replace(/\/+$/,"")}function le(n,e){let t=[],r=s=>{if(!s)return;let o=S(s);o&&!t.includes(o)&&t.push(o)};r(n);for(let s of e??[])r(s);for(let s of vr(n))r(s);return t}function Oe(n){try{if(typeof fetch!="function")return;let e=`${S(n.baseUrl)}/api/session-requests/${encodeURIComponent(n.requestId)}/release`;fetch(e,{method:"POST",headers:q(n,n.jwt),keepalive:!0}).catch(()=>{})}catch{}}async function gt(n){try{let e=await $(n),t=await fetch(`${S(n.baseUrl)}/api/session-requests/${encodeURIComponent(n.requestId)}/release`,{method:"POST",headers:q(n,e)}),r=await pe(t);if(!t.ok)throw new U(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 U("[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 U?e:new U("[urun] session release request failed",{requestId:n.requestId,cause:e})}}function vt(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}var nr=120,sr=1e3,ir=20,or=5,ar=500,wt=1e4,cr=3;function dr(n,e){if(!n)return null;try{let t=new URL(n),r=e?new URL(S(e)):null,s=t.pathname==="/api/sessions/create"||t.pathname==="/api/sessions/create/";return t.protocol!=="https:"||!s||!ur(t,r)?null:S(t.origin)}catch{return null}}function ur(n,e){return ht(n.hostname)&&(!e||ht(e.hostname))}function ht(n){let e=n.toLowerCase();return e==="urun.sh"||e.endsWith(".urun.sh")}async function yt(n){let e=le(n.baseUrl,n.fallbackUrls),t=null,r=e.length>1;for(let s=0;s<L;s++){for(let o of e)try{let i=await lr(o,n,{pollAttempts:nr,retryAfterLimitMs:r?sr:void 0});return xe(),i}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof P)throw t}if(!ue(t))break;if(s+1<L){if(!Me())break;await De(de(s))}}throw t??new Error("[urun] session allocation failed")}async function lr(n,e,t){let r,s,o,i=n,a=0,c=new Set,f=Date.now()+t.pollAttempts*wt;for(let d=0;d<t.pollAttempts;d++){s=o??await $(e),o=void 0;let m=Math.max(1,Math.min(ir,Math.floor((f-Date.now())/1e3))),l=!!r,w=Date.now(),u=r?await fetch(`${i}/api/session-requests/${encodeURIComponent(r)}?wait_s=${m}`,{headers:q(e,s),signal:gr((m+or)*1e3)}):await fetch(`${i}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...q(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(pr(e))});if(!r&&(u.status===307||u.status===308)){let b=dr(u.headers.get("location"),i);if(b&&b!==i&&a<cr){a+=1,i=b;continue}throw new R(`[urun] session create redirected from ${i} without a usable target`,{httpStatus:u.status})}let p=await pe(u);if(p.request_id)try{e.onRequest?.({requestId:p.request_id,baseUrl:i})}catch{}if(u.ok&&(p.status==="allocated"||!p.status&&!!p.session_id)&&!!p.session_id){let b=p.session_id;if(!p.ws_url)throw new P(`[urun] gateway allocated session ${b} without ws_url`);if(!_t(p.ws_url))throw new P(`[urun] gateway allocated session ${b} with non-absolute ws_url`);return{baseUrl:i,sessionId:b,wsUrl:p.ws_url,endsAt:vt(p.ends_at),response:p}}if(u.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(mr(p,r))}catch{}let b=Date.now()-w<ar;l&&b&&await De(hr(u,p,t.retryAfterLimitMs));continue}if((u.status===401||u.status===403)&&e.getAccessToken){let b=s??"";c.add(b);let h=await $(e,{forceRefresh:!0,reason:"unauthorized"});if(h&&!c.has(h)){o=h,r=void 0;continue}}let _=p.error_message||p.error_code||`HTTP ${u.status}`;throw new R(`[urun] session allocation failed at ${i}: ${_}`,{httpStatus:u.status})}throw new R(`[urun] timed out waiting for session allocation at ${i}`)}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 $(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function pr(n){let e=n.priority==="preempt";return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey,...n.sessionKey&&!e?{logical_id:n.sessionKey}:{},...e?{priority:"preempt"}:{}}}async function bt(n){let e=le(n.baseUrl,n.fallbackUrls),t=null;for(let r=0;r<L;r++){for(let s of e)try{let o={baseUrl:s,app:"",functionName:"",orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider,idempotencyKey:""},i=await $(o),a=await fetch(`${S(s)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,{headers:q(o,i)});if(!a.ok)throw new R(`[urun] viewer-connect for ${n.sessionId} failed: HTTP ${a.status}`,{httpStatus:a.status});let c=await pe(a);if(!c.ws_url||!_t(c.ws_url))throw new P(`[urun] viewer-connect returned no usable ws_url for ${n.sessionId}`);return xe(),{baseUrl:S(s),sessionId:n.sessionId,wsUrl:c.ws_url,endsAt:vt(c.ends_at),response:c}}catch(o){if(t=o instanceof Error?o:new Error(String(o)),t instanceof P)throw t}if(!ue(t))break;if(r+1<L){if(!Me())break;await De(de(r))}}throw t??new Error("[urun] viewer-connect failed")}async function fr(n){try{let e=S(n.baseUrl),t=await $(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 pe(r),o={status:s.status==="prebound"?"prebound":"warming"};return typeof s.expires_at=="string"&&(o.expiresAt=s.expires_at),typeof s.warm_capable=="boolean"&&(o.warmCapable=s.warm_capable),o}catch(e){return console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function pe(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function mr(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 hr(n,e,t){let r=Number(n.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??r),o=t??wt;return Number.isFinite(s)&&s>0?Math.min(s*1e3,o):1e3}function De(n){return new Promise(e=>setTimeout(e,n))}function gr(n){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(n):void 0}var P=class extends Error{};function _t(n){try{let e=new URL(n);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function vr(n){try{return new URL(n).hostname!==tr?[]:rr}catch{return[]}}var k=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)}},fe=class extends k{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},me=class extends k{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function H(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function wr(n){return new M(n)}var M=class{_options;constructor(e){this._options=e}async list(e){let r=kt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new k("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(St)}async getDownloadUrl(e,t){let r=kt(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!br(s))throw new k("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:St(r.artifact),downloadUrl:s}}async _request(e,t){let r=le(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let o of r)try{return await this._requestFromBase(o,e,t)}catch(i){if(s=i instanceof Error?i:new Error(String(i)),s instanceof k&&_r(s.status))throw s}throw s??new k("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let s=`${S(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,o=await this._resolveToken(),i=await fetch(s,{method:"GET",headers:this._headers(o)});if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await fetch(s,{method:"GET",headers:this._headers(o)}))}if(!i.ok){let{code:a,message:c}=await this._readError(i,e);throw Sr(i.status,a,c)}try{return await i.json()}catch(a){throw new k(`[urun] runtime artifacts: invalid JSON response from ${S(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=S(t);try{let o=(await e.json()).error;if(o&&typeof o=="object"){let{code:i,message:a}=o;return{code:typeof i=="string"&&i.length>0?i:`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 St(n){if(!n||typeof n!="object")throw new k("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=n,t=E(e,"artifact_id")||E(e,"id"),r=E(e,"filename"),s=E(e,"kind"),o=E(e,"status")||"ready",i=yr(e,"size_bytes"),a=E(e,"sha256");if(!t||!r||!s||i==null||!a)throw new k("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:r,contentType:E(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:E(e,"created_at"),expiresAt:E(e,"expires_at")}}function E(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function yr(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function br(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function _r(n){return n===401||n===403}function Sr(n,e,t){return n===401?new fe(t,e):n===404?new me(t,e):new k(t,n,e)}function kt(n){if(!n||typeof n!="object"||Array.isArray(n))throw new k("[urun] runtime artifacts: malformed response",0,"bad_response");return n}var T=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)}},B=class extends T{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},he=class extends T{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},ge=class extends T{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)}},ve=class extends T{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)}},we=class extends T{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)}},F=class extends T{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 Ue(n){return/^(\d+[smhdw])+$/.test(n)}function kr(n){if(n==="pin")return{action:"pin"};if(Ue(n))return{action:"retain",duration:n};throw new F(`[urun] recordings: "${n}" is not a duration or "pin"`)}function Tr(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new B(r,e??"unauthorized");if(n===404)return new he(r,e??"not_found");if(n===400)return new F(r,e??"bad_request",400);if(n===409)switch(e){case"retain_not_temp":return new ge(r,e);case"pin_requires_active_temp":return new ve(r,e);case"permanent_locked":return new we(r,e)}return new T(r,{status:n,code:e??`http_${n}`})}var N=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(!Ue(t))throw new F(`[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 T("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),o=await this._resolveToken(),i=await this._fetch(s,e,o,r.body);if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await this._fetch(s,e,o,r.body))}if(!i.ok){let{code:a,message:c}=await this._readError(i);throw Tr(i.status,a,c)}return this._readJson(i)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,i])=>`${encodeURIComponent(o)}=${encodeURIComponent(i)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r,s){let o={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(o["X-Auth-Provider"]=this._options.authProvider);let i={method:t,headers:o};return s!==void 0&&(o["Content-Type"]="application/json",i.body=JSON.stringify(s)),fetch(e,i)}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 B("[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:o}=r;return{code:typeof s=="string"?s:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Ar(n){return new N(n)}var Tt="activity",Rr=15e3,Le=["pointerdown","pointermove","keydown","wheel","touchstart"];function qe(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,o,i=()=>{if(s)return;let d=e();if(!(o!==void 0&&d-o<15e3)){o=d;try{n.awareness.setLocalStateField(Tt,{at:d})}catch{}}},a=()=>i(),c=()=>{(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&i()};if(t)for(let d of Le)t.addEventListener(d,a,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",c);let f=null;return n.isProducing&&(f=setInterval(()=>{if(!s)try{n.isProducing?.()&&i()}catch{}},15e3),f.unref?.()),i(),{touch:i,dispose(){if(!s){if(s=!0,t)for(let d of Le)t.removeEventListener(d,a,{capture:!0});r&&r.removeEventListener("visibilitychange",c),f&&(clearInterval(f),f=null)}}}}var Er=250;function Fe(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)}}function Ne(n){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,n())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}var At="video/mp4";function je(n,e={}){let t=e.timesliceMs??1e3,r=null,s=null,o=!1,i=(a,c,f)=>{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 m=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(At)?At:void 0),l=new MediaStream([a]),w=new d(l,m?{mimeType:m}:void 0);r=w;let u=Promise.resolve();w.ondataavailable=p=>{let y=p.data;o||!y||y.size===0||(u=u.then(async()=>{let _=new Uint8Array(await y.arrayBuffer());o||c(_)}))},w.onstop=()=>{u.then(()=>{o||f()})},w.onerror=()=>{u.then(()=>{o||f()})},w.start(t)};return{start(a,c){if(r||o)return;let f=n.track();if(f){i(f,a,c);return}s=n.onTrack(d=>{!d||r||o||(s?.(),s=null,i(d,a,c))})},stop(){if(o)return;o=!0,s?.(),s=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Ir(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 Rt(n,e){let t=null,r=!1,s=!1,o=new ReadableStream({pull(i){r||(r=!0,t=n(e),t.start(a=>{if(!s)try{i.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{i.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Ir(o)}import{encode as Cr,decode as Pr}from"@msgpack/msgpack";var Et=65536;function $e(n){let e=Cr(n),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var K=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>Et)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(Pr(s))}return t}},V=12,We=1;function He(n){let e=n.getUint8(8);return{groupId:n.getUint32(0,!0),frameSeq:n.getUint32(4,!0),keyframe:(e&We)===We,fragIndex:n.getUint8(9),fragCount:n.getUint8(10)}}function Mr(n){let e=new Uint8Array(V),t=new DataView(e.buffer);return t.setUint32(0,n.groupId,!0),t.setUint32(4,n.frameSeq,!0),t.setUint8(8,n.keyframe?We:0),t.setUint8(9,n.fragIndex),t.setUint8(10,n.fragCount),t.setUint8(11,0),e}var xr=100,G=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??xr}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<V)return;let t=He(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(V),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++)}}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let r=t.chunks.reduce((i,a)=>i+a.byteLength,0),s=new Uint8Array(r),o=0;for(let i of t.chunks)s.set(i,o),o+=i.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 Or=/^avc[13]\.[0-9a-fA-F]{6}$/;function Dr(n){return Or.test(n)?null:`codec ${JSON.stringify(n)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function Be(n,e){let t=Dr(n);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var Ur=250,Lr=3,qr=1e4,Ke=2500,z=class{constructor(e,t,r){this.offer=e;this.sessionId=t;this.canvas=r;this.firstMedia=new Promise((s,o)=>{this.firstFrameResolve=s,this.firstFrameReject=o}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorsAt=[];writer;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;reassembler=new G({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;firstFrameOutput=!1;firstDecodeTimer=null;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");Be(this.offer.codec,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(a=>({algorithm:"sha-256",value:Uint8Array.from(atob(a),c=>c.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let t=await this.wt.createBidirectionalStream();this.writer=t.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let r=t.readable.getReader(),s=new K,o=[],i=await this.readControl(r,s,o);if(i?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");Be(i.codec,"hello-ack"),this.initDecoder(i.codec,i.width,i.height),this.controlLoop(r,s,o).catch(a=>this.die(`control loop: ${a}`)),this.datagramLoop().catch(a=>this.die(`datagram loop: ${a}`)),this.feedbackLoop(),this.wt.closed.then(()=>this.die("connection closed")).catch(a=>this.die(`connection error: ${a}`))}async stop(){this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null;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 o=this.canvas.getContext("2d");if(!o)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r},this.decoder=new s({output:i=>{this.firstFrameOutput=!0,this.firstDecodeTimer&&(clearTimeout(this.firstDecodeTimer),this.firstDecodeTimer=null),this.canvas.width=i.displayWidth,this.canvas.height=i.displayHeight,o.drawImage(i,0,0),i.close()},error:i=>this.onDecoderError(i)}),this.decoder.configure({codec:e,...t>0&&r>0?{codedWidth:t,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"})}onDecoderError(e){if(this.stopped||this.deadFired)return;let t=performance.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(s=>t-s<qr),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=Lr){this.die(`decoder: ${e.message}`);return}console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=this.decoderConfig;if(!r){this.die(`decoder: ${e.message} (no config to re-init from)`);return}try{this.initDecoder(r.codec,r.width,r.height)}catch(s){this.die(`decoder re-init: ${s instanceof Error?s.message:String(s)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}armFirstDecodeDeadline(){if(this.firstDecodeTimer||this.firstFrameOutput||this.stopped||this.deadFired)return;let e=setTimeout(()=>{this.firstDecodeTimer=null,!(this.firstFrameOutput||this.stopped||this.deadFired)&&(console.error(`[urun] webtransport: media datagrams arriving but NO frame decoded within ${Ke}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${Ke}ms`))},Ke);e.unref?.(),this.firstDecodeTimer=e}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:r}=await e.read();if(r)break;if(!t)continue;this.armFirstDecodeDeadline();let s=performance.now();if(this.lastArrivalTs>0){let o=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(o-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($e(e))}async readControl(e,t,r=[]){for(;;){let s=r.shift();if(s)return s;let{value:o,done:i}=await e.read();if(i)return null;o&&r.push(...t.push(o))}}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(),o=s.delivered+s.abandoned;this.lastStats={recvBps:r>0?s.bytes*8/r:0,lossPct:o>0?100*s.abandoned/o:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Ur)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var Fr=2500,Nr=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Y=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,o={webtransport:t&&r&&s,webcodecs:r,codecs:Nr};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:o});let i=o.webtransport&&!!this.offer.webtransport;if(o.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),i){let a=null;try{return a=this.createWebTransportSession(),await jr(a.start(),this.opts.quicDeadlineMs??Fr,"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(),i||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 z(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(){let e=this.session;e.onDead(t=>{console.warn("[urun] quic died mid-session, failing over to webrtc:",t),e.stop().catch(()=>{}),(async()=>{try{this.session=await this.startWebRtc(),this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(r){this.session=null,console.error("[urun] failover to webrtc also failed:",r)}})()})}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function jr(n,e,t){return new Promise((r,s)=>{let o=setTimeout(()=>s(new Error(t)),e);n.then(i=>{clearTimeout(o),r(i)},i=>{clearTimeout(o),s(i)})})}var Wr=1e4,J=class{constructor(e,t=Wr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=oe();return new Promise((s,o)=>{let i=setTimeout(()=>{a(),o(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(i),a(),c.error){o(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:f,requestId:d,...m}=c;s(m)});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)})}};var $r="video",X=class{constructor(e,t=$r){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};var Hr="video";function It(n,e,t){let r=globalThis,s=r.document;if(!(typeof s?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let i=s.createElement("canvas"),a=!1,c=null,f=!1,d=()=>{if(c){for(let u of c.getVideoTracks())try{u.stop()}catch{}c=null}f&&(f=!1,t.onOverrideTrack(null))},m=new Y(new J(n),e,{canvas:i,createWebRtcSession:t.createWebRtcSession??(()=>new X(n,t.streamName??Hr)),createWebTransportSession:t.createWebTransportSession,onTransportChange:(u,p)=>{u==="webrtc"&&d(),t.onTransportChange?.(u,p)}}),l=null,w=()=>{l!==null&&(clearTimeout(l),l=null)};return(async()=>{let u=await m.connect();if(a||u.kind!=="webtransport")return;let p=t.firstMediaWarnMs??1e4;if(l=setTimeout(()=>{a||m.activeTransport!=="webtransport"||console.warn(`[urun] webtransport established but no QUIC media after ${p}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)},p),await u.firstMedia,w(),a||m.activeTransport!=="webtransport"||typeof i.captureStream!="function")return;c=i.captureStream();let y=c.getVideoTracks()[0];y&&(f=!0,t.onOverrideTrack(y))})().catch(u=>{w(),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",u)}),{activeTransport:()=>m.activeTransport,dispose(){a=!0,w(),d(),m.disconnect().catch(()=>{})}}}var Br=new Set;function ze(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var Kr="rpc",Pt=3e4,Vr="rpc-resp";function Gr(n){return`${Vr}:${n}`}function Ve(){return oe()}function zr(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 Yr(n,e,t,r,s,o,i,a,c,f){let d=[],m=null,l=!1,w=null,u=!1,p,y,_=new Promise((g,C)=>{p=g,y=C});_.catch(()=>{});let b=i(),h=null,v=null,A=null,I=null,Z=!0,Qe=()=>{A&&(clearTimeout(A),A=null),I&&(I(),I=null)},Ze=!1,et=()=>{Ze||!u||(Ze=!0,n.set({rpc:{[e]:null}}))},ee=()=>{Z=!1,Qe(),h?.(),h=null,v?.(),v=null,a?.removeEventListener("abort",rt),b.dispose(),et()},Se=()=>{if(m){if(d.length>0){let g=m;m=null,g.resolve({value:d.shift(),done:!1})}else if(w!==null){let g=m;m=null,g.reject(w)}else if(l){let g=m;m=null,g.resolve({value:void 0,done:!0})}}},Nt=g=>{l||(d.push(g),Se())},O=g=>{l||(w=g,l=!0,y(g),ee(),Se())},tt=g=>{l||(l=!0,p(g),ee(),Se())},rt=()=>{let g=a?.reason;O(g instanceof re?g:new ne(e))},jt=g=>{if(!(l||!g||typeof g!="object"))switch(et(),g.t){case"delta":typeof g.delta=="string"&&Nt(g.delta);break;case"response":tt(g.body);break;case"error":{let{message:C,code:D}=zr(g.body);O(new re(C,{requestId:e,code:g.code??D}));break}}},Wt=()=>{let g=b.messages()[Symbol.asyncIterator]();h=()=>{g.return?.(void 0)};let C=()=>{Z&&g.next().then(D=>{if(Z){if(D.done){l||tt(void 0);return}jt(D.value),C()}},D=>{Z&&O(D)})};C()},nt=()=>{if(!u){if(u=!0,a){if(a.aborted){O(new ne(e));return}a.addEventListener("abort",rt,{once:!0})}v=c?.(g=>O(g))??null,Wt(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:o}}}),f&&f>0&&!n.synced&&(A=setTimeout(()=>{A=null,!l&&!n.synced&&O(new Te(f,e))},f),I=n.onSynced(()=>Qe()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(nt(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(w!==null){let g=w;return w=null,Promise.reject(g)}return l?Promise.resolve({value:void 0,done:!0}):new Promise((g,C)=>{m={resolve:g,reject:C}})},return(){return l||(l=!0,p(void 0),ee()),Promise.resolve({value:void 0,done:!0})},throw(g){return l||(l=!0,y(g),ee()),Promise.reject(g)}}}},body:_,start:nt}}function Ct(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 Jr(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:o,br:i}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let c=Ct(o);c&&(a.rt=c);let f=Ct(i);return f&&(a.br=f),a}var Ge=class{constructor(e,t,r,s,o){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;this._onActivity=o;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,s=!1,o={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(o);let i=()=>{s=!0,e._messageConsumers.delete(o)};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 i(),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._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let s of r)s(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=Jr(t,this._name),s=r?.br;if(s?.by==="runtime")throw new Ae(this._name,"runtime","browser");if(s)return;let o={br:{epoch:1}};r?.rt&&(o.rt=r.rt);let i=r?.kind??e;i&&(o.kind=i),t.set({streams:{[this._name]:o}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??je;return Rt(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){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},Q=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new ct;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_dialNegotiationStarted=!1;constructor(e,t,r,s,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=o,this._streamData=it(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Fe(()=>this.recover()),this._activity=qe({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new W({onPhase:i=>this.onPhase(i),hint:()=>this.doc(Ie).get(Ce)??this.doc("control").get(Pe),onData:(i,a)=>this._streamData.onData(i,a)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await bt({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,o=new te,i=new ae({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,o,i,ze(t),H({...t,baseUrl:r.baseUrl}));return i.on("connected",()=>{i.multiplexer&&o.setTarget(i.multiplexer)}),i.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),i.setEndsAt(r.endsAt),se()&&await ie(),a.setDocTransport({wsUrl:r.wsUrl,token:s}),await i.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}whenLive(e){return Ee(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 N(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 M(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new M(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 Ge(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._activity?.touch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new dt(e,this._sessionId,Br.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=ut(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=ot(e.wsUrl),r=`${t}\0${e.token??""}\0${this._sessionId}`;r!==this._docEndpointKey&&(this._docEndpointKey=r,this.connectDocs(at({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=Ve(),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 o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;o=setTimeout(()=>s.abort(new ke(a,r)),a)}let i=this._consumeResponse(r,e,!1,s.signal);return i.start(),i.body.finally(()=>{o&&clearTimeout(o)})}_consumeResponse(e,t,r,s,o){this._activity?.touch();let i=this.doc(Kr),a=Gr(e);return Yr(i,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??Pt)}requestStream(e,t={}){let r=Ve();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Ve(),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)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=It(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t)}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.disconnect(),e)),this._endPromise):Promise.reject(new j)}disconnect(){let e=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let r of e)try{r()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._activation.dispose(),this._recoveryHooks.clear();let t=Array.from(this._activeRequests);this._activeRequests.clear();for(let r of t)try{r(new Re)}catch{}for(let r of this._docs.values())r.dispose();this._docs.clear();for(let r of this._streams.values())r.dispose();this._streams.clear(),this._transport.disconnect()}};function Mt(n){return`urun:logical:v1:${n.orgId}:${n.app}:${n.functionName}`}function Ye(){try{return globalThis.sessionStorage??null}catch{return null}}function xt(n){let e=Ye();if(!e)return null;try{let t=e.getItem(n);if(!t)return null;let r=JSON.parse(t);return typeof r?.logicalId!="string"||r.logicalId.length===0?null:{logicalId:r.logicalId}}catch{return null}}function Ot(n,e){let t=Ye();if(t)try{t.setItem(n,JSON.stringify({logicalId:e.logicalId}))}catch{}}function ye(n){let e=Ye();if(e)try{e.removeItem(n)}catch{}}var Xr=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Qr(n,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(t,r){if(!(Xr.has(r)||typeof r!="string"))return s=>{let o=s??{},i=Mt({orgId:e.orgId,app:n,functionName:r}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,c=a(),f=new te,d=new ae({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c}),m=new Q(c,f,d,ze(e),H(e)),l,w=e.jwt,u,p=new Promise(h=>{u=h}),y=h=>{l=h,u({status:"ready",handle:h})};m.setEndHandler(async()=>{let h=l?{status:"ready",handle:l}:await p;if(h.status==="unavailable")throw new j("[urun] session allocation failed before a releasable request was created",{cause:h.cause});let v=h.handle;return ye(i),gt({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})});let _=async h=>{let v=await yt({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:h,sessionKey:e.sessionKey??xt(i)?.logicalId,priority:e.priority,onAdmission:I=>d.reportAdmission(I),onRequest:y}),A=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return w=A,e.sessionKey||Ot(i,{logicalId:v.sessionId}),m.setSessionId(v.sessionId),m.setArtifactsAuth(H({...e,baseUrl:v.baseUrl})),d.setEndsAt(v.endsAt),{url:v.wsUrl,sessionId:v.sessionId,jwt:A,iceServers:v.response.ice_servers,endsAt:v.endsAt}},b;if(d.setConnectionResolver(async()=>{let h=await _(a());return b=h.jwt,h}),d.on("connected",()=>{d.multiplexer&&f.setTarget(d.multiplexer);let h=d.connectedUrl;h&&m.setDocTransport({wsUrl:h,token:b})}),(async()=>{let h;try{h=await _(c)}catch(v){console.error(`[urun] Failed to create session for ${r}:`,v),ye(i);let A=v instanceof Error?v:new Error(String(v)),I=v instanceof R?v.httpStatus:void 0;d.reportAllocationFailure(A,I),u({status:"unavailable",cause:v});return}d.setAuth({jwt:h.jwt,authProvider:e.authProvider,orgId:e.orgId}),d.setConnection({url:h.url,sessionId:h.sessionId,iceServers:h.iceServers}),se()&&await ie(),b=h.jwt,m.setDocTransport({wsUrl:h.url,token:h.jwt}),await d.connect({app:n,functionName:r,args:o}),m.negotiateMediaTransport({allowWebTransport:e.allowWebTransport})})().catch(h=>{console.error(`[urun] Failed to connect session for ${r}:`,h)}),e.releaseOnLeave!==!1){let h=Ne(()=>{let v=l;v&&(ye(i),Oe({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:w,authProvider:e.authProvider}))});m.onDisconnect(h)}return m}}})}var Dt="https://api.urun.sh",x=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Zr(n,e={}){if(!n)throw new x("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=S(e.baseUrl??Dt),s={};e.expiresIn!==void 0&&(s.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(s.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(s.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(s.max_session_s=e.maxSessionS),e.subject!==void 0&&(s.subject=e.subject),e.metadata!==void 0&&(s.metadata=e.metadata);let o;try{o=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(s)})}catch(l){throw new x(`[urun] client token mint request failed: ${l instanceof Error?l.message:String(l)}`)}let i={};try{i=await o.json()}catch{}if(!o.ok){let l=typeof i.message=="string"?i.message:`HTTP ${o.status}`;throw new x(`[urun] client token mint failed: ${l}`,o.status)}let a=typeof i.token=="string"?i.token:"",c=typeof i.org_id=="string"?i.org_id:"",f=typeof i.expires_at=="string"?Date.parse(i.expires_at):Number.NaN,d=typeof i.expires_in=="number"?i.expires_in:void 0;if(!a)throw new x("[urun] client token mint returned no token (control-plane contract violation)",o.status);let m=Number.isFinite(f)?new Date(f):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:m,orgId:c}}var Ut=3e4,Lt="stream:",Je=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 o=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(o.timer),s.error?o.reject(new Error(s.error)):o.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=`${Lt}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${Lt}${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 o=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),s(new Error(`RPC request "${e}" timed out after ${Ut}ms`)))},Ut);this._pendingRpc.set(o,{resolve:r,reject:s,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function en(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 o=new st(s);return new Je(s,o)}var tn='video/mp4; codecs="avc1.42E01E"';function rn(n,e){let t=e?.codec??tn,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let s=new MediaSource,o=URL.createObjectURL(s);r.src=o,s.addEventListener("sourceopen",()=>{let l;try{l=s.addSourceBuffer(t)}catch(y){throw y instanceof DOMException&&y.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).`):y}let w=n.getReader();function u(){return l.updating?new Promise(y=>{l.addEventListener("updateend",()=>y(),{once:!0})}):Promise.resolve()}async function p(){try{for(;;){let{done:y,value:_}=await w.read();if(y){await u(),s.readyState==="open"&&s.endOfStream();return}await u();try{l.appendBuffer(_)}catch(b){if(b instanceof DOMException&&b.name==="QuotaExceededError"){let h=l.buffered;if(h.length>0){let v=h.start(h.length-1);l.remove(0,v),await u(),l.appendBuffer(_)}else throw b}else throw b}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}p()}),r.play().catch(()=>{});let i=r,a=i.captureStream??i.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),f=c.getTracks(),d=0,m=f.length;if(m===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let l of f)l.addEventListener("ended",()=>{d++,d>=m&&URL.revokeObjectURL(o)});return c}function nn(n){return n.status.startsWith("pending_")}var be=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 qt(n){let e=[];return n.audio&&e.push("audio"),n.video&&e.push("video"),e.join("+")}function sn(n,e){return e==="audio"?n.getAudioTracks():n.getVideoTracks()}function on(n,e){let t=n.getTracks();if(t.length===1&&t[0]===e)return n;try{return new MediaStream([e])}catch{return n}}function Xe(n,e){for(let t of[...n.lostListeners])try{t(e)}catch{}}var _e=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,Xe(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 be;return t=>e.getUserMedia(t)}async converge(e){for(let i of this.claims.values())i.track&&(i.track.stop(),i.track=null,i.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(i){let a=`one-capture getUserMedia(${qt(r)}) failed`,c=i instanceof Error?i.message:String(i);for(let f of[...this.claims.values()])if(this.claims.delete(f.kind),f.released=!0,f!==e){let d=new Error(`${a} \u2014 ${f.kind} capture lost: ${c||i}`);d.cause=i,Xe(f,d)}throw i}let o=[...this.claims.values()].sort((i,a)=>i===e?1:a===e?-1:0);for(let i of o){let a=sn(s,i.kind)[0]??null;if(i.released){a?.stop();continue}if(!a){this.claims.delete(i.kind),i.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${qt(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===e)throw c;Xe(i,c);continue}if(i.track=a,i.stream=on(s,a),i!==e)for(let c of[...i.trackListeners])try{c(a,i.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(o){return r.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=o,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(o){return s.trackListeners.add(o),()=>s.trackListeners.delete(o)},onLost(o){return s.lostListeners.add(o),()=>s.lostListeners.delete(o)}}};return s}},an=null;function cn(){return an??=new _e}var Ft="input",dn=30;function un(n){let e=n.now??Date.now,t=n.field??Ft,r=1e3/Math.max(n.hz??30,.001),s=new Set,o=0,i=0,a=0,c=0,f,d=null,m=!1,l=()=>{if(m)return;f=e(),c+=1;let u={keys:[...s],buttons:o,pointer:{x:i,y:a},seq:c,at:f};try{n.awareness.setLocalStateField(t,u)}catch{}},w=()=>{if(m)return;let u=e();if(f===void 0||u-f>=r){d&&(clearTimeout(d),d=null),l();return}if(d)return;let p=Math.max(r-(u-f),0);d=setTimeout(()=>{d=null,l()},p),d.unref?.()};return{keyDown(u){let p=String(u).toLowerCase();s.has(p)||(s.add(p),w())},keyUp(u){let p=String(u).toLowerCase();s.delete(p)&&w()},setButtons(u){let p=Number.isFinite(u)?Number(u):0;p!==o&&(o=p,w())},movePointer(u,p){let y=Number.isFinite(u)?Number(u):0,_=Number.isFinite(p)?Number(p):0;y===0&&_===0||(i+=y,a+=_,w())},heldKeys(){return[...s]},clear(){m||(s.clear(),o=0,d&&(clearTimeout(d),d=null),l())},dispose(){if(m)return;let u=s.size>0||o!==0;s.clear(),o=0,d&&(clearTimeout(d),d=null),u&&l(),m=!0}}}export{Xt as ACTIVATION_COLD_BOOT_AFTER_MS,Qt as ACTIVATION_DEGRADED_AFTER_MS,Ce as ACTIVATION_HINT_PATH,Jt as ACTIVATION_STILL_AFTER_MS,Le as ACTIVITY_DOM_EVENTS,Tt as ACTIVITY_FIELD,Rr as ACTIVITY_STAMP_MIN_INTERVAL_MS,W as ActivationMonitor,Qr as App,pt as BACKOFF_BASE_MS,L as BACKOFF_MAX_ATTEMPTS,ft as BACKOFF_MAX_MS,_e as CaptureController,be as CaptureUnavailableError,x as ClientTokenError,Pt as DEFAULT_DOC_SYNC_TIMEOUT_MS,Dt as DEFAULT_GATEWAY_URL,$t as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,zt as DEFAULT_WHEN_LIVE_TIMEOUT_MS,V as DGRAM_HEADER_BYTES,Er as FOREGROUND_COALESCE_MS,G as FrameReassembler,dn as INPUT_PRESENCE_DEFAULT_HZ,Ft as INPUT_PRESENCE_FIELD,F as InvalidDurationError,Pe as LEGACY_ACTIVATION_HINT_PATH,Ie as PLATFORM_DOC_NAME,we as PermanentLockedError,ve as PinRequiresActiveTempError,Ht as ProduceAckTimeoutError,he as RecordingNotFoundError,N as RecordingsClient,T as RecordingsError,B as RecordingsUnauthorizedError,ne as RequestAbortError,Re as RequestCancelledError,Te as RequestDocSyncError,re as RequestError,ke as RequestTimeoutError,ge as RetainNotTempError,me as RuntimeArtifactNotFoundError,M as RuntimeArtifactsClient,k as RuntimeArtifactsError,fe as RuntimeArtifactsUnauthorizedError,Q as Session,R as SessionAllocationError,U as SessionEndError,j as SessionEndUnavailableError,Kt as SessionFailedError,Ae as StreamDirectionConflict,Y as TransportNegotiator,J as TransportSessionSignaling,Et as WT_CONTROL_FRAME_MAX,X as WebRtcSession,z as WebTransportSession,K as WtControlDecoder,lt as activationHintFrom,de as computeBackoffDelay,qe as createActivityTracker,Zr as createClientToken,un as createInputPresencePublisher,Ar as createRecordingsClient,wr as createRuntimeArtifactsClient,en as createStore,Bt as describeSessionFailure,Yt as describeSessionPhase,$e as encodeWtControlFrame,Ue as isDurationString,nn as isPendingRecording,ue as isRetryableSessionError,Gt as isWakingPhase,je as mediaRecorderChunkSource,kr as normalizeRetention,Fe as observePageLifecycle,Ne as observePageTeardown,He as parseDgramHeader,fr as prewake,Oe as releaseSessionBeacon,Vt as sessionFailureFromMediaError,cn as sharedCaptureController,rn as videoStream,Ee as whenLive,Mr as writeDgramHeader};
1
+ import{B as ae,D as ot,E as at,F as ct,G as dt,H as ut,a as st,b as te,c as j,d as U,e as re,f as ke,g as Te,h as Ae,i as Bt,j as Kt,k as ne,l as Re,m as Vt,n as Gt,o as zt,p as R,q as Yt,r as Jt,s as Ee,t as Xt,u as se,w as ie,x as oe,z as it}from"./chunk-WBUDJHD7.mjs";var Qt=15e3,Zt=45e3,er=12e4,Ie="platform",Ce="activation",Pe="desired.activation";function lt(n){if(typeof n=="string"&&n.length>0)return n;if(n&&typeof n=="object"){let e=n.note;if(typeof e=="string"&&e.length>0)return e}}var tr=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],W=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(t?.name==="error"||t?.name==="ended"||t?.name==="expired")&&this.dispose()}),this._stopped&&(this._offPhase(),this._offPhase=null)}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;watch(e,t){if(this._stopped||this._watches.has(e))return;let r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let s=()=>this._firstMedia(e);r.addEventListener("unmute",s,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",s));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of tr){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let s={state:t,elapsedMs:r,stream:e.name},o=lt(this._options.hint());o!==void 0&&(s.hint=o),e.lastEvent=s;for(let i of Array.from(this._handlers))i(s)}};var pt=500,ft=15e3,L=6;function de(n,e=Math.random){if(!Number.isFinite(n)||n<0)throw new Error(`[urun] computeBackoffDelay: attempt must be a non-negative number, got ${n}`);let t=Math.min(ft,pt*2**n);return Math.round(e()*t)}function ue(n){if(n instanceof R){let e=n.httpStatus;return e===408||e===429||e!==void 0&&e>=500}return n instanceof Error?n.name==="TypeError"||n.name==="TimeoutError"||n.name==="AbortError":!1}var mt=10,rr=.5,ce=mt;function Me(){return ce<1?!1:(ce-=1,!0)}function xe(){ce=Math.min(mt,ce+rr)}var nr="session-api.prod.cloud.urun.sh",sr=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function S(n){return n.trim().replace(/\/+$/,"")}function le(n,e){let t=[],r=s=>{if(!s)return;let o=S(s);o&&!t.includes(o)&&t.push(o)};r(n);for(let s of e??[])r(s);for(let s of _r(n))r(s);return t}function Oe(n){try{if(typeof fetch!="function")return;let e=`${S(n.baseUrl)}/api/session-requests/${encodeURIComponent(n.requestId)}/release`;fetch(e,{method:"POST",headers:q(n,n.jwt),keepalive:!0}).catch(()=>{})}catch{}}async function vt(n){try{let e=await $(n),t=await fetch(`${S(n.baseUrl)}/api/session-requests/${encodeURIComponent(n.requestId)}/release`,{method:"POST",headers:q(n,e)}),r=await pe(t);if(!t.ok)throw new U(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 U("[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 U?e:new U("[urun] session release request failed",{requestId:n.requestId,cause:e})}}function wt(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}var ir=120,or=1e3,ar=20,cr=5,dr=500,yt=1e4,ur=3;function lr(n,e){if(!n)return null;try{let t=new URL(n),r=e?new URL(S(e)):null,s=t.pathname==="/api/sessions/create"||t.pathname==="/api/sessions/create/";return t.protocol!=="https:"||!s||!pr(t,r)?null:S(t.origin)}catch{return null}}function pr(n,e){return ht(n.hostname)&&(!e||ht(e.hostname))}function ht(n){let e=n.toLowerCase();return e==="urun.sh"||e.endsWith(".urun.sh")}async function bt(n){let e=le(n.baseUrl,n.fallbackUrls),t=null,r=e.length>1;for(let s=0;s<L;s++){for(let o of e)try{let i=await fr(o,n,{pollAttempts:ir,retryAfterLimitMs:r?or:void 0});return xe(),i}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof E)throw t}if(!ue(t))break;if(s+1<L){if(!Me())break;await De(de(s))}}throw t??new Error("[urun] session allocation failed")}async function fr(n,e,t){let r,s,o,i=n,a=0,c=new Set,f=Date.now()+t.pollAttempts*yt;for(let d=0;d<t.pollAttempts;d++){s=o??await $(e),o=void 0;let l=Math.max(1,Math.min(ar,Math.floor((f-Date.now())/1e3))),p=!!r,w=Date.now(),u=r?await fetch(`${i}/api/session-requests/${encodeURIComponent(r)}?wait_s=${l}`,{headers:q(e,s),signal:wr((l+cr)*1e3)}):await fetch(`${i}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...q(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(mr(e))});if(!r&&(u.status===307||u.status===308)){let b=lr(u.headers.get("location"),i);if(b&&b!==i&&a<ur){a+=1,i=b;continue}throw new R(`[urun] session create redirected from ${i} without a usable target`,{httpStatus:u.status})}let m=await pe(u);if(m.request_id)try{e.onRequest?.({requestId:m.request_id,baseUrl:i})}catch{}if(u.ok&&(m.status==="allocated"||!m.status&&!!m.session_id)&&!!m.session_id){let b=m.session_id,h=St(m.ws_url,i,b,"gateway allocated session");return{baseUrl:i,sessionId:b,wsUrl:h,endsAt:wt(m.ends_at),response:m}}if(u.status===202||m.status==="pending"||m.status==="queued"||m.queued){if(r=m.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(gr(m,r))}catch{}let b=Date.now()-w<dr;p&&b&&await De(vr(u,m,t.retryAfterLimitMs));continue}if((u.status===401||u.status===403)&&e.getAccessToken){let b=s??"";c.add(b);let h=await $(e,{forceRefresh:!0,reason:"unauthorized"});if(h&&!c.has(h)){o=h,r=void 0;continue}}let _=m.error_message||m.error_code||`HTTP ${u.status}`;throw new R(`[urun] session allocation failed at ${i}: ${_}`,{httpStatus:u.status})}throw new R(`[urun] timed out waiting for session allocation at ${i}`)}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 $(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function mr(n){let e=n.priority==="preempt";return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey,...n.sessionKey&&!e?{logical_id:n.sessionKey}:{},...e?{priority:"preempt"}:{}}}async function _t(n){let e=le(n.baseUrl,n.fallbackUrls),t=null;for(let r=0;r<L;r++){for(let s of e)try{let o={baseUrl:s,app:"",functionName:"",orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider,idempotencyKey:""},i=await $(o),a=await fetch(`${S(s)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,{headers:q(o,i)});if(!a.ok)throw new R(`[urun] viewer-connect for ${n.sessionId} failed: HTTP ${a.status}`,{httpStatus:a.status});let c=await pe(a),f=St(c.ws_url,s,n.sessionId,"viewer-connect");return xe(),{baseUrl:S(s),sessionId:n.sessionId,wsUrl:f,endsAt:wt(c.ends_at),response:c}}catch(o){if(t=o instanceof Error?o:new Error(String(o)),t instanceof E)throw t}if(!ue(t))break;if(r+1<L){if(!Me())break;await De(de(r))}}throw t??new Error("[urun] viewer-connect failed")}async function hr(n){try{let e=S(n.baseUrl),t=await $(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 pe(r),o={status:s.status==="prebound"?"prebound":"warming"};return typeof s.expires_at=="string"&&(o.expiresAt=s.expires_at),typeof s.warm_capable=="boolean"&&(o.warmCapable=s.warm_capable),o}catch(e){return console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function pe(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function gr(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 vr(n,e,t){let r=Number(n.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??r),o=t??yt;return Number.isFinite(s)&&s>0?Math.min(s*1e3,o):1e3}function De(n){return new Promise(e=>setTimeout(e,n))}function wr(n){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(n):void 0}var E=class extends Error{};function St(n,e,t,r){if(!n)throw new E(`[urun] ${r} ${t} without ws_url`);let s,o;try{s=new URL(n)}catch{throw new E(r==="viewer-connect"?`[urun] viewer-connect returned no usable ws_url for ${t}`:`[urun] ${r} ${t} with non-absolute ws_url`)}try{o=new URL(S(e))}catch{throw new E(`[urun] ${r} ${t} has invalid gateway base URL`)}if(!(yr(o.hostname)&&o.protocol==="http:"&&s.protocol==="ws:"||s.protocol==="wss:"))throw new E(`[urun] ${r} ${t} with insecure ws_url`);if(!br(s,o))throw new E(`[urun] ${r} ${t} with cross-origin ws_url`);return s.toString()}function yr(n){return n==="localhost"||n==="127.0.0.1"||n==="::1"||n.endsWith(".localhost")}function br(n,e){return!!(n.hostname===e.hostname&&n.port===e.port||gt(n.hostname)&&gt(e.hostname))}function gt(n){return n==="urun.sh"||n.endsWith(".urun.sh")}function _r(n){try{return new URL(n).hostname!==nr?[]:sr}catch{return[]}}var k=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)}},fe=class extends k{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},me=class extends k{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function H(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function Sr(n){return new M(n)}var M=class{_options;constructor(e){this._options=e}async list(e){let r=Tt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new k("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(kt)}async getDownloadUrl(e,t){let r=Tt(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!Tr(s))throw new k("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:kt(r.artifact),downloadUrl:s}}async _request(e,t){let r=le(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let o of r)try{return await this._requestFromBase(o,e,t)}catch(i){if(s=i instanceof Error?i:new Error(String(i)),s instanceof k&&Ar(s.status))throw s}throw s??new k("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let s=`${S(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,o=await this._resolveToken(),i=await fetch(s,{method:"GET",headers:this._headers(o)});if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await fetch(s,{method:"GET",headers:this._headers(o)}))}if(!i.ok){let{code:a,message:c}=await this._readError(i,e);throw Rr(i.status,a,c)}try{return await i.json()}catch(a){throw new k(`[urun] runtime artifacts: invalid JSON response from ${S(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=S(t);try{let o=(await e.json()).error;if(o&&typeof o=="object"){let{code:i,message:a}=o;return{code:typeof i=="string"&&i.length>0?i:`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 kt(n){if(!n||typeof n!="object")throw new k("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=n,t=I(e,"artifact_id")||I(e,"id"),r=I(e,"filename"),s=I(e,"kind"),o=I(e,"status")||"ready",i=kr(e,"size_bytes"),a=I(e,"sha256");if(!t||!r||!s||i==null||!a)throw new k("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:r,contentType:I(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:I(e,"created_at"),expiresAt:I(e,"expires_at")}}function I(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function kr(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function Tr(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function Ar(n){return n===401||n===403}function Rr(n,e,t){return n===401?new fe(t,e):n===404?new me(t,e):new k(t,n,e)}function Tt(n){if(!n||typeof n!="object"||Array.isArray(n))throw new k("[urun] runtime artifacts: malformed response",0,"bad_response");return n}var T=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)}},B=class extends T{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},he=class extends T{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},ge=class extends T{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)}},ve=class extends T{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)}},we=class extends T{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)}},F=class extends T{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 Ue(n){return/^(\d+[smhdw])+$/.test(n)}function Er(n){if(n==="pin")return{action:"pin"};if(Ue(n))return{action:"retain",duration:n};throw new F(`[urun] recordings: "${n}" is not a duration or "pin"`)}function Ir(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new B(r,e??"unauthorized");if(n===404)return new he(r,e??"not_found");if(n===400)return new F(r,e??"bad_request",400);if(n===409)switch(e){case"retain_not_temp":return new ge(r,e);case"pin_requires_active_temp":return new ve(r,e);case"permanent_locked":return new we(r,e)}return new T(r,{status:n,code:e??`http_${n}`})}var N=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(!Ue(t))throw new F(`[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 T("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),o=await this._resolveToken(),i=await this._fetch(s,e,o,r.body);if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await this._fetch(s,e,o,r.body))}if(!i.ok){let{code:a,message:c}=await this._readError(i);throw Ir(i.status,a,c)}return this._readJson(i)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,i])=>`${encodeURIComponent(o)}=${encodeURIComponent(i)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r,s){let o={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(o["X-Auth-Provider"]=this._options.authProvider);let i={method:t,headers:o};return s!==void 0&&(o["Content-Type"]="application/json",i.body=JSON.stringify(s)),fetch(e,i)}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 B("[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:o}=r;return{code:typeof s=="string"?s:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Cr(n){return new N(n)}var At="activity",Rt="visibility",Pr=15e3,Le=["pointerdown","pointermove","keydown","wheel","touchstart"];function qe(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,o,i=()=>{if(s)return;let l=e();if(!(o!==void 0&&l-o<15e3)){o=l;try{n.awareness.setLocalStateField(At,{at:l})}catch{}}},a=()=>{if(!(s||!r||r.visibilityState===void 0))try{n.awareness.setLocalStateField(Rt,r.visibilityState)}catch{}},c=()=>i(),f=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&i()};if(t)for(let l of Le)t.addEventListener(l,c,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",f);let d=null;return n.isProducing&&(d=setInterval(()=>{if(!s)try{n.isProducing?.()&&i()}catch{}},15e3),d.unref?.()),i(),a(),{touch:i,dispose(){if(!s){if(s=!0,t)for(let l of Le)t.removeEventListener(l,c,{capture:!0});r&&r.removeEventListener("visibilitychange",f),d&&(clearInterval(d),d=null)}}}}var Mr=250;function Fe(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)}}function Ne(n){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,n())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}var Et="video/mp4";function je(n,e={}){let t=e.timesliceMs??1e3,r=null,s=null,o=!1,i=(a,c,f)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let l=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(Et)?Et:void 0),p=new MediaStream([a]),w=new d(p,l?{mimeType:l}:void 0);r=w;let u=Promise.resolve();w.ondataavailable=m=>{let y=m.data;o||!y||y.size===0||(u=u.then(async()=>{let _=new Uint8Array(await y.arrayBuffer());o||c(_)}))},w.onstop=()=>{u.then(()=>{o||f()})},w.onerror=()=>{u.then(()=>{o||f()})},w.start(t)};return{start(a,c){if(r||o)return;let f=n.track();if(f){i(f,a,c);return}s=n.onTrack(d=>{!d||r||o||(s?.(),s=null,i(d,a,c))})},stop(){if(o)return;o=!0,s?.(),s=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function xr(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 It(n,e){let t=null,r=!1,s=!1,o=new ReadableStream({pull(i){r||(r=!0,t=n(e),t.start(a=>{if(!s)try{i.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{i.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return xr(o)}import{encode as Or,decode as Dr}from"@msgpack/msgpack";var Ct=65536;function $e(n){let e=Or(n),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var K=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>Ct)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(Dr(s))}return t}},V=12,We=1;function He(n){let e=n.getUint8(8);return{groupId:n.getUint32(0,!0),frameSeq:n.getUint32(4,!0),keyframe:(e&We)===We,fragIndex:n.getUint8(9),fragCount:n.getUint8(10)}}function Ur(n){let e=new Uint8Array(V),t=new DataView(e.buffer);return t.setUint32(0,n.groupId,!0),t.setUint32(4,n.frameSeq,!0),t.setUint8(8,n.keyframe?We:0),t.setUint8(9,n.fragIndex),t.setUint8(10,n.fragCount),t.setUint8(11,0),e}var Lr=100,G=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??Lr}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<V)return;let t=He(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(V),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++)}}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let r=t.chunks.reduce((i,a)=>i+a.byteLength,0),s=new Uint8Array(r),o=0;for(let i of t.chunks)s.set(i,o),o+=i.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 qr=/^avc[13]\.[0-9a-fA-F]{6}$/;function Fr(n){return qr.test(n)?null:`codec ${JSON.stringify(n)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function Be(n,e){let t=Fr(n);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var Nr=250,jr=3,Wr=1e4,Ke=2500,z=class{constructor(e,t,r){this.offer=e;this.sessionId=t;this.canvas=r;this.firstMedia=new Promise((s,o)=>{this.firstFrameResolve=s,this.firstFrameReject=o}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorsAt=[];writer;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;reassembler=new G({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;firstFrameOutput=!1;firstDecodeTimer=null;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");Be(this.offer.codec,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(a=>({algorithm:"sha-256",value:Uint8Array.from(atob(a),c=>c.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let t=await this.wt.createBidirectionalStream();this.writer=t.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let r=t.readable.getReader(),s=new K,o=[],i=await this.readControl(r,s,o);if(i?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");Be(i.codec,"hello-ack"),this.initDecoder(i.codec,i.width,i.height),this.controlLoop(r,s,o).catch(a=>this.die(`control loop: ${a}`)),this.datagramLoop().catch(a=>this.die(`datagram loop: ${a}`)),this.feedbackLoop(),this.wt.closed.then(()=>this.die("connection closed")).catch(a=>this.die(`connection error: ${a}`))}async stop(){this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null;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 o=this.canvas.getContext("2d");if(!o)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r},this.decoder=new s({output:i=>{this.firstFrameOutput=!0,this.firstDecodeTimer&&(clearTimeout(this.firstDecodeTimer),this.firstDecodeTimer=null),this.canvas.width=i.displayWidth,this.canvas.height=i.displayHeight,o.drawImage(i,0,0),i.close()},error:i=>this.onDecoderError(i)}),this.decoder.configure({codec:e,...t>0&&r>0?{codedWidth:t,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"})}onDecoderError(e){if(this.stopped||this.deadFired)return;let t=performance.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(s=>t-s<Wr),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=jr){this.die(`decoder: ${e.message}`);return}console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=this.decoderConfig;if(!r){this.die(`decoder: ${e.message} (no config to re-init from)`);return}try{this.initDecoder(r.codec,r.width,r.height)}catch(s){this.die(`decoder re-init: ${s instanceof Error?s.message:String(s)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}armFirstDecodeDeadline(){if(this.firstDecodeTimer||this.firstFrameOutput||this.stopped||this.deadFired)return;let e=setTimeout(()=>{this.firstDecodeTimer=null,!(this.firstFrameOutput||this.stopped||this.deadFired)&&(console.error(`[urun] webtransport: media datagrams arriving but NO frame decoded within ${Ke}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${Ke}ms`))},Ke);e.unref?.(),this.firstDecodeTimer=e}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:r}=await e.read();if(r)break;if(!t)continue;this.armFirstDecodeDeadline();let s=performance.now();if(this.lastArrivalTs>0){let o=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(o-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($e(e))}async readControl(e,t,r=[]){for(;;){let s=r.shift();if(s)return s;let{value:o,done:i}=await e.read();if(i)return null;o&&r.push(...t.push(o))}}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(),o=s.delivered+s.abandoned;this.lastStats={recvBps:r>0?s.bytes*8/r:0,lossPct:o>0?100*s.abandoned/o:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Nr)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var $r=2500,Hr=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Y=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,o={webtransport:t&&r&&s,webcodecs:r,codecs:Hr};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:o});let i=o.webtransport&&!!this.offer.webtransport;if(o.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),i){let a=null;try{return a=this.createWebTransportSession(),await Br(a.start(),this.opts.quicDeadlineMs??$r,"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(),i||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 z(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(){let e=this.session;e.onDead(t=>{console.warn("[urun] quic died mid-session, failing over to webrtc:",t),e.stop().catch(()=>{}),(async()=>{try{this.session=await this.startWebRtc(),this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(r){this.session=null,console.error("[urun] failover to webrtc also failed:",r)}})()})}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function Br(n,e,t){return new Promise((r,s)=>{let o=setTimeout(()=>s(new Error(t)),e);n.then(i=>{clearTimeout(o),r(i)},i=>{clearTimeout(o),s(i)})})}var Kr=1e4,J=class{constructor(e,t=Kr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=oe();return new Promise((s,o)=>{let i=setTimeout(()=>{a(),o(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(i),a(),c.error){o(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:f,requestId:d,...l}=c;s(l)});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)})}};var Vr="video",X=class{constructor(e,t=Vr){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};var Gr="video";function Pt(n,e,t){let r=globalThis,s=r.document;if(!(typeof s?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let i=s.createElement("canvas"),a=!1,c=null,f=!1,d=()=>{if(c){for(let u of c.getVideoTracks())try{u.stop()}catch{}c=null}f&&(f=!1,t.onOverrideTrack(null))},l=new Y(new J(n),e,{canvas:i,createWebRtcSession:t.createWebRtcSession??(()=>new X(n,t.streamName??Gr)),createWebTransportSession:t.createWebTransportSession,onTransportChange:(u,m)=>{u==="webrtc"&&d(),t.onTransportChange?.(u,m)}}),p=null,w=()=>{p!==null&&(clearTimeout(p),p=null)};return(async()=>{let u=await l.connect();if(a||u.kind!=="webtransport")return;let m=t.firstMediaWarnMs??1e4;if(p=setTimeout(()=>{a||l.activeTransport!=="webtransport"||console.warn(`[urun] webtransport established but no QUIC media after ${m}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)},m),await u.firstMedia,w(),a||l.activeTransport!=="webtransport"||typeof i.captureStream!="function")return;c=i.captureStream();let y=c.getVideoTracks()[0];y&&(f=!0,t.onOverrideTrack(y))})().catch(u=>{w(),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",u)}),{activeTransport:()=>l.activeTransport,dispose(){a=!0,w(),d(),l.disconnect().catch(()=>{})}}}var zr=new Set;function ze(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var Yr="rpc",xt=3e4,Jr="rpc-resp";function Xr(n){return`${Jr}:${n}`}function Ve(){return oe()}function Qr(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 Zr(n,e,t,r,s,o,i,a,c,f){let d=[],l=null,p=!1,w=null,u=!1,m,y,_=new Promise((g,P)=>{m=g,y=P});_.catch(()=>{});let b=i(),h=null,v=null,A=null,C=null,Z=!0,Qe=()=>{A&&(clearTimeout(A),A=null),C&&(C(),C=null)},Ze=!1,et=()=>{Ze||!u||(Ze=!0,n.set({rpc:{[e]:null}}))},ee=()=>{Z=!1,Qe(),h?.(),h=null,v?.(),v=null,a?.removeEventListener("abort",rt),b.dispose(),et()},Se=()=>{if(l){if(d.length>0){let g=l;l=null,g.resolve({value:d.shift(),done:!1})}else if(w!==null){let g=l;l=null,g.reject(w)}else if(p){let g=l;l=null,g.resolve({value:void 0,done:!0})}}},Wt=g=>{p||(d.push(g),Se())},O=g=>{p||(w=g,p=!0,y(g),ee(),Se())},tt=g=>{p||(p=!0,m(g),ee(),Se())},rt=()=>{let g=a?.reason;O(g instanceof re?g:new ne(e))},$t=g=>{if(!(p||!g||typeof g!="object"))switch(et(),g.t){case"delta":typeof g.delta=="string"&&Wt(g.delta);break;case"response":tt(g.body);break;case"error":{let{message:P,code:D}=Qr(g.body);O(new re(P,{requestId:e,code:g.code??D}));break}}},Ht=()=>{let g=b.messages()[Symbol.asyncIterator]();h=()=>{g.return?.(void 0)};let P=()=>{Z&&g.next().then(D=>{if(Z){if(D.done){p||tt(void 0);return}$t(D.value),P()}},D=>{Z&&O(D)})};P()},nt=()=>{if(!u){if(u=!0,a){if(a.aborted){O(new ne(e));return}a.addEventListener("abort",rt,{once:!0})}v=c?.(g=>O(g))??null,Ht(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:o}}}),f&&f>0&&!n.synced&&(A=setTimeout(()=>{A=null,!p&&!n.synced&&O(new Te(f,e))},f),C=n.onSynced(()=>Qe()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(nt(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(w!==null){let g=w;return w=null,Promise.reject(g)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((g,P)=>{l={resolve:g,reject:P}})},return(){return p||(p=!0,m(void 0),ee()),Promise.resolve({value:void 0,done:!0})},throw(g){return p||(p=!0,y(g),ee()),Promise.reject(g)}}}},body:_,start:nt}}function Mt(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 en(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:o,br:i}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let c=Mt(o);c&&(a.rt=c);let f=Mt(i);return f&&(a.br=f),a}var Ge=class{constructor(e,t,r,s,o){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;this._onActivity=o;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,s=!1,o={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(o);let i=()=>{s=!0,e._messageConsumers.delete(o)};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 i(),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._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let s of r)s(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=en(t,this._name),s=r?.br;if(s?.by==="runtime")throw new Ae(this._name,"runtime","browser");if(s)return;let o={br:{epoch:1}};r?.rt&&(o.rt=r.rt);let i=r?.kind??e;i&&(o.kind=i),t.set({streams:{[this._name]:o}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??je;return It(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){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},Q=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new ct;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_dialNegotiationStarted=!1;constructor(e,t,r,s,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=o,this._streamData=it(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Fe(()=>this.recover()),this._activity=qe({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new W({onPhase:i=>this.onPhase(i),hint:()=>this.doc(Ie).get(Ce)??this.doc("control").get(Pe),onData:(i,a)=>this._streamData.onData(i,a)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await _t({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,o=new te,i=new ae({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,o,i,ze(t),H({...t,baseUrl:r.baseUrl}));return i.on("connected",()=>{i.multiplexer&&o.setTarget(i.multiplexer)}),i.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),i.setEndsAt(r.endsAt),se()&&await ie(),a.setDocTransport({wsUrl:r.wsUrl,token:s}),await i.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}whenLive(e){return Ee(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 N(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 M(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new M(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 Ge(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._activity?.touch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new dt(e,this._sessionId,zr.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=ut(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=ot(e.wsUrl),r=`${t}\0${e.token??""}\0${this._sessionId}`;r!==this._docEndpointKey&&(this._docEndpointKey=r,this.connectDocs(at({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=Ve(),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 o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;o=setTimeout(()=>s.abort(new ke(a,r)),a)}let i=this._consumeResponse(r,e,!1,s.signal);return i.start(),i.body.finally(()=>{o&&clearTimeout(o)})}_consumeResponse(e,t,r,s,o){this._activity?.touch();let i=this.doc(Yr),a=Xr(e);return Zr(i,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??xt)}requestStream(e,t={}){let r=Ve();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Ve(),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)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=Pt(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t)}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.disconnect(),e)),this._endPromise):Promise.reject(new j)}disconnect(){let e=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let r of e)try{r()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._activation.dispose(),this._recoveryHooks.clear();let t=Array.from(this._activeRequests);this._activeRequests.clear();for(let r of t)try{r(new Re)}catch{}for(let r of this._docs.values())r.dispose();this._docs.clear();for(let r of this._streams.values())r.dispose();this._streams.clear(),this._transport.disconnect()}};function Ot(n){return`urun:logical:v1:${n.orgId}:${n.app}:${n.functionName}`}function Ye(){try{return globalThis.sessionStorage??null}catch{return null}}function Dt(n){let e=Ye();if(!e)return null;try{let t=e.getItem(n);if(!t)return null;let r=JSON.parse(t);return typeof r?.logicalId!="string"||r.logicalId.length===0?null:{logicalId:r.logicalId}}catch{return null}}function Ut(n,e){let t=Ye();if(t)try{t.setItem(n,JSON.stringify({logicalId:e.logicalId}))}catch{}}function ye(n){let e=Ye();if(e)try{e.removeItem(n)}catch{}}var tn=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function rn(n,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(t,r){if(!(tn.has(r)||typeof r!="string"))return s=>{let o=s??{},i=Ot({orgId:e.orgId,app:n,functionName:r}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,c=a(),f=new te,d=new ae({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c}),l=new Q(c,f,d,ze(e),H(e)),p,w=e.jwt,u,m=new Promise(h=>{u=h}),y=h=>{p=h,u({status:"ready",handle:h})};l.setEndHandler(async()=>{let h=p?{status:"ready",handle:p}:await m;if(h.status==="unavailable")throw new j("[urun] session allocation failed before a releasable request was created",{cause:h.cause});let v=h.handle;return ye(i),vt({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})});let _=async h=>{let v=await bt({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:h,sessionKey:e.sessionKey??Dt(i)?.logicalId,priority:e.priority,onAdmission:C=>d.reportAdmission(C),onRequest:y}),A=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return w=A,e.sessionKey||Ut(i,{logicalId:v.sessionId}),l.setSessionId(v.sessionId),l.setArtifactsAuth(H({...e,baseUrl:v.baseUrl})),d.setEndsAt(v.endsAt),{url:v.wsUrl,sessionId:v.sessionId,jwt:A,iceServers:v.response.ice_servers,endsAt:v.endsAt}},b;if(d.setConnectionResolver(async()=>{let h=await _(a());return b=h.jwt,h}),d.on("connected",()=>{d.multiplexer&&f.setTarget(d.multiplexer);let h=d.connectedUrl;h&&l.setDocTransport({wsUrl:h,token:b})}),(async()=>{let h;try{h=await _(c)}catch(v){console.error(`[urun] Failed to create session for ${r}:`,v),ye(i);let A=v instanceof Error?v:new Error(String(v)),C=v instanceof R?v.httpStatus:void 0;d.reportAllocationFailure(A,C),u({status:"unavailable",cause:v});return}d.setAuth({jwt:h.jwt,authProvider:e.authProvider,orgId:e.orgId}),d.setConnection({url:h.url,sessionId:h.sessionId,iceServers:h.iceServers}),se()&&await ie(),b=h.jwt,l.setDocTransport({wsUrl:h.url,token:h.jwt}),await d.connect({app:n,functionName:r,args:o}),l.negotiateMediaTransport({allowWebTransport:e.allowWebTransport})})().catch(h=>{console.error(`[urun] Failed to connect session for ${r}:`,h)}),e.releaseOnLeave!==!1){let h=Ne(()=>{let v=p;v&&(ye(i),Oe({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:w,authProvider:e.authProvider}))});l.onDisconnect(h)}return l}}})}var Lt="https://api.urun.sh",x=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function nn(n,e={}){if(!n)throw new x("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=S(e.baseUrl??Lt),s={};e.expiresIn!==void 0&&(s.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(s.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(s.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(s.max_session_s=e.maxSessionS),e.subject!==void 0&&(s.subject=e.subject),e.metadata!==void 0&&(s.metadata=e.metadata);let o;try{o=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(s)})}catch(p){throw new x(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let i={};try{i=await o.json()}catch{}if(!o.ok){let p=typeof i.message=="string"?i.message:`HTTP ${o.status}`;throw new x(`[urun] client token mint failed: ${p}`,o.status)}let a=typeof i.token=="string"?i.token:"",c=typeof i.org_id=="string"?i.org_id:"",f=typeof i.expires_at=="string"?Date.parse(i.expires_at):Number.NaN,d=typeof i.expires_in=="number"?i.expires_in:void 0;if(!a)throw new x("[urun] client token mint returned no token (control-plane contract violation)",o.status);let l=Number.isFinite(f)?new Date(f):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:l,orgId:c}}var qt=3e4,Ft="stream:",Je=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 o=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(o.timer),s.error?o.reject(new Error(s.error)):o.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=`${Ft}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${Ft}${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 o=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),s(new Error(`RPC request "${e}" timed out after ${qt}ms`)))},qt);this._pendingRpc.set(o,{resolve:r,reject:s,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function sn(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 o=new st(s);return new Je(s,o)}var on='video/mp4; codecs="avc1.42E01E"';function an(n,e){let t=e?.codec??on,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let s=new MediaSource,o=URL.createObjectURL(s);r.src=o,s.addEventListener("sourceopen",()=>{let p;try{p=s.addSourceBuffer(t)}catch(y){throw y instanceof DOMException&&y.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).`):y}let w=n.getReader();function u(){return p.updating?new Promise(y=>{p.addEventListener("updateend",()=>y(),{once:!0})}):Promise.resolve()}async function m(){try{for(;;){let{done:y,value:_}=await w.read();if(y){await u(),s.readyState==="open"&&s.endOfStream();return}await u();try{p.appendBuffer(_)}catch(b){if(b instanceof DOMException&&b.name==="QuotaExceededError"){let h=p.buffered;if(h.length>0){let v=h.start(h.length-1);p.remove(0,v),await u(),p.appendBuffer(_)}else throw b}else throw b}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}m()}),r.play().catch(()=>{});let i=r,a=i.captureStream??i.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),f=c.getTracks(),d=0,l=f.length;if(l===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let p of f)p.addEventListener("ended",()=>{d++,d>=l&&URL.revokeObjectURL(o)});return c}function cn(n){return n.status.startsWith("pending_")}var be=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 Nt(n){let e=[];return n.audio&&e.push("audio"),n.video&&e.push("video"),e.join("+")}function dn(n,e){return e==="audio"?n.getAudioTracks():n.getVideoTracks()}function un(n,e){let t=n.getTracks();if(t.length===1&&t[0]===e)return n;try{return new MediaStream([e])}catch{return n}}function Xe(n,e){for(let t of[...n.lostListeners])try{t(e)}catch{}}var _e=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,Xe(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 be;return t=>e.getUserMedia(t)}async converge(e){for(let i of this.claims.values())i.track&&(i.track.stop(),i.track=null,i.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(i){let a=`one-capture getUserMedia(${Nt(r)}) failed`,c=i instanceof Error?i.message:String(i);for(let f of[...this.claims.values()])if(this.claims.delete(f.kind),f.released=!0,f!==e){let d=new Error(`${a} \u2014 ${f.kind} capture lost: ${c||i}`);d.cause=i,Xe(f,d)}throw i}let o=[...this.claims.values()].sort((i,a)=>i===e?1:a===e?-1:0);for(let i of o){let a=dn(s,i.kind)[0]??null;if(i.released){a?.stop();continue}if(!a){this.claims.delete(i.kind),i.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${Nt(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===e)throw c;Xe(i,c);continue}if(i.track=a,i.stream=un(s,a),i!==e)for(let c of[...i.trackListeners])try{c(a,i.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(o){return r.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=o,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(o){return s.trackListeners.add(o),()=>s.trackListeners.delete(o)},onLost(o){return s.lostListeners.add(o),()=>s.lostListeners.delete(o)}}};return s}},ln=null;function pn(){return ln??=new _e}var jt="input",fn=30;function mn(n){let e=n.now??Date.now,t=n.field??jt,r=1e3/Math.max(n.hz??30,.001),s=new Set,o=0,i=0,a=0,c=0,f,d=null,l=!1,p=()=>{if(l)return;f=e(),c+=1;let u={keys:[...s],buttons:o,pointer:{x:i,y:a},seq:c,at:f};try{n.awareness.setLocalStateField(t,u)}catch{}},w=()=>{if(l)return;let u=e();if(f===void 0||u-f>=r){d&&(clearTimeout(d),d=null),p();return}if(d)return;let m=Math.max(r-(u-f),0);d=setTimeout(()=>{d=null,p()},m),d.unref?.()};return{keyDown(u){let m=String(u).toLowerCase();s.has(m)||(s.add(m),w())},keyUp(u){let m=String(u).toLowerCase();s.delete(m)&&w()},setButtons(u){let m=Number.isFinite(u)?Number(u):0;m!==o&&(o=m,w())},movePointer(u,m){let y=Number.isFinite(u)?Number(u):0,_=Number.isFinite(m)?Number(m):0;y===0&&_===0||(i+=y,a+=_,w())},heldKeys(){return[...s]},clear(){l||(s.clear(),o=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(l)return;let u=s.size>0||o!==0;s.clear(),o=0,d&&(clearTimeout(d),d=null),u&&p(),l=!0}}}export{Zt as ACTIVATION_COLD_BOOT_AFTER_MS,er as ACTIVATION_DEGRADED_AFTER_MS,Ce as ACTIVATION_HINT_PATH,Qt as ACTIVATION_STILL_AFTER_MS,Le as ACTIVITY_DOM_EVENTS,At as ACTIVITY_FIELD,Pr as ACTIVITY_STAMP_MIN_INTERVAL_MS,W as ActivationMonitor,rn as App,pt as BACKOFF_BASE_MS,L as BACKOFF_MAX_ATTEMPTS,ft as BACKOFF_MAX_MS,_e as CaptureController,be as CaptureUnavailableError,x as ClientTokenError,xt as DEFAULT_DOC_SYNC_TIMEOUT_MS,Lt as DEFAULT_GATEWAY_URL,Bt as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Jt as DEFAULT_WHEN_LIVE_TIMEOUT_MS,V as DGRAM_HEADER_BYTES,Mr as FOREGROUND_COALESCE_MS,G as FrameReassembler,fn as INPUT_PRESENCE_DEFAULT_HZ,jt as INPUT_PRESENCE_FIELD,F as InvalidDurationError,Pe as LEGACY_ACTIVATION_HINT_PATH,Ie as PLATFORM_DOC_NAME,we as PermanentLockedError,ve as PinRequiresActiveTempError,Kt as ProduceAckTimeoutError,he as RecordingNotFoundError,N as RecordingsClient,T as RecordingsError,B as RecordingsUnauthorizedError,ne as RequestAbortError,Re as RequestCancelledError,Te as RequestDocSyncError,re as RequestError,ke as RequestTimeoutError,ge as RetainNotTempError,me as RuntimeArtifactNotFoundError,M as RuntimeArtifactsClient,k as RuntimeArtifactsError,fe as RuntimeArtifactsUnauthorizedError,Q as Session,R as SessionAllocationError,U as SessionEndError,j as SessionEndUnavailableError,Gt as SessionFailedError,Ae as StreamDirectionConflict,Y as TransportNegotiator,J as TransportSessionSignaling,Rt as VISIBILITY_FIELD,Ct as WT_CONTROL_FRAME_MAX,X as WebRtcSession,z as WebTransportSession,K as WtControlDecoder,lt as activationHintFrom,de as computeBackoffDelay,qe as createActivityTracker,nn as createClientToken,mn as createInputPresencePublisher,Cr as createRecordingsClient,Sr as createRuntimeArtifactsClient,sn as createStore,Vt as describeSessionFailure,Xt as describeSessionPhase,$e as encodeWtControlFrame,Ue as isDurationString,cn as isPendingRecording,ue as isRetryableSessionError,Yt as isWakingPhase,je as mediaRecorderChunkSource,Er as normalizeRetention,Fe as observePageLifecycle,Ne as observePageTeardown,He as parseDgramHeader,hr as prewake,Oe as releaseSessionBeacon,zt as sessionFailureFromMediaError,pn as sharedCaptureController,an as videoStream,Ee as whenLive,Ur as writeDgramHeader};
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { d as AppOptions, c as App$1, J as SessionPhase, Q as SessionStatus, N as SessionPhaseName, A as AccessTokenOptions$1, x as RuntimeArtifact, y as RuntimeArtifactDownload, R as Recording, S as Session$1, C as ChannelEndpoint, Z as TransportSession, e as AttachOptions, E as SessionDiagnostic, a as ActivationEvent, u as RecordingsAccessor, z as RuntimeArtifactsAccessor, H as SessionEndResult, T as SessionStream$1, Y as StreamDataTransport, G as SessionDocumentImpl, X as StreamChunkOptions, i as ChunkReadable, P as Presence, m as DocConnector, v as RequestOptions, w as RequestStreamOptions, W as StoreOptions, V as Store, g as ChannelMultiplexer, I as SessionFailureKind, $ as TransportState } from './stream-data-Bph8tc9M.mjs';
2
- export { b as ActivationState, M as MediaChunkBinding, n as MediaChunkSource, o as MediaChunkSourceFactory, p as MediaRecorderChunkSourceOptions, q as PresenceState, r as RecordingBucket, s as RecordingLifecycle, t as RecordingStatus, B as RuntimeAvailability, F as SessionDocument, K as SessionPhaseError, U as SessionText, a3 as isPendingRecording, a4 as mediaRecorderChunkSource } from './stream-data-Bph8tc9M.mjs';
1
+ import { d as AppOptions, c as App$1, J as SessionPhase, Q as SessionStatus, N as SessionPhaseName, A as AccessTokenOptions$1, x as RuntimeArtifact, y as RuntimeArtifactDownload, R as Recording, S as Session$1, C as ChannelEndpoint, Z as TransportSession, e as AttachOptions, E as SessionDiagnostic, a as ActivationEvent, u as RecordingsAccessor, z as RuntimeArtifactsAccessor, H as SessionEndResult, T as SessionStream$1, Y as StreamDataTransport, G as SessionDocumentImpl, X as StreamChunkOptions, i as ChunkReadable, P as Presence, m as DocConnector, v as RequestOptions, w as RequestStreamOptions, W as StoreOptions, V as Store, g as ChannelMultiplexer, I as SessionFailureKind, $ as TransportState } from './stream-data-8bdjS6Au.mjs';
2
+ export { b as ActivationState, M as MediaChunkBinding, n as MediaChunkSource, o as MediaChunkSourceFactory, p as MediaRecorderChunkSourceOptions, q as PresenceState, r as RecordingBucket, s as RecordingLifecycle, t as RecordingStatus, B as RuntimeAvailability, F as SessionDocument, K as SessionPhaseError, U as SessionText, a3 as isPendingRecording, a4 as mediaRecorderChunkSource } from './stream-data-8bdjS6Au.mjs';
3
3
  import 'yjs';
4
4
  import 'y-protocols/awareness';
5
5
 
@@ -638,6 +638,8 @@ declare function sharedCaptureController(): CaptureController;
638
638
 
639
639
  declare const ACTIVITY_FIELD = "activity";
640
640
 
641
+ declare const VISIBILITY_FIELD = "visibility";
642
+
641
643
  declare const ACTIVITY_STAMP_MIN_INTERVAL_MS = 15000;
642
644
 
643
645
  declare const ACTIVITY_DOM_EVENTS: readonly ["pointerdown", "pointermove", "keydown", "wheel", "touchstart"];
@@ -985,4 +987,4 @@ declare class FrameReassembler {
985
987
  private requestKeyframe;
986
988
  }
987
989
 
988
- export { ACTIVATION_COLD_BOOT_AFTER_MS, ACTIVATION_DEGRADED_AFTER_MS, ACTIVATION_HINT_PATH, ACTIVATION_STILL_AFTER_MS, ACTIVITY_DOM_EVENTS, ACTIVITY_FIELD, ACTIVITY_STAMP_MIN_INTERVAL_MS, ActivationEvent, ActivationMonitor, type ActivationMonitorOptions, type ActivationStreamLike, type ActivityAwareness, type ActivityTracker, type ActivityTrackerOptions, App, App$1 as AppInterface, AppOptions, AttachOptions, BACKOFF_BASE_MS, BACKOFF_MAX_ATTEMPTS, BACKOFF_MAX_MS, type CaptureClaim, CaptureController, type CaptureControllerOptions, type CaptureKind, CaptureUnavailableError, ChunkReadable, type ClientToken, ClientTokenError, type ConsumingTransport, type CreateClientTokenOptions, DEFAULT_DOC_SYNC_TIMEOUT_MS, DEFAULT_GATEWAY_URL, 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, LEGACY_ACTIVATION_HINT_PATH, type MediaSession, type NegotiatorOptions, PLATFORM_DOC_NAME, 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, type ReleaseSessionBeaconOptions, RequestAbortError, RequestCancelledError, RequestDocSyncError, RequestError, RequestOptions, RequestStreamOptions, RequestTimeoutError, RetainNotTempError, type RetentionIntent, RuntimeArtifact, RuntimeArtifactDownload, RuntimeArtifactNotFoundError, RuntimeArtifactsAccessor, RuntimeArtifactsClient, type RuntimeArtifactsClientOptions, RuntimeArtifactsError, RuntimeArtifactsUnauthorizedError, Session, SessionAllocationError, SessionDiagnostic, 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, activationHintFrom, computeBackoffDelay, createActivityTracker, createClientToken, createInputPresencePublisher, createRecordingsClient, createRuntimeArtifactsClient, createStore, describeSessionFailure, describeSessionPhase, encodeWtControlFrame, isDurationString, isRetryableSessionError, isWakingPhase, normalizeRetention, observePageLifecycle, observePageTeardown, parseDgramHeader, prewake, releaseSessionBeacon, sessionFailureFromMediaError, sharedCaptureController, videoStream, whenLive, writeDgramHeader };
990
+ export { ACTIVATION_COLD_BOOT_AFTER_MS, ACTIVATION_DEGRADED_AFTER_MS, ACTIVATION_HINT_PATH, ACTIVATION_STILL_AFTER_MS, ACTIVITY_DOM_EVENTS, ACTIVITY_FIELD, ACTIVITY_STAMP_MIN_INTERVAL_MS, ActivationEvent, ActivationMonitor, type ActivationMonitorOptions, type ActivationStreamLike, type ActivityAwareness, type ActivityTracker, type ActivityTrackerOptions, App, App$1 as AppInterface, AppOptions, AttachOptions, BACKOFF_BASE_MS, BACKOFF_MAX_ATTEMPTS, BACKOFF_MAX_MS, type CaptureClaim, CaptureController, type CaptureControllerOptions, type CaptureKind, CaptureUnavailableError, ChunkReadable, type ClientToken, ClientTokenError, type ConsumingTransport, type CreateClientTokenOptions, DEFAULT_DOC_SYNC_TIMEOUT_MS, DEFAULT_GATEWAY_URL, 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, LEGACY_ACTIVATION_HINT_PATH, type MediaSession, type NegotiatorOptions, PLATFORM_DOC_NAME, 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, type ReleaseSessionBeaconOptions, RequestAbortError, RequestCancelledError, RequestDocSyncError, RequestError, RequestOptions, RequestStreamOptions, RequestTimeoutError, RetainNotTempError, type RetentionIntent, RuntimeArtifact, RuntimeArtifactDownload, RuntimeArtifactNotFoundError, RuntimeArtifactsAccessor, RuntimeArtifactsClient, type RuntimeArtifactsClientOptions, RuntimeArtifactsError, RuntimeArtifactsUnauthorizedError, Session, SessionAllocationError, SessionDiagnostic, 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, VISIBILITY_FIELD, type VideoStreamOptions, WT_CONTROL_FRAME_MAX, WebRtcSession, WebTransportSession, type WhenLiveOptions, WtControlDecoder, type WtControlMessage, activationHintFrom, computeBackoffDelay, createActivityTracker, createClientToken, createInputPresencePublisher, createRecordingsClient, createRuntimeArtifactsClient, createStore, describeSessionFailure, describeSessionPhase, encodeWtControlFrame, isDurationString, isRetryableSessionError, isWakingPhase, normalizeRetention, observePageLifecycle, observePageTeardown, parseDgramHeader, prewake, releaseSessionBeacon, sessionFailureFromMediaError, sharedCaptureController, videoStream, whenLive, writeDgramHeader };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { d as AppOptions, c as App$1, J as SessionPhase, Q as SessionStatus, N as SessionPhaseName, A as AccessTokenOptions$1, x as RuntimeArtifact, y as RuntimeArtifactDownload, R as Recording, S as Session$1, C as ChannelEndpoint, Z as TransportSession, e as AttachOptions, E as SessionDiagnostic, a as ActivationEvent, u as RecordingsAccessor, z as RuntimeArtifactsAccessor, H as SessionEndResult, T as SessionStream$1, Y as StreamDataTransport, G as SessionDocumentImpl, X as StreamChunkOptions, i as ChunkReadable, P as Presence, m as DocConnector, v as RequestOptions, w as RequestStreamOptions, W as StoreOptions, V as Store, g as ChannelMultiplexer, I as SessionFailureKind, $ as TransportState } from './stream-data-Bph8tc9M.js';
2
- export { b as ActivationState, M as MediaChunkBinding, n as MediaChunkSource, o as MediaChunkSourceFactory, p as MediaRecorderChunkSourceOptions, q as PresenceState, r as RecordingBucket, s as RecordingLifecycle, t as RecordingStatus, B as RuntimeAvailability, F as SessionDocument, K as SessionPhaseError, U as SessionText, a3 as isPendingRecording, a4 as mediaRecorderChunkSource } from './stream-data-Bph8tc9M.js';
1
+ import { d as AppOptions, c as App$1, J as SessionPhase, Q as SessionStatus, N as SessionPhaseName, A as AccessTokenOptions$1, x as RuntimeArtifact, y as RuntimeArtifactDownload, R as Recording, S as Session$1, C as ChannelEndpoint, Z as TransportSession, e as AttachOptions, E as SessionDiagnostic, a as ActivationEvent, u as RecordingsAccessor, z as RuntimeArtifactsAccessor, H as SessionEndResult, T as SessionStream$1, Y as StreamDataTransport, G as SessionDocumentImpl, X as StreamChunkOptions, i as ChunkReadable, P as Presence, m as DocConnector, v as RequestOptions, w as RequestStreamOptions, W as StoreOptions, V as Store, g as ChannelMultiplexer, I as SessionFailureKind, $ as TransportState } from './stream-data-8bdjS6Au.js';
2
+ export { b as ActivationState, M as MediaChunkBinding, n as MediaChunkSource, o as MediaChunkSourceFactory, p as MediaRecorderChunkSourceOptions, q as PresenceState, r as RecordingBucket, s as RecordingLifecycle, t as RecordingStatus, B as RuntimeAvailability, F as SessionDocument, K as SessionPhaseError, U as SessionText, a3 as isPendingRecording, a4 as mediaRecorderChunkSource } from './stream-data-8bdjS6Au.js';
3
3
  import 'yjs';
4
4
  import 'y-protocols/awareness';
5
5
 
@@ -638,6 +638,8 @@ declare function sharedCaptureController(): CaptureController;
638
638
 
639
639
  declare const ACTIVITY_FIELD = "activity";
640
640
 
641
+ declare const VISIBILITY_FIELD = "visibility";
642
+
641
643
  declare const ACTIVITY_STAMP_MIN_INTERVAL_MS = 15000;
642
644
 
643
645
  declare const ACTIVITY_DOM_EVENTS: readonly ["pointerdown", "pointermove", "keydown", "wheel", "touchstart"];
@@ -985,4 +987,4 @@ declare class FrameReassembler {
985
987
  private requestKeyframe;
986
988
  }
987
989
 
988
- export { ACTIVATION_COLD_BOOT_AFTER_MS, ACTIVATION_DEGRADED_AFTER_MS, ACTIVATION_HINT_PATH, ACTIVATION_STILL_AFTER_MS, ACTIVITY_DOM_EVENTS, ACTIVITY_FIELD, ACTIVITY_STAMP_MIN_INTERVAL_MS, ActivationEvent, ActivationMonitor, type ActivationMonitorOptions, type ActivationStreamLike, type ActivityAwareness, type ActivityTracker, type ActivityTrackerOptions, App, App$1 as AppInterface, AppOptions, AttachOptions, BACKOFF_BASE_MS, BACKOFF_MAX_ATTEMPTS, BACKOFF_MAX_MS, type CaptureClaim, CaptureController, type CaptureControllerOptions, type CaptureKind, CaptureUnavailableError, ChunkReadable, type ClientToken, ClientTokenError, type ConsumingTransport, type CreateClientTokenOptions, DEFAULT_DOC_SYNC_TIMEOUT_MS, DEFAULT_GATEWAY_URL, 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, LEGACY_ACTIVATION_HINT_PATH, type MediaSession, type NegotiatorOptions, PLATFORM_DOC_NAME, 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, type ReleaseSessionBeaconOptions, RequestAbortError, RequestCancelledError, RequestDocSyncError, RequestError, RequestOptions, RequestStreamOptions, RequestTimeoutError, RetainNotTempError, type RetentionIntent, RuntimeArtifact, RuntimeArtifactDownload, RuntimeArtifactNotFoundError, RuntimeArtifactsAccessor, RuntimeArtifactsClient, type RuntimeArtifactsClientOptions, RuntimeArtifactsError, RuntimeArtifactsUnauthorizedError, Session, SessionAllocationError, SessionDiagnostic, 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, activationHintFrom, computeBackoffDelay, createActivityTracker, createClientToken, createInputPresencePublisher, createRecordingsClient, createRuntimeArtifactsClient, createStore, describeSessionFailure, describeSessionPhase, encodeWtControlFrame, isDurationString, isRetryableSessionError, isWakingPhase, normalizeRetention, observePageLifecycle, observePageTeardown, parseDgramHeader, prewake, releaseSessionBeacon, sessionFailureFromMediaError, sharedCaptureController, videoStream, whenLive, writeDgramHeader };
990
+ export { ACTIVATION_COLD_BOOT_AFTER_MS, ACTIVATION_DEGRADED_AFTER_MS, ACTIVATION_HINT_PATH, ACTIVATION_STILL_AFTER_MS, ACTIVITY_DOM_EVENTS, ACTIVITY_FIELD, ACTIVITY_STAMP_MIN_INTERVAL_MS, ActivationEvent, ActivationMonitor, type ActivationMonitorOptions, type ActivationStreamLike, type ActivityAwareness, type ActivityTracker, type ActivityTrackerOptions, App, App$1 as AppInterface, AppOptions, AttachOptions, BACKOFF_BASE_MS, BACKOFF_MAX_ATTEMPTS, BACKOFF_MAX_MS, type CaptureClaim, CaptureController, type CaptureControllerOptions, type CaptureKind, CaptureUnavailableError, ChunkReadable, type ClientToken, ClientTokenError, type ConsumingTransport, type CreateClientTokenOptions, DEFAULT_DOC_SYNC_TIMEOUT_MS, DEFAULT_GATEWAY_URL, 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, LEGACY_ACTIVATION_HINT_PATH, type MediaSession, type NegotiatorOptions, PLATFORM_DOC_NAME, 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, type ReleaseSessionBeaconOptions, RequestAbortError, RequestCancelledError, RequestDocSyncError, RequestError, RequestOptions, RequestStreamOptions, RequestTimeoutError, RetainNotTempError, type RetentionIntent, RuntimeArtifact, RuntimeArtifactDownload, RuntimeArtifactNotFoundError, RuntimeArtifactsAccessor, RuntimeArtifactsClient, type RuntimeArtifactsClientOptions, RuntimeArtifactsError, RuntimeArtifactsUnauthorizedError, Session, SessionAllocationError, SessionDiagnostic, 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, VISIBILITY_FIELD, type VideoStreamOptions, WT_CONTROL_FRAME_MAX, WebRtcSession, WebTransportSession, type WhenLiveOptions, WtControlDecoder, type WtControlMessage, activationHintFrom, computeBackoffDelay, createActivityTracker, createClientToken, createInputPresencePublisher, createRecordingsClient, createRuntimeArtifactsClient, createStore, describeSessionFailure, describeSessionPhase, encodeWtControlFrame, isDurationString, isRetryableSessionError, isWakingPhase, normalizeRetention, observePageLifecycle, observePageTeardown, parseDgramHeader, prewake, releaseSessionBeacon, sessionFailureFromMediaError, sharedCaptureController, videoStream, whenLive, writeDgramHeader };