@urun-sh/core 0.6.9 → 0.6.10

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,5 +1,5 @@
1
1
  import { createRequire as __urunCreateRequire } from 'node:module'; const require = globalThis.require ?? __urunCreateRequire(import.meta.url);
2
- import{B as re,H as ie,I as dt,J as Ie,K as Ce,L as ct,M as lt,N as ut,O as We,P as pt,Q as ht,S as ft,T as se,U as mt,W as gt,Y as vt,b as te,c as G,ca as oe,d as nt,e as De,ea as ae,f as Ue,fa as wt,g as rt,ga as bt,h as it,ha as yt,i as st,ia as kt,l as Le,m as ot,r as Q,w as at,y as ne}from"./chunk-2DW5QEXW.mjs";var cr=15e3,lr=45e3,ur=12e4,_t="platform",St="activation",Tt="desired.activation";function sn(r){if(typeof r=="string"&&r.length>0)return r;if(r&&typeof r=="object"){let e=r.note;if(typeof e=="string"&&e.length>0)return e}}var on=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],de=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 n of this._watches.values())this._arm(n)}}else(t?.name==="error"||t?.name==="paused")&&this._park()})}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;_park(){this._liveAt=null;for(let e of this._watches.values())if(!e.done){for(let t of e.timers)clearTimeout(t);e.timers=[],e.startedAt=null,e.lastEvent=null}}watch(e,t){if(this._stopped||this._watches.has(e))return;let n={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,n),this._hookFirstMediaSignals(n),!n.done&&this._liveAt!==null&&this._arm(n)}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=n=>{if(!(!n||e.done)){if(n.muted===!0&&typeof n.addEventListener=="function"){let i=()=>this._firstMedia(e);n.addEventListener("unmute",i,{once:!0}),e.cleanups.push(()=>n.removeEventListener?.("unmute",i));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",n=>t(n))),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 on){let n=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);n.unref?.(),e.timers.push(n)}}}_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,n){let i={state:t,elapsedMs:n,stream:e.name},s=sn(this._options.hint());s!==void 0&&(i.hint=s),e.lastEvent=i;for(let a of Array.from(this._handlers))a(i)}};var P=class extends Error{status;code;constructor(e,t,n=t>0?`http_${t}`:"runtime_artifacts_error",i){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=n,i!==void 0&&(this.cause=i),Object.setPrototypeOf(this,new.target.prototype)}},Pe=class extends P{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Me=class extends P{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function z(r){return{baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}function fr(r){return new Y(r)}var Y=class{_options;constructor(e){this._options=e}async list(e){let n=Rt(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new P("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map(At)}async getDownloadUrl(e,t){let n=Rt(await this._request(t,`/${encodeURIComponent(e)}/download`)),i=n.download_url;if(typeof i!="string"||!dn(i))throw new P("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:At(n.artifact),downloadUrl:i}}async _request(e,t){let n=dt(this._options.baseUrl,this._options.fallbackUrls),i=null;for(let s of n)try{return await this._requestFromBase(s,e,t)}catch(a){if(i=a instanceof Error?a:new Error(String(a)),i instanceof P&&cn(i.status))throw i}throw i??new P("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let i=`${ie(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${n}`,s=await this._resolveToken(),a=await fetch(i,{method:"GET",headers:this._headers(s)});if(a.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==s&&(s=o,a=await fetch(i,{method:"GET",headers:this._headers(s)}))}if(!a.ok){let{code:o,message:d}=await this._readError(a,e);throw ln(a.status,o,d)}try{return await a.json()}catch(o){throw new P(`[urun] runtime artifacts: invalid JSON response from ${ie(e)}`,0,"bad_response",o)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let n=ie(t);try{let s=(await e.json()).error;if(s&&typeof s=="object"){let{code:a,message:o}=s;return{code:typeof a=="string"&&a.length>0?a:`http_${e.status}`,message:typeof o=="string"&&o.length>0?`[urun] runtime artifacts request failed at ${n}: ${o}`:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}};function At(r){if(!r||typeof r!="object")throw new P("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=r,t=q(e,"artifact_id")||q(e,"id"),n=q(e,"filename"),i=q(e,"kind"),s=q(e,"status")||"ready",a=an(e,"size_bytes"),o=q(e,"sha256");if(!t||!n||!i||a==null||!o)throw new P("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:i,filename:n,contentType:q(e,"content_type")||"application/octet-stream",sizeBytes:a,sha256:o,status:s,createdAt:q(e,"created_at"),expiresAt:q(e,"expires_at")}}function q(r,e){let t=r[e];return typeof t=="string"&&t.length>0?t:void 0}function an(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function dn(r){try{return new URL(r).protocol==="https:"}catch{return!1}}function cn(r){return r===401||r===403}function ln(r,e,t){return r===401?new Pe(t,e):r===404?new Me(t,e):new P(t,r,e)}function Rt(r){if(!r||typeof r!="object"||Array.isArray(r))throw new P("[urun] runtime artifacts: malformed response",0,"bad_response");return r}var F=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)}},ce=class extends F{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},xe=class extends F{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Oe=class extends F{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)}},Ne=class extends F{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)}},Fe=class extends F{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},X=class extends F{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",n=400){super(e,{status:n,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function Et(r){return/^(\d+[smhdw])+$/.test(r)}function gr(r){if(r==="pin")return{action:"pin"};if(Et(r))return{action:"retain",duration:r};throw new X(`[urun] recordings: "${r}" is not a duration or "pin"`)}function un(r,e,t){let n=t||e||`HTTP ${r}`;if(r===401)return new ce(n,e??"unauthorized");if(r===404)return new xe(n,e??"not_found");if(r===400)return new X(n,e??"bad_request",400);if(r===409)switch(e){case"retain_not_temp":return new Oe(n,e);case"pin_requires_active_temp":return new Ne(n,e);case"permanent_locked":return new Fe(n,e)}return new F(n,{status:r,code:e??`http_${r}`})}var J=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let n=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(n)?n:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!Et(t))throw new X(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new F("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let i=this._buildUrl(t,n.params),s=await this._resolveToken(),a=await this._fetch(i,e,s,n.body);if(a.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==s&&(s=o,a=await this._fetch(i,e,s,n.body))}if(!a.ok){let{code:o,message:d}=await this._readError(a);throw un(a.status,o,d)}return this._readJson(a)}_buildUrl(e,t){let n=`${this._base}${e}`,i=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,a])=>`${encodeURIComponent(s)}=${encodeURIComponent(a)}`).join("&");return i&&(n+=`?${i}`),n}_fetch(e,t,n,i){let s={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider);let a={method:t,headers:s};return i!==void 0&&(s["Content-Type"]="application/json",a.body=JSON.stringify(i)),fetch(e,a)}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 ce("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let n=(await e.json()).error;if(n&&typeof n=="object"){let{code:i,message:s}=n;return{code:typeof i=="string"?i:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function vr(r){return new J(r)}var br=1e3,yr=12e3;function Dt(r,e,t={}){let n=null,i=0,s=0,a=null,o=-1,d=()=>{let h=r.get("desired.billing.generationSeconds");if(typeof h!="number"||!Number.isFinite(h)||h<=0)return null;let b=r.get("desired.billing.epoch"),v=r.get("desired.billing.updatedAtMs");return{seconds:h,epoch:typeof b=="number"&&Number.isFinite(b)?b:0,updatedAtMs:typeof v=="number"&&Number.isFinite(v)?v:null}},l=()=>{if(n===null)return null;let h=Math.min(Math.max(0,Date.now()-i),s);return n+h/1e3},c=()=>{let h=t.creditsPerSecond;if(typeof h=="number"&&Number.isFinite(h)&&h>0)return h;let b=r.get("desired.billing.creditsPerSecond");return typeof b=="number"&&Number.isFinite(b)&&b>0?b:null},u=()=>{let h=l();if(h===null)return;let b=Math.floor(h);if(b<=o)return;o=b;let v={seconds:b},R=c();R!==null&&(v.estimatedCredits=b*R),e(v)},p=h=>{i=Date.now();let b=h===null?0:Math.max(0,i-h);s=Math.max(0,12e3-b)},y=()=>{let h=d();if(h!==null){if(a!==null&&h.epoch!==a){a=h.epoch,n=h.seconds,o=-1,p(h.updatedAtMs),u();return}n!==null&&h.seconds<=n||(a=h.epoch,n=h.seconds,p(h.updatedAtMs),u())}};y();let k=r.on("change",y),S=setInterval(u,1e3);return S.unref?.(),()=>{clearInterval(S),k()}}var pn="activity",hn="visibility",_r=15e3,Ut=["pointerdown","pointermove","keydown","wheel","touchstart"];function Lt(r){let e=r.now??Date.now,t=r.mode==="explicit",n=t?null:r.windowTarget!==void 0?r.windowTarget:typeof window<"u"?window:null,i=t?null:r.documentTarget!==void 0?r.documentTarget:typeof document<"u"?document:null,s=!1,a,o=()=>{if(s)return;let p=e();if(!(a!==void 0&&p-a<15e3)){a=p;try{r.awareness.setLocalStateField(pn,{at:p})}catch{}}},d=()=>{if(!(s||!i||i.visibilityState===void 0))try{r.awareness.setLocalStateField(hn,i.visibilityState)}catch{}},l=()=>o(),c=()=>{d(),(!i||i.visibilityState===void 0||i.visibilityState==="visible")&&o()};if(n)for(let p of Ut)n.addEventListener(p,l,{passive:!0,capture:!0});i&&i.addEventListener("visibilitychange",c);let u=null;return!t&&r.isProducing&&(u=setInterval(()=>{if(!s)try{r.isProducing?.()&&o()}catch{}},15e3),u.unref?.()),o(),d(),{touch:o,dispose(){if(!s){if(s=!0,n)for(let p of Ut)n.removeEventListener(p,l,{capture:!0});i&&i.removeEventListener("visibilitychange",c),u&&(clearInterval(u),u=null)}}}}var fn="user_activity",mn="focus",Tr=3e4;function It(r){switch(r){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var le=class{_awareness;_now;_win;_state="idle";_stateHandlers=new Set;_transportUnsubs=new Set;_disposed=!1;_counts={typing:0,pointer:0,tty:0,consumer_reads:0};_inflight=0;_visibility;_focus;_lastSignalAt;_lastPublishedAt;_trailing=null;_onWindowFocus=null;_onWindowBlur=null;constructor(e={}){this._awareness=e.awareness??null,this._now=e.now??Date.now,this._win=e.windowTarget!==void 0?e.windowTarget:typeof window<"u"?window:null;let t=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null;this._win&&t&&typeof t.hasFocus=="function"&&(this._onWindowFocus=()=>this.setFocus("focused"),this._onWindowBlur=()=>this.setFocus("unfocused"),this._win.addEventListener("focus",this._onWindowFocus),this._win.addEventListener("blur",this._onWindowBlur),this.setFocus(t.hasFocus()?"focused":"unfocused"))}get state(){return this._state}onState(e){return this._stateHandlers.add(e),()=>this._stateHandlers.delete(e)}transportConnecting(){this._setState("connecting")}transportReady(){this._setState("ready")}transportClosed(){this._setState("transient_failure")}attachTransport(e){if(this._disposed)return()=>{};this._setState(It(e.state));let t=e.on("stateChange",i=>{this._setState(It(i))}),n=()=>{t(),this._transportUnsubs.delete(n)};return this._transportUnsubs.add(n),n}_setState(e){if(!(this._disposed||e===this._state)){this._state=e;for(let t of this._stateHandlers)try{t(e)}catch{}}}interaction(e,t=1){this._disposed||!Number.isFinite(t)||t<=0||e==="pointer"&&this._focus==="unfocused"||(this._counts[e]+=t,this._signal())}consumerRead(e=1){this._disposed||!Number.isFinite(e)||e<=0||(this._counts.consumer_reads+=e,this._signal())}get inflight(){return this._inflight}workBegin(){if(this._disposed)return()=>{};this._inflight+=1,this._inflight===1&&this._publishNow();let e=!1;return()=>{e||this._disposed||(e=!0,this._inflight-=1,this._inflight===0&&this._publishNow())}}setVisibility(e){this._disposed||(this._visibility=e)}setFocus(e){if(!(this._disposed||e===this._focus)){this._focus=e;try{this._awareness?.setLocalStateField(mn,e)}catch{}}}_signal(){this._lastSignalAt=this._now();let e=this._lastPublishedAt===void 0?1/0:this._lastSignalAt-this._lastPublishedAt;if(e>=3e4){this._publishNow();return}if(this._trailing)return;let t=Math.max(3e4-e,0);this._trailing=setTimeout(()=>{this._trailing=null,this._disposed||this._publishNow()},t),this._trailing.unref?.()}_publishNow(){this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._lastPublishedAt=this._now();let e={at:this._lastSignalAt??this._lastPublishedAt,counts:{...this._counts},inflight:this._inflight};this._visibility!==void 0&&(e.visibility=this._visibility),this._focus!==void 0&&(e.focus=this._focus);try{this._awareness?.setLocalStateField(fn,e)}catch{}}dispose(){if(!this._disposed){for(let e of Array.from(this._transportUnsubs))e();this._transportUnsubs.clear(),this._win&&(this._onWindowFocus&&this._win.removeEventListener("focus",this._onWindowFocus),this._onWindowBlur&&this._win.removeEventListener("blur",this._onWindowBlur)),this._onWindowFocus=null,this._onWindowBlur=null,this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._state="idle",this._stateHandlers.clear(),this._disposed=!0}}};var Rr=250;function Ct(r){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let n=Date.now();n-e<250||(e=n,r())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function Wt(r){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=n=>{n.persisted||e||(e=!0,r())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function Pt(r){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{r()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var Mt="video/mp4";function xt(r,e={}){let t=e.timesliceMs??1e3,n=null,i=null,s=!1,a=(o,d,l)=>{let c=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!c)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let u=e.mimeType??(typeof c.isTypeSupported=="function"&&c.isTypeSupported(Mt)?Mt:void 0),p=new MediaStream([o]),y=new c(p,u?{mimeType:u}:void 0);n=y;let k=Promise.resolve();y.ondataavailable=S=>{let h=S.data;s||!h||h.size===0||(k=k.then(async()=>{let b=new Uint8Array(await h.arrayBuffer());s||d(b)}))},y.onstop=()=>{k.then(()=>{s||l()})},y.onerror=()=>{k.then(()=>{s||l()})},y.start(t)};return{start(o,d){if(n||s)return;let l=r.track();if(l){a(l,o,d);return}i=r.onTrack(c=>{!c||n||s||(i?.(),i=null,a(c,o,d))})},stop(){if(s)return;s=!0,i?.(),i=null;let o=n;if(n=null,o&&o.state!=="inactive")try{o.stop()}catch{}}}}function gn(r){let e=r;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=r.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function Ot(r,e){let t=null,n=!1,i=!1,s=new ReadableStream({pull(a){n||(n=!0,t=r(e),t.start(o=>{if(!i)try{a.enqueue(o)}catch{}},()=>{if(!i){i=!0;try{a.close()}catch{}}}))},cancel(){i=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return gn(s)}import{encode as vn,decode as wn}from"@msgpack/msgpack";var bn=65536;function Nt(r){let e=vn(r),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var ue=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(n>bn)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+n)break;let i=this.buf.subarray(4,4+n);this.buf=this.buf.subarray(4+n),t.push(Object.assign(wn(i),{raw:i}))}return t}};function Ft(r,e){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),n=t.getUint8(0),i=(n&240)===128,s=n===222;if(!i&&!s&&!(n===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let o=i?n&15:s?t.getUint16(1,!1):t.getUint32(1,!1),d=i?1:s?3:5,l=[];l.push(r.subarray(0,d));for(let y=0;y<o;y++){let k=d,S=Z(r,t,d);d=S.end;let b=Z(r,t,d).end;if(yn(t.getUint8(k))){let v=t.getUint8(k),R=(v&224)===160?1:v===217?2:v===218?3:5;if(new TextDecoder().decode(r.subarray(k+R,S.end))==="t"){l.push(r.subarray(k,S.end));let T=new TextEncoder().encode(e);if(T.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");l.push(new Uint8Array([160|T.byteLength]),T)}else l.push(r.subarray(k,b))}else l.push(r.subarray(k,b));d=b}let c=l.reduce((y,k)=>y+k.byteLength,0),u=new Uint8Array(c),p=0;for(let y of l)u.set(y,p),p+=y.byteLength;return u}function yn(r){return(r&224)===160?!0:r===217||r===218||r===219}function Z(r,e,t){let n=e.getUint8(t),i=t;if(n<=127||n>=224)return{start:i,end:t+1};if((n&224)===160)return{start:i,end:t+1+(n&31)};if((n&240)===128||(n&240)===144){let a=n&15;t+=1;let o=(n&240)===128?a*2:a;for(let d=0;d<o;d++)t=Z(r,e,t).end;return{start:i,end:t}}let s={192:0,194:0,195:0,204:1,205:2,206:4,207:8,208:1,209:2,210:4,211:8,202:4,203:8};if(s[n]!==void 0)return{start:i,end:t+1+s[n]};if(n===217||n===196)return{start:i,end:t+2+e.getUint8(t+1)};if(n===218||n===197)return{start:i,end:t+3+e.getUint16(t+1,!1)};if(n===219||n===198)return{start:i,end:t+5+e.getUint32(t+1,!1)};if(n===220||n===221){let a=n===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===220?3:5;for(let o=0;o<a;o++)t=Z(r,e,t).end;return{start:i,end:t}}if(n===222||n===223){let a=n===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===222?3:5;for(let o=0;o<a*2;o++)t=Z(r,e,t).end;return{start:i,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${n.toString(16)} at byte ${i}`)}var M=12,$e=1,kn=0,pe=1,$t=2;function he(r){let e=r.getUint8(8);return{groupId:r.getUint32(0,!0),frameSeq:r.getUint32(4,!0),keyframe:(e&$e)===$e,fragIndex:r.getUint8(9),fragCount:r.getUint8(10),lane:r.getUint8(11)}}function qt(r){let e=new Uint8Array(M),t=new DataView(e.buffer);return t.setUint32(0,r.groupId,!0),t.setUint32(4,r.frameSeq,!0),t.setUint8(8,r.keyframe?$e:0),t.setUint8(9,r.fragIndex),t.setUint8(10,r.fragCount),t.setUint8(11,r.lane??kn),e}var _n=100,Ht=100,fe=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??_n}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<M)return;let t=he(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.isSourceRestart(t.groupId,t.frameSeq))this.resync(t.groupId);else if(t.groupId<this.newestGroupSeen||(t.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t.groupId,this.needKeyframe=!0),t.frameSeq<=this.newestFrameDelivered))return;let n=this.pending.get(t.frameSeq);if(n||(n={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n)),!n.chunks[t.fragIndex]){n.chunks[t.fragIndex]=e.subarray(M),n.received++,n.received===n.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,n));for(let i of this.pending.keys())i<t.frameSeq-1&&(this.pending.delete(i),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-Ht?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-Ht}resync(e){this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e,this.newestFrameDelivered=-1,this.needKeyframe=!0,this.requestKeyframe()}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let n=t.chunks.reduce((a,o)=>a+o.byteLength,0),i=new Uint8Array(n),s=0;for(let a of t.chunks)i.set(a,s),s+=a.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:i})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Sn=/^avc[13]\.[0-9a-fA-F]{6}$/;function Tn(r){return Sn.test(r)?null:`codec ${JSON.stringify(r)} 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 qe(r,e){let t=Tn(r);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var An=1,He=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}if(this.name===null){if(this.buf.byteLength<2)return[];let n=this.buf[0];if(n!==An)throw new Error(`[urun] wt data stream: unknown header version 0x${n.toString(16)} \u2014 rejecting stream`);let i=this.buf[1];if(i===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+i)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+i)),this.buf=this.buf.subarray(2+i)}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+n)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let i=gt(this.buf.subarray(4,4+n));this.buf=this.buf.subarray(4+n),i===mt&&(this.ended=!0),t.push({name:this.name,payload:i})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return t}finish(){if(this.ended&&this.buf.byteLength===0)return;let e=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN without an END envelope`)}};async function jt(r,e){let t=r.getReader();for(;;){let{value:n,done:i}=await t.read();if(i)return;n&&Rn(n,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function Rn(r,e){let t=r.getReader(),n=new He;try{for(;;){let{value:i,done:s}=await t.read();if(s)break;if(!(!i||i.byteLength===0))for(let{name:a,payload:o}of n.push(i))e.onData(a,o)}n.finish()}catch(i){try{await t.cancel?.(i)}catch{}throw i}}var je=40,En=48e3,Dn=64,Un=100,Be=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<M)return;let t=he(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-Un)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let n=this.pending.get(t.frameSeq);if(!n)for(n={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n);this.pending.size>Dn;){let o=1/0;for(let d of this.pending.keys())d<o&&(o=d);this.pending.delete(o),this.framesAbandoned++}if(t.fragIndex>=n.fragCount||n.chunks[t.fragIndex]||(n.chunks[t.fragIndex]=e.subarray(M),n.received++,n.received<n.fragCount))return;this.pending.delete(t.frameSeq);for(let o of this.pending.keys())o<t.frameSeq&&(this.pending.delete(o),this.framesAbandoned++);let i=n.chunks.reduce((o,d)=>o+(d?.byteLength??0),0),s=new Uint8Array(i),a=0;for(let o of n.chunks)s.set(o,a),a+=o.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:n.timestamp,data:s})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},me=class{constructor(e,t){this.config=e;this.seam=t;let n=this.seam.jitterBufferTargetMs??je;Number.isFinite(n)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${n} is not finite \u2014 using default ${je}ms`),n=je),this.targetS=Math.max(0,n)/1e3}config;seam;decoder=null;ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;assembler=new Be(e=>this.decodeFrame(e));start(){let e=globalThis.AudioDecoder,t=globalThis.AudioContext;if(typeof e!="function"||typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new t({sampleRate:this.config.sampleRate}),this.dest=this.ctx.createMediaStreamDestination();try{this.initDecoder(e)}catch(n){throw this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,n}}stop(){if(!this.stopped){this.stopped=!0,this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ctx?.close().catch(()=>{})}}initDecoder(e){let t=new e({output:n=>this.schedule(n),error:n=>this.onDecoderError(n)});t.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels}),this.decoder=t}decodeFrame(e){let t=globalThis.EncodedAudioChunk;if(typeof t!="function"||this.stopped)return;if(!this.decoder){let i=globalThis.AudioDecoder;if(typeof i!="function")return;try{this.initDecoder(i)}catch{return}}let n=this.decoder;n&&n.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/En)),data:e.data}))}schedule(e){let t=this.ctx,n=this.dest;if(!t||!n||this.stopped){e.close();return}if(!this.trackSurfaced){this.trackSurfaced=!0,t.resume?.().catch(()=>{});let c=n.stream.getAudioTracks()[0];c&&(this.armBridgeEndedWatch(c),this.seam.onTrack(c))}let i=e.numberOfFrames,s=Math.max(1,e.numberOfChannels),a=t.createBuffer(s,i,e.sampleRate);for(let c=0;c<s;c++){let u=new Float32Array(i);e.copyTo(u,{planeIndex:c,format:"f32-planar"}),a.copyToChannel(u,c)}let o=i/e.sampleRate;e.close();let d=t.createBufferSource();d.buffer=a,d.connect(n);let l=Math.max(this.playhead,t.currentTime+this.targetS);d.start(l),this.playhead=l+o}armBridgeEndedWatch(e){e.addEventListener?.("ended",()=>{if(!this.stopped){console.warn("[urun] WT audio bridge track ENDED while the lane is live \u2014 rebuilding the WebAudio playout surface and re-delivering the bridge track");try{this.rebuildSurface()}catch(t){console.error(`[urun] WT audio bridge rebuild failed \u2014 the reply stays silent until the next lane death re-delivers: ${t instanceof Error?t.message:String(t)}`)}}},{once:!0})}rebuildSurface(){let e=globalThis.AudioContext;if(typeof e!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");let t=this.ctx,n=new e({sampleRate:this.config.sampleRate});this.ctx=n,this.dest=n.createMediaStreamDestination(),this.playhead=0,this.trackSurfaced=!0;let i=this.dest.stream.getAudioTracks()[0];if(!i)throw new Error("[urun] rebuilt playout produced no bridge track");this.armBridgeEndedWatch(i),t?.close().catch(()=>{}),this.seam.onTrack(i)}onDecoderError(e){if(this.stopped)return;console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=globalThis.AudioDecoder;if(typeof t=="function")try{this.initDecoder(t)}catch(n){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${n instanceof Error?n.message:String(n)}`)}}};var ee=1200;function Ve(r,e,t,n,i){let s=n-M;if(s<=0)return null;let a=Math.max(1,Math.ceil(t.byteLength/s));if(a>255)return null;let o=[];for(let d=0;d<a;d++){let l=t.subarray(d*s,Math.min((d+1)*s,t.byteLength)),c=qt({groupId:e>>>0,frameSeq:r>>>0,keyframe:i?.keyframe??!0,fragIndex:d,fragCount:a,lane:i?.lane??pe}),u=new Uint8Array(M+l.byteLength);u.set(c,0),u.set(l,M),o.push(u)}return o}var Ln=`
2
+ import{B as re,H as ie,I as dt,J as Ie,K as Ce,L as ct,M as lt,N as ut,O as We,P as pt,Q as ht,S as ft,T as se,U as mt,W as gt,Y as vt,b as te,c as G,ca as oe,d as nt,e as De,ea as ae,f as Ue,fa as wt,g as rt,ga as bt,h as it,ha as yt,i as st,ia as kt,l as Le,m as ot,r as Q,w as at,y as ne}from"./chunk-6NLEURUP.mjs";var cr=15e3,lr=45e3,ur=12e4,_t="platform",St="activation",Tt="desired.activation";function sn(r){if(typeof r=="string"&&r.length>0)return r;if(r&&typeof r=="object"){let e=r.note;if(typeof e=="string"&&e.length>0)return e}}var on=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],de=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 n of this._watches.values())this._arm(n)}}else(t?.name==="error"||t?.name==="paused")&&this._park()})}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;_park(){this._liveAt=null;for(let e of this._watches.values())if(!e.done){for(let t of e.timers)clearTimeout(t);e.timers=[],e.startedAt=null,e.lastEvent=null}}watch(e,t){if(this._stopped||this._watches.has(e))return;let n={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,n),this._hookFirstMediaSignals(n),!n.done&&this._liveAt!==null&&this._arm(n)}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=n=>{if(!(!n||e.done)){if(n.muted===!0&&typeof n.addEventListener=="function"){let i=()=>this._firstMedia(e);n.addEventListener("unmute",i,{once:!0}),e.cleanups.push(()=>n.removeEventListener?.("unmute",i));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",n=>t(n))),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 on){let n=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);n.unref?.(),e.timers.push(n)}}}_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,n){let i={state:t,elapsedMs:n,stream:e.name},s=sn(this._options.hint());s!==void 0&&(i.hint=s),e.lastEvent=i;for(let a of Array.from(this._handlers))a(i)}};var P=class extends Error{status;code;constructor(e,t,n=t>0?`http_${t}`:"runtime_artifacts_error",i){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=n,i!==void 0&&(this.cause=i),Object.setPrototypeOf(this,new.target.prototype)}},Pe=class extends P{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Me=class extends P{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function z(r){return{baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}function fr(r){return new Y(r)}var Y=class{_options;constructor(e){this._options=e}async list(e){let n=Rt(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new P("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map(At)}async getDownloadUrl(e,t){let n=Rt(await this._request(t,`/${encodeURIComponent(e)}/download`)),i=n.download_url;if(typeof i!="string"||!dn(i))throw new P("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:At(n.artifact),downloadUrl:i}}async _request(e,t){let n=dt(this._options.baseUrl,this._options.fallbackUrls),i=null;for(let s of n)try{return await this._requestFromBase(s,e,t)}catch(a){if(i=a instanceof Error?a:new Error(String(a)),i instanceof P&&cn(i.status))throw i}throw i??new P("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let i=`${ie(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${n}`,s=await this._resolveToken(),a=await fetch(i,{method:"GET",headers:this._headers(s)});if(a.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==s&&(s=o,a=await fetch(i,{method:"GET",headers:this._headers(s)}))}if(!a.ok){let{code:o,message:d}=await this._readError(a,e);throw ln(a.status,o,d)}try{return await a.json()}catch(o){throw new P(`[urun] runtime artifacts: invalid JSON response from ${ie(e)}`,0,"bad_response",o)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let n=ie(t);try{let s=(await e.json()).error;if(s&&typeof s=="object"){let{code:a,message:o}=s;return{code:typeof a=="string"&&a.length>0?a:`http_${e.status}`,message:typeof o=="string"&&o.length>0?`[urun] runtime artifacts request failed at ${n}: ${o}`:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}};function At(r){if(!r||typeof r!="object")throw new P("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=r,t=q(e,"artifact_id")||q(e,"id"),n=q(e,"filename"),i=q(e,"kind"),s=q(e,"status")||"ready",a=an(e,"size_bytes"),o=q(e,"sha256");if(!t||!n||!i||a==null||!o)throw new P("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:i,filename:n,contentType:q(e,"content_type")||"application/octet-stream",sizeBytes:a,sha256:o,status:s,createdAt:q(e,"created_at"),expiresAt:q(e,"expires_at")}}function q(r,e){let t=r[e];return typeof t=="string"&&t.length>0?t:void 0}function an(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function dn(r){try{return new URL(r).protocol==="https:"}catch{return!1}}function cn(r){return r===401||r===403}function ln(r,e,t){return r===401?new Pe(t,e):r===404?new Me(t,e):new P(t,r,e)}function Rt(r){if(!r||typeof r!="object"||Array.isArray(r))throw new P("[urun] runtime artifacts: malformed response",0,"bad_response");return r}var F=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)}},ce=class extends F{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},xe=class extends F{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Oe=class extends F{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)}},Ne=class extends F{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)}},Fe=class extends F{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},X=class extends F{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",n=400){super(e,{status:n,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function Et(r){return/^(\d+[smhdw])+$/.test(r)}function gr(r){if(r==="pin")return{action:"pin"};if(Et(r))return{action:"retain",duration:r};throw new X(`[urun] recordings: "${r}" is not a duration or "pin"`)}function un(r,e,t){let n=t||e||`HTTP ${r}`;if(r===401)return new ce(n,e??"unauthorized");if(r===404)return new xe(n,e??"not_found");if(r===400)return new X(n,e??"bad_request",400);if(r===409)switch(e){case"retain_not_temp":return new Oe(n,e);case"pin_requires_active_temp":return new Ne(n,e);case"permanent_locked":return new Fe(n,e)}return new F(n,{status:r,code:e??`http_${r}`})}var J=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let n=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(n)?n:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!Et(t))throw new X(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new F("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let i=this._buildUrl(t,n.params),s=await this._resolveToken(),a=await this._fetch(i,e,s,n.body);if(a.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==s&&(s=o,a=await this._fetch(i,e,s,n.body))}if(!a.ok){let{code:o,message:d}=await this._readError(a);throw un(a.status,o,d)}return this._readJson(a)}_buildUrl(e,t){let n=`${this._base}${e}`,i=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,a])=>`${encodeURIComponent(s)}=${encodeURIComponent(a)}`).join("&");return i&&(n+=`?${i}`),n}_fetch(e,t,n,i){let s={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider);let a={method:t,headers:s};return i!==void 0&&(s["Content-Type"]="application/json",a.body=JSON.stringify(i)),fetch(e,a)}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 ce("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let n=(await e.json()).error;if(n&&typeof n=="object"){let{code:i,message:s}=n;return{code:typeof i=="string"?i:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function vr(r){return new J(r)}var br=1e3,yr=12e3;function Dt(r,e,t={}){let n=null,i=0,s=0,a=null,o=-1,d=()=>{let h=r.get("desired.billing.generationSeconds");if(typeof h!="number"||!Number.isFinite(h)||h<=0)return null;let b=r.get("desired.billing.epoch"),v=r.get("desired.billing.updatedAtMs");return{seconds:h,epoch:typeof b=="number"&&Number.isFinite(b)?b:0,updatedAtMs:typeof v=="number"&&Number.isFinite(v)?v:null}},l=()=>{if(n===null)return null;let h=Math.min(Math.max(0,Date.now()-i),s);return n+h/1e3},c=()=>{let h=t.creditsPerSecond;if(typeof h=="number"&&Number.isFinite(h)&&h>0)return h;let b=r.get("desired.billing.creditsPerSecond");return typeof b=="number"&&Number.isFinite(b)&&b>0?b:null},u=()=>{let h=l();if(h===null)return;let b=Math.floor(h);if(b<=o)return;o=b;let v={seconds:b},R=c();R!==null&&(v.estimatedCredits=b*R),e(v)},p=h=>{i=Date.now();let b=h===null?0:Math.max(0,i-h);s=Math.max(0,12e3-b)},y=()=>{let h=d();if(h!==null){if(a!==null&&h.epoch!==a){a=h.epoch,n=h.seconds,o=-1,p(h.updatedAtMs),u();return}n!==null&&h.seconds<=n||(a=h.epoch,n=h.seconds,p(h.updatedAtMs),u())}};y();let k=r.on("change",y),S=setInterval(u,1e3);return S.unref?.(),()=>{clearInterval(S),k()}}var pn="activity",hn="visibility",_r=15e3,Ut=["pointerdown","pointermove","keydown","wheel","touchstart"];function Lt(r){let e=r.now??Date.now,t=r.mode==="explicit",n=t?null:r.windowTarget!==void 0?r.windowTarget:typeof window<"u"?window:null,i=t?null:r.documentTarget!==void 0?r.documentTarget:typeof document<"u"?document:null,s=!1,a,o=()=>{if(s)return;let p=e();if(!(a!==void 0&&p-a<15e3)){a=p;try{r.awareness.setLocalStateField(pn,{at:p})}catch{}}},d=()=>{if(!(s||!i||i.visibilityState===void 0))try{r.awareness.setLocalStateField(hn,i.visibilityState)}catch{}},l=()=>o(),c=()=>{d(),(!i||i.visibilityState===void 0||i.visibilityState==="visible")&&o()};if(n)for(let p of Ut)n.addEventListener(p,l,{passive:!0,capture:!0});i&&i.addEventListener("visibilitychange",c);let u=null;return!t&&r.isProducing&&(u=setInterval(()=>{if(!s)try{r.isProducing?.()&&o()}catch{}},15e3),u.unref?.()),o(),d(),{touch:o,dispose(){if(!s){if(s=!0,n)for(let p of Ut)n.removeEventListener(p,l,{capture:!0});i&&i.removeEventListener("visibilitychange",c),u&&(clearInterval(u),u=null)}}}}var fn="user_activity",mn="focus",Tr=3e4;function It(r){switch(r){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var le=class{_awareness;_now;_win;_state="idle";_stateHandlers=new Set;_transportUnsubs=new Set;_disposed=!1;_counts={typing:0,pointer:0,tty:0,consumer_reads:0};_inflight=0;_visibility;_focus;_lastSignalAt;_lastPublishedAt;_trailing=null;_onWindowFocus=null;_onWindowBlur=null;constructor(e={}){this._awareness=e.awareness??null,this._now=e.now??Date.now,this._win=e.windowTarget!==void 0?e.windowTarget:typeof window<"u"?window:null;let t=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null;this._win&&t&&typeof t.hasFocus=="function"&&(this._onWindowFocus=()=>this.setFocus("focused"),this._onWindowBlur=()=>this.setFocus("unfocused"),this._win.addEventListener("focus",this._onWindowFocus),this._win.addEventListener("blur",this._onWindowBlur),this.setFocus(t.hasFocus()?"focused":"unfocused"))}get state(){return this._state}onState(e){return this._stateHandlers.add(e),()=>this._stateHandlers.delete(e)}transportConnecting(){this._setState("connecting")}transportReady(){this._setState("ready")}transportClosed(){this._setState("transient_failure")}attachTransport(e){if(this._disposed)return()=>{};this._setState(It(e.state));let t=e.on("stateChange",i=>{this._setState(It(i))}),n=()=>{t(),this._transportUnsubs.delete(n)};return this._transportUnsubs.add(n),n}_setState(e){if(!(this._disposed||e===this._state)){this._state=e;for(let t of this._stateHandlers)try{t(e)}catch{}}}interaction(e,t=1){this._disposed||!Number.isFinite(t)||t<=0||e==="pointer"&&this._focus==="unfocused"||(this._counts[e]+=t,this._signal())}consumerRead(e=1){this._disposed||!Number.isFinite(e)||e<=0||(this._counts.consumer_reads+=e,this._signal())}get inflight(){return this._inflight}workBegin(){if(this._disposed)return()=>{};this._inflight+=1,this._inflight===1&&this._publishNow();let e=!1;return()=>{e||this._disposed||(e=!0,this._inflight-=1,this._inflight===0&&this._publishNow())}}setVisibility(e){this._disposed||(this._visibility=e)}setFocus(e){if(!(this._disposed||e===this._focus)){this._focus=e;try{this._awareness?.setLocalStateField(mn,e)}catch{}}}_signal(){this._lastSignalAt=this._now();let e=this._lastPublishedAt===void 0?1/0:this._lastSignalAt-this._lastPublishedAt;if(e>=3e4){this._publishNow();return}if(this._trailing)return;let t=Math.max(3e4-e,0);this._trailing=setTimeout(()=>{this._trailing=null,this._disposed||this._publishNow()},t),this._trailing.unref?.()}_publishNow(){this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._lastPublishedAt=this._now();let e={at:this._lastSignalAt??this._lastPublishedAt,counts:{...this._counts},inflight:this._inflight};this._visibility!==void 0&&(e.visibility=this._visibility),this._focus!==void 0&&(e.focus=this._focus);try{this._awareness?.setLocalStateField(fn,e)}catch{}}dispose(){if(!this._disposed){for(let e of Array.from(this._transportUnsubs))e();this._transportUnsubs.clear(),this._win&&(this._onWindowFocus&&this._win.removeEventListener("focus",this._onWindowFocus),this._onWindowBlur&&this._win.removeEventListener("blur",this._onWindowBlur)),this._onWindowFocus=null,this._onWindowBlur=null,this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._state="idle",this._stateHandlers.clear(),this._disposed=!0}}};var Rr=250;function Ct(r){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let n=Date.now();n-e<250||(e=n,r())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function Wt(r){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=n=>{n.persisted||e||(e=!0,r())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function Pt(r){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{r()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var Mt="video/mp4";function xt(r,e={}){let t=e.timesliceMs??1e3,n=null,i=null,s=!1,a=(o,d,l)=>{let c=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!c)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let u=e.mimeType??(typeof c.isTypeSupported=="function"&&c.isTypeSupported(Mt)?Mt:void 0),p=new MediaStream([o]),y=new c(p,u?{mimeType:u}:void 0);n=y;let k=Promise.resolve();y.ondataavailable=S=>{let h=S.data;s||!h||h.size===0||(k=k.then(async()=>{let b=new Uint8Array(await h.arrayBuffer());s||d(b)}))},y.onstop=()=>{k.then(()=>{s||l()})},y.onerror=()=>{k.then(()=>{s||l()})},y.start(t)};return{start(o,d){if(n||s)return;let l=r.track();if(l){a(l,o,d);return}i=r.onTrack(c=>{!c||n||s||(i?.(),i=null,a(c,o,d))})},stop(){if(s)return;s=!0,i?.(),i=null;let o=n;if(n=null,o&&o.state!=="inactive")try{o.stop()}catch{}}}}function gn(r){let e=r;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=r.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function Ot(r,e){let t=null,n=!1,i=!1,s=new ReadableStream({pull(a){n||(n=!0,t=r(e),t.start(o=>{if(!i)try{a.enqueue(o)}catch{}},()=>{if(!i){i=!0;try{a.close()}catch{}}}))},cancel(){i=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return gn(s)}import{encode as vn,decode as wn}from"@msgpack/msgpack";var bn=65536;function Nt(r){let e=vn(r),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var ue=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(n>bn)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+n)break;let i=this.buf.subarray(4,4+n);this.buf=this.buf.subarray(4+n),t.push(Object.assign(wn(i),{raw:i}))}return t}};function Ft(r,e){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),n=t.getUint8(0),i=(n&240)===128,s=n===222;if(!i&&!s&&!(n===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let o=i?n&15:s?t.getUint16(1,!1):t.getUint32(1,!1),d=i?1:s?3:5,l=[];l.push(r.subarray(0,d));for(let y=0;y<o;y++){let k=d,S=Z(r,t,d);d=S.end;let b=Z(r,t,d).end;if(yn(t.getUint8(k))){let v=t.getUint8(k),R=(v&224)===160?1:v===217?2:v===218?3:5;if(new TextDecoder().decode(r.subarray(k+R,S.end))==="t"){l.push(r.subarray(k,S.end));let T=new TextEncoder().encode(e);if(T.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");l.push(new Uint8Array([160|T.byteLength]),T)}else l.push(r.subarray(k,b))}else l.push(r.subarray(k,b));d=b}let c=l.reduce((y,k)=>y+k.byteLength,0),u=new Uint8Array(c),p=0;for(let y of l)u.set(y,p),p+=y.byteLength;return u}function yn(r){return(r&224)===160?!0:r===217||r===218||r===219}function Z(r,e,t){let n=e.getUint8(t),i=t;if(n<=127||n>=224)return{start:i,end:t+1};if((n&224)===160)return{start:i,end:t+1+(n&31)};if((n&240)===128||(n&240)===144){let a=n&15;t+=1;let o=(n&240)===128?a*2:a;for(let d=0;d<o;d++)t=Z(r,e,t).end;return{start:i,end:t}}let s={192:0,194:0,195:0,204:1,205:2,206:4,207:8,208:1,209:2,210:4,211:8,202:4,203:8};if(s[n]!==void 0)return{start:i,end:t+1+s[n]};if(n===217||n===196)return{start:i,end:t+2+e.getUint8(t+1)};if(n===218||n===197)return{start:i,end:t+3+e.getUint16(t+1,!1)};if(n===219||n===198)return{start:i,end:t+5+e.getUint32(t+1,!1)};if(n===220||n===221){let a=n===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===220?3:5;for(let o=0;o<a;o++)t=Z(r,e,t).end;return{start:i,end:t}}if(n===222||n===223){let a=n===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===222?3:5;for(let o=0;o<a*2;o++)t=Z(r,e,t).end;return{start:i,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${n.toString(16)} at byte ${i}`)}var M=12,$e=1,kn=0,pe=1,$t=2;function he(r){let e=r.getUint8(8);return{groupId:r.getUint32(0,!0),frameSeq:r.getUint32(4,!0),keyframe:(e&$e)===$e,fragIndex:r.getUint8(9),fragCount:r.getUint8(10),lane:r.getUint8(11)}}function qt(r){let e=new Uint8Array(M),t=new DataView(e.buffer);return t.setUint32(0,r.groupId,!0),t.setUint32(4,r.frameSeq,!0),t.setUint8(8,r.keyframe?$e:0),t.setUint8(9,r.fragIndex),t.setUint8(10,r.fragCount),t.setUint8(11,r.lane??kn),e}var _n=100,Ht=100,fe=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??_n}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<M)return;let t=he(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.isSourceRestart(t.groupId,t.frameSeq))this.resync(t.groupId);else if(t.groupId<this.newestGroupSeen||(t.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t.groupId,this.needKeyframe=!0),t.frameSeq<=this.newestFrameDelivered))return;let n=this.pending.get(t.frameSeq);if(n||(n={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n)),!n.chunks[t.fragIndex]){n.chunks[t.fragIndex]=e.subarray(M),n.received++,n.received===n.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,n));for(let i of this.pending.keys())i<t.frameSeq-1&&(this.pending.delete(i),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-Ht?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-Ht}resync(e){this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e,this.newestFrameDelivered=-1,this.needKeyframe=!0,this.requestKeyframe()}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let n=t.chunks.reduce((a,o)=>a+o.byteLength,0),i=new Uint8Array(n),s=0;for(let a of t.chunks)i.set(a,s),s+=a.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:i})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Sn=/^avc[13]\.[0-9a-fA-F]{6}$/;function Tn(r){return Sn.test(r)?null:`codec ${JSON.stringify(r)} 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 qe(r,e){let t=Tn(r);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var An=1,He=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}if(this.name===null){if(this.buf.byteLength<2)return[];let n=this.buf[0];if(n!==An)throw new Error(`[urun] wt data stream: unknown header version 0x${n.toString(16)} \u2014 rejecting stream`);let i=this.buf[1];if(i===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+i)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+i)),this.buf=this.buf.subarray(2+i)}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+n)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let i=gt(this.buf.subarray(4,4+n));this.buf=this.buf.subarray(4+n),i===mt&&(this.ended=!0),t.push({name:this.name,payload:i})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return t}finish(){if(this.ended&&this.buf.byteLength===0)return;let e=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN without an END envelope`)}};async function jt(r,e){let t=r.getReader();for(;;){let{value:n,done:i}=await t.read();if(i)return;n&&Rn(n,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function Rn(r,e){let t=r.getReader(),n=new He;try{for(;;){let{value:i,done:s}=await t.read();if(s)break;if(!(!i||i.byteLength===0))for(let{name:a,payload:o}of n.push(i))e.onData(a,o)}n.finish()}catch(i){try{await t.cancel?.(i)}catch{}throw i}}var je=40,En=48e3,Dn=64,Un=100,Be=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<M)return;let t=he(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-Un)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let n=this.pending.get(t.frameSeq);if(!n)for(n={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n);this.pending.size>Dn;){let o=1/0;for(let d of this.pending.keys())d<o&&(o=d);this.pending.delete(o),this.framesAbandoned++}if(t.fragIndex>=n.fragCount||n.chunks[t.fragIndex]||(n.chunks[t.fragIndex]=e.subarray(M),n.received++,n.received<n.fragCount))return;this.pending.delete(t.frameSeq);for(let o of this.pending.keys())o<t.frameSeq&&(this.pending.delete(o),this.framesAbandoned++);let i=n.chunks.reduce((o,d)=>o+(d?.byteLength??0),0),s=new Uint8Array(i),a=0;for(let o of n.chunks)s.set(o,a),a+=o.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:n.timestamp,data:s})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},me=class{constructor(e,t){this.config=e;this.seam=t;let n=this.seam.jitterBufferTargetMs??je;Number.isFinite(n)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${n} is not finite \u2014 using default ${je}ms`),n=je),this.targetS=Math.max(0,n)/1e3}config;seam;decoder=null;ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;assembler=new Be(e=>this.decodeFrame(e));start(){let e=globalThis.AudioDecoder,t=globalThis.AudioContext;if(typeof e!="function"||typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new t({sampleRate:this.config.sampleRate}),this.dest=this.ctx.createMediaStreamDestination();try{this.initDecoder(e)}catch(n){throw this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,n}}stop(){if(!this.stopped){this.stopped=!0,this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ctx?.close().catch(()=>{})}}initDecoder(e){let t=new e({output:n=>this.schedule(n),error:n=>this.onDecoderError(n)});t.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels}),this.decoder=t}decodeFrame(e){let t=globalThis.EncodedAudioChunk;if(typeof t!="function"||this.stopped)return;if(!this.decoder){let i=globalThis.AudioDecoder;if(typeof i!="function")return;try{this.initDecoder(i)}catch{return}}let n=this.decoder;n&&n.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/En)),data:e.data}))}schedule(e){let t=this.ctx,n=this.dest;if(!t||!n||this.stopped){e.close();return}if(!this.trackSurfaced){this.trackSurfaced=!0,t.resume?.().catch(()=>{});let c=n.stream.getAudioTracks()[0];c&&(this.armBridgeEndedWatch(c),this.seam.onTrack(c))}let i=e.numberOfFrames,s=Math.max(1,e.numberOfChannels),a=t.createBuffer(s,i,e.sampleRate);for(let c=0;c<s;c++){let u=new Float32Array(i);e.copyTo(u,{planeIndex:c,format:"f32-planar"}),a.copyToChannel(u,c)}let o=i/e.sampleRate;e.close();let d=t.createBufferSource();d.buffer=a,d.connect(n);let l=Math.max(this.playhead,t.currentTime+this.targetS);d.start(l),this.playhead=l+o}armBridgeEndedWatch(e){e.addEventListener?.("ended",()=>{if(!this.stopped){console.warn("[urun] WT audio bridge track ENDED while the lane is live \u2014 rebuilding the WebAudio playout surface and re-delivering the bridge track");try{this.rebuildSurface()}catch(t){console.error(`[urun] WT audio bridge rebuild failed \u2014 the reply stays silent until the next lane death re-delivers: ${t instanceof Error?t.message:String(t)}`)}}},{once:!0})}rebuildSurface(){let e=globalThis.AudioContext;if(typeof e!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");let t=this.ctx,n=new e({sampleRate:this.config.sampleRate});this.ctx=n,this.dest=n.createMediaStreamDestination(),this.playhead=0,this.trackSurfaced=!0;let i=this.dest.stream.getAudioTracks()[0];if(!i)throw new Error("[urun] rebuilt playout produced no bridge track");this.armBridgeEndedWatch(i),t?.close().catch(()=>{}),this.seam.onTrack(i)}onDecoderError(e){if(this.stopped)return;console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=globalThis.AudioDecoder;if(typeof t=="function")try{this.initDecoder(t)}catch(n){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${n instanceof Error?n.message:String(n)}`)}}};var ee=1200;function Ve(r,e,t,n,i){let s=n-M;if(s<=0)return null;let a=Math.max(1,Math.ceil(t.byteLength/s));if(a>255)return null;let o=[];for(let d=0;d<a;d++){let l=t.subarray(d*s,Math.min((d+1)*s,t.byteLength)),c=qt({groupId:e>>>0,frameSeq:r>>>0,keyframe:i?.keyframe??!0,fragIndex:d,fragCount:a,lane:i?.lane??pe}),u=new Uint8Array(M+l.byteLength);u.set(c,0),u.set(l,M),o.push(u)}return o}var Ln=`
3
3
  self.onrtctransform = (event) => {
4
4
  const transformer = event.transformer
5
5
  if (transformer.options?.role === 'sender') {
@@ -1,5 +1,5 @@
1
- import { ad as SessionDirectoryRequestOptions, h as AppOptions, g as App$1, ai as SessionPhase, ao as SessionStatus, ak as SessionPhaseName, A as AccessTokenOptions, a2 as RuntimeArtifact, a3 as RuntimeArtifactDownload, W as Recording, aF as TransportState, ab as Session$1, C as ChannelEndpoint, aC as TransportSession, d as ActivitySignalMode, i as AttachOptions, ac as SessionDiagnostic, b as ActivationEvent, an as SessionStatsSample, B as GenerationTick, _ as RecordingsAccessor, a4 as RuntimeArtifactsAccessor, ag as SessionEndResult, ap as SessionStream$1, ax as StreamDataTransport, af as SessionDocumentImpl, aw as StreamChunkOptions, n as ChunkReadable, Q as Presence, w as DocConnector, y as DocTokenSupplier, x as DocServerUrlResolver, a0 as RequestOptions, a1 as RequestStreamOptions, av as StoreOptions, au as Store, l as ChannelMultiplexer, ah as SessionFailureKind, J as MediaSession, P as PathHealthReporting, aB as TransportOfferResponse, aK as WtAudioLaneSeam, aL as WtAudioUplinkSeam, aS as WtVideoUplinkSeam, aR as WtDataUplinkSender, O as PathLiveness, aP as WtDataLaneSink } from './stream-data-C1du_YcA.mjs';
2
- export { c as ActivationState, j as AudioPlayoutOptions, D as DERIVED_LEG_SEP, o as DGRAM_HEADER_BYTES, s as DerivedLegRole, t as DgramHeader, v as DocConnectionState, G as GENERATION_TICK_EMIT_INTERVAL_MS, z as GENERATION_TICK_MAX_EXTRAPOLATION_MS, I as InboundStatsSample, M as MediaChunkBinding, E as MediaChunkSource, F as MediaChunkSourceFactory, H as MediaRecorderChunkSourceOptions, N as NegotiatorDataLaneSeam, K as NegotiatorOptions, R as PresenceState, S as PrewakeOptions, T as PrewakeResult, U as PrewakeStatus, V as QuicStreamDataTransport, X as RecordingBucket, Y as RecordingLifecycle, Z as RecordingStatus, $ as ReleaseSessionBeaconOptions, a5 as RuntimeAvailability, a6 as RuntimeWakeDetail, a7 as RuntimeWakeGolden, a8 as RuntimeWakeReasonCode, a9 as SIGNALING_PROTOCOL_VERSION, aa as STREAM_END, ae as SessionDocument, aj as SessionPhaseError, am as SessionStatsOptions, aq as SessionText, ar as SignalCarrier, as as Signaling, at as StartSessionOptions, ay as TransportEstablishedNotify, az as TransportNegotiator, aA as TransportOfferRequest, aE as TransportSessionSignaling, aG as VideoPlayoutOptions, aH as WT_CONTROL_FRAME_MAX, aI as WT_DATA_STREAM_VERSION, aJ as WatchGenerationTickOptions, aM as WtControlDecoder, aN as WtControlMessage, aO as WtDataEnvelope, aQ as WtDataStreamParser, aU as consumeWtDataStreams, aX as decodeStreamEnvelope, aZ as derivedLegName, a_ as derivedLegRole, a$ as encodeStreamEnvelope, b0 as encodeWtControlFrame, b1 as isPendingRecording, b2 as mediaRecorderChunkSource, b3 as parseDgramHeader, b4 as prewake, b5 as releaseSessionBeacon, b8 as watchGenerationTick, b9 as writeDgramHeader } from './stream-data-C1du_YcA.mjs';
1
+ import { ad as SessionDirectoryRequestOptions, h as AppOptions, g as App$1, ai as SessionPhase, ao as SessionStatus, ak as SessionPhaseName, A as AccessTokenOptions, a2 as RuntimeArtifact, a3 as RuntimeArtifactDownload, W as Recording, aF as TransportState, ab as Session$1, C as ChannelEndpoint, aC as TransportSession, d as ActivitySignalMode, i as AttachOptions, ac as SessionDiagnostic, b as ActivationEvent, an as SessionStatsSample, B as GenerationTick, _ as RecordingsAccessor, a4 as RuntimeArtifactsAccessor, ag as SessionEndResult, ap as SessionStream$1, ax as StreamDataTransport, af as SessionDocumentImpl, aw as StreamChunkOptions, n as ChunkReadable, Q as Presence, w as DocConnector, y as DocTokenSupplier, x as DocServerUrlResolver, a0 as RequestOptions, a1 as RequestStreamOptions, av as StoreOptions, au as Store, l as ChannelMultiplexer, ah as SessionFailureKind, J as MediaSession, P as PathHealthReporting, aB as TransportOfferResponse, aK as WtAudioLaneSeam, aL as WtAudioUplinkSeam, aS as WtVideoUplinkSeam, aR as WtDataUplinkSender, O as PathLiveness, aP as WtDataLaneSink } from './stream-data-ByijrPsc.mjs';
2
+ export { c as ActivationState, j as AudioPlayoutOptions, D as DERIVED_LEG_SEP, o as DGRAM_HEADER_BYTES, s as DerivedLegRole, t as DgramHeader, v as DocConnectionState, G as GENERATION_TICK_EMIT_INTERVAL_MS, z as GENERATION_TICK_MAX_EXTRAPOLATION_MS, I as InboundStatsSample, M as MediaChunkBinding, E as MediaChunkSource, F as MediaChunkSourceFactory, H as MediaRecorderChunkSourceOptions, N as NegotiatorDataLaneSeam, K as NegotiatorOptions, R as PresenceState, S as PrewakeOptions, T as PrewakeResult, U as PrewakeStatus, V as QuicStreamDataTransport, X as RecordingBucket, Y as RecordingLifecycle, Z as RecordingStatus, $ as ReleaseSessionBeaconOptions, a5 as RuntimeAvailability, a6 as RuntimeWakeDetail, a7 as RuntimeWakeGolden, a8 as RuntimeWakeReasonCode, a9 as SIGNALING_PROTOCOL_VERSION, aa as STREAM_END, ae as SessionDocument, aj as SessionPhaseError, am as SessionStatsOptions, aq as SessionText, ar as SignalCarrier, as as Signaling, at as StartSessionOptions, ay as TransportEstablishedNotify, az as TransportNegotiator, aA as TransportOfferRequest, aE as TransportSessionSignaling, aG as VideoPlayoutOptions, aH as WT_CONTROL_FRAME_MAX, aI as WT_DATA_STREAM_VERSION, aJ as WatchGenerationTickOptions, aM as WtControlDecoder, aN as WtControlMessage, aO as WtDataEnvelope, aQ as WtDataStreamParser, aU as consumeWtDataStreams, aX as decodeStreamEnvelope, aZ as derivedLegName, a_ as derivedLegRole, a$ as encodeStreamEnvelope, b0 as encodeWtControlFrame, b1 as isPendingRecording, b2 as mediaRecorderChunkSource, b3 as parseDgramHeader, b4 as prewake, b5 as releaseSessionBeacon, b8 as watchGenerationTick, b9 as writeDgramHeader } from './stream-data-ByijrPsc.mjs';
3
3
  import 'yjs';
4
4
  import 'y-protocols/awareness';
5
5
 
@@ -1,5 +1,5 @@
1
- import { ad as SessionDirectoryRequestOptions, h as AppOptions, g as App$1, ai as SessionPhase, ao as SessionStatus, ak as SessionPhaseName, A as AccessTokenOptions, a2 as RuntimeArtifact, a3 as RuntimeArtifactDownload, W as Recording, aF as TransportState, ab as Session$1, C as ChannelEndpoint, aC as TransportSession, d as ActivitySignalMode, i as AttachOptions, ac as SessionDiagnostic, b as ActivationEvent, an as SessionStatsSample, B as GenerationTick, _ as RecordingsAccessor, a4 as RuntimeArtifactsAccessor, ag as SessionEndResult, ap as SessionStream$1, ax as StreamDataTransport, af as SessionDocumentImpl, aw as StreamChunkOptions, n as ChunkReadable, Q as Presence, w as DocConnector, y as DocTokenSupplier, x as DocServerUrlResolver, a0 as RequestOptions, a1 as RequestStreamOptions, av as StoreOptions, au as Store, l as ChannelMultiplexer, ah as SessionFailureKind, J as MediaSession, P as PathHealthReporting, aB as TransportOfferResponse, aK as WtAudioLaneSeam, aL as WtAudioUplinkSeam, aS as WtVideoUplinkSeam, aR as WtDataUplinkSender, O as PathLiveness, aP as WtDataLaneSink } from './stream-data-C1du_YcA.js';
2
- export { c as ActivationState, j as AudioPlayoutOptions, D as DERIVED_LEG_SEP, o as DGRAM_HEADER_BYTES, s as DerivedLegRole, t as DgramHeader, v as DocConnectionState, G as GENERATION_TICK_EMIT_INTERVAL_MS, z as GENERATION_TICK_MAX_EXTRAPOLATION_MS, I as InboundStatsSample, M as MediaChunkBinding, E as MediaChunkSource, F as MediaChunkSourceFactory, H as MediaRecorderChunkSourceOptions, N as NegotiatorDataLaneSeam, K as NegotiatorOptions, R as PresenceState, S as PrewakeOptions, T as PrewakeResult, U as PrewakeStatus, V as QuicStreamDataTransport, X as RecordingBucket, Y as RecordingLifecycle, Z as RecordingStatus, $ as ReleaseSessionBeaconOptions, a5 as RuntimeAvailability, a6 as RuntimeWakeDetail, a7 as RuntimeWakeGolden, a8 as RuntimeWakeReasonCode, a9 as SIGNALING_PROTOCOL_VERSION, aa as STREAM_END, ae as SessionDocument, aj as SessionPhaseError, am as SessionStatsOptions, aq as SessionText, ar as SignalCarrier, as as Signaling, at as StartSessionOptions, ay as TransportEstablishedNotify, az as TransportNegotiator, aA as TransportOfferRequest, aE as TransportSessionSignaling, aG as VideoPlayoutOptions, aH as WT_CONTROL_FRAME_MAX, aI as WT_DATA_STREAM_VERSION, aJ as WatchGenerationTickOptions, aM as WtControlDecoder, aN as WtControlMessage, aO as WtDataEnvelope, aQ as WtDataStreamParser, aU as consumeWtDataStreams, aX as decodeStreamEnvelope, aZ as derivedLegName, a_ as derivedLegRole, a$ as encodeStreamEnvelope, b0 as encodeWtControlFrame, b1 as isPendingRecording, b2 as mediaRecorderChunkSource, b3 as parseDgramHeader, b4 as prewake, b5 as releaseSessionBeacon, b8 as watchGenerationTick, b9 as writeDgramHeader } from './stream-data-C1du_YcA.js';
1
+ import { ad as SessionDirectoryRequestOptions, h as AppOptions, g as App$1, ai as SessionPhase, ao as SessionStatus, ak as SessionPhaseName, A as AccessTokenOptions, a2 as RuntimeArtifact, a3 as RuntimeArtifactDownload, W as Recording, aF as TransportState, ab as Session$1, C as ChannelEndpoint, aC as TransportSession, d as ActivitySignalMode, i as AttachOptions, ac as SessionDiagnostic, b as ActivationEvent, an as SessionStatsSample, B as GenerationTick, _ as RecordingsAccessor, a4 as RuntimeArtifactsAccessor, ag as SessionEndResult, ap as SessionStream$1, ax as StreamDataTransport, af as SessionDocumentImpl, aw as StreamChunkOptions, n as ChunkReadable, Q as Presence, w as DocConnector, y as DocTokenSupplier, x as DocServerUrlResolver, a0 as RequestOptions, a1 as RequestStreamOptions, av as StoreOptions, au as Store, l as ChannelMultiplexer, ah as SessionFailureKind, J as MediaSession, P as PathHealthReporting, aB as TransportOfferResponse, aK as WtAudioLaneSeam, aL as WtAudioUplinkSeam, aS as WtVideoUplinkSeam, aR as WtDataUplinkSender, O as PathLiveness, aP as WtDataLaneSink } from './stream-data-ByijrPsc.js';
2
+ export { c as ActivationState, j as AudioPlayoutOptions, D as DERIVED_LEG_SEP, o as DGRAM_HEADER_BYTES, s as DerivedLegRole, t as DgramHeader, v as DocConnectionState, G as GENERATION_TICK_EMIT_INTERVAL_MS, z as GENERATION_TICK_MAX_EXTRAPOLATION_MS, I as InboundStatsSample, M as MediaChunkBinding, E as MediaChunkSource, F as MediaChunkSourceFactory, H as MediaRecorderChunkSourceOptions, N as NegotiatorDataLaneSeam, K as NegotiatorOptions, R as PresenceState, S as PrewakeOptions, T as PrewakeResult, U as PrewakeStatus, V as QuicStreamDataTransport, X as RecordingBucket, Y as RecordingLifecycle, Z as RecordingStatus, $ as ReleaseSessionBeaconOptions, a5 as RuntimeAvailability, a6 as RuntimeWakeDetail, a7 as RuntimeWakeGolden, a8 as RuntimeWakeReasonCode, a9 as SIGNALING_PROTOCOL_VERSION, aa as STREAM_END, ae as SessionDocument, aj as SessionPhaseError, am as SessionStatsOptions, aq as SessionText, ar as SignalCarrier, as as Signaling, at as StartSessionOptions, ay as TransportEstablishedNotify, az as TransportNegotiator, aA as TransportOfferRequest, aE as TransportSessionSignaling, aG as VideoPlayoutOptions, aH as WT_CONTROL_FRAME_MAX, aI as WT_DATA_STREAM_VERSION, aJ as WatchGenerationTickOptions, aM as WtControlDecoder, aN as WtControlMessage, aO as WtDataEnvelope, aQ as WtDataStreamParser, aU as consumeWtDataStreams, aX as decodeStreamEnvelope, aZ as derivedLegName, a_ as derivedLegRole, a$ as encodeStreamEnvelope, b0 as encodeWtControlFrame, b1 as isPendingRecording, b2 as mediaRecorderChunkSource, b3 as parseDgramHeader, b4 as prewake, b5 as releaseSessionBeacon, b8 as watchGenerationTick, b9 as writeDgramHeader } from './stream-data-ByijrPsc.js';
3
3
  import 'yjs';
4
4
  import 'y-protocols/awareness';
5
5