@urun-sh/core 0.6.5 → 0.6.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/index.js +6 -6
- package/dist/adapter/index.mjs +1 -1
- package/dist/{app-5J2CT25H.mjs → app-MMVCG3MH.mjs} +1 -1
- package/dist/chunk-GRC3SSMU.mjs +3 -0
- package/dist/{chunk-XYSKKUGW.mjs → chunk-PEJG2PNI.mjs} +1 -1
- package/dist/{chunk-YSDR2RAJ.mjs → chunk-WJRMA2FH.mjs} +5 -5
- package/dist/index.browser.js +3 -3
- package/dist/index.browser.mjs +1 -1
- package/dist/index.js +6 -6
- package/dist/index.mjs +1 -1
- package/dist/internal.browser.js +2 -2
- package/dist/internal.browser.mjs +1 -1
- package/dist/internal.js +5 -5
- package/dist/internal.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-EPBFNUD2.mjs +0 -3
package/dist/index.browser.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as cn,A as Ze,B as Zr,C as en,D as tn,E as rn,F as nn,G as sn,H as J,I as Bt,J as Te,K as et,L as jt,M as Ht,N as Vt,O as tt,P as Kt,Q as Gt,R as on,S as zt,T as Ae,U as rt,V as an,W as nt,Y as Yt,_ as dn,a as qt,aa as ln,b as we,ba as un,c as K,ca as Ee,d as ze,e as be,ea as Re,f as ye,fa as Qt,g as Ye,ga as Xt,h as Qe,ha as Jt,i as Xe,ia as Zt,j as jr,k as Hr,l as ke,m as Je,n as Vr,o as Kr,p as Gr,q as zr,r as G,s as Se,v as _e,w as Yr,x as Qr,y as Xr,z as Jr}from"./chunk-EPBFNUD2.mjs";var pn=15e3,hn=45e3,fn=12e4,it="platform",st="activation",ot="desired.activation";function er(i){if(typeof i=="string"&&i.length>0)return i;if(i&&typeof i=="object"){let e=i.note;if(typeof e=="string"&&e.length>0)return e}}var mn=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],ne=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(t?.name==="error"||t?.name==="paused")&&this._park()})}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;_park(){this._liveAt=null;for(let e of this._watches.values())if(!e.done){for(let t of e.timers)clearTimeout(t);e.timers=[],e.startedAt=null,e.lastEvent=null}}watch(e,t){if(this._stopped||this._watches.has(e))return;let r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let n=()=>this._firstMedia(e);r.addEventListener("unmute",n,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",n));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of mn){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let n={state:t,elapsedMs:r,stream:e.name},s=er(this._options.hint());s!==void 0&&(n.hint=s),e.lastEvent=n;for(let o of Array.from(this._handlers))o(n)}};var I=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",n){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,n!==void 0&&(this.cause=n),Object.setPrototypeOf(this,new.target.prototype)}},Ce=class extends I{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},De=class extends I{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function ie(i){return{baseUrl:i.baseUrl,fallbackUrls:i.fallbackUrls,orgId:i.orgId,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}function gn(i){return new z(i)}var z=class{_options;constructor(e){this._options=e}async list(e){let r=rr(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new I("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(tr)}async getDownloadUrl(e,t){let r=rr(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!wn(n))throw new I("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:tr(r.artifact),downloadUrl:n}}async _request(e,t){let r=Bt(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let s of r)try{return await this._requestFromBase(s,e,t)}catch(o){if(n=o instanceof Error?o:new Error(String(o)),n instanceof I&&bn(n.status))throw n}throw n??new I("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${J(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,s=await this._resolveToken(),o=await fetch(n,{method:"GET",headers:this._headers(s)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await fetch(n,{method:"GET",headers:this._headers(s)}))}if(!o.ok){let{code:a,message:d}=await this._readError(o,e);throw yn(o.status,a,d)}try{return await o.json()}catch(a){throw new I(`[urun] runtime artifacts: invalid JSON response from ${J(e)}`,0,"bad_response",a)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let r=J(t);try{let s=(await e.json()).error;if(s&&typeof s=="object"){let{code:o,message:a}=s;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${r}: ${a}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}};function tr(i){if(!i||typeof i!="object")throw new I("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=i,t=q(e,"artifact_id")||q(e,"id"),r=q(e,"filename"),n=q(e,"kind"),s=q(e,"status")||"ready",o=vn(e,"size_bytes"),a=q(e,"sha256");if(!t||!r||!n||o==null||!a)throw new I("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:q(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:s,createdAt:q(e,"created_at"),expiresAt:q(e,"expires_at")}}function q(i,e){let t=i[e];return typeof t=="string"&&t.length>0?t:void 0}function vn(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function wn(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function bn(i){return i===401||i===403}function yn(i,e,t){return i===401?new Ce(t,e):i===404?new De(t,e):new I(t,i,e)}function rr(i){if(!i||typeof i!="object"||Array.isArray(i))throw new I("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var O=class extends Error{status;code;constructor(e,t){super(e),this.name="RecordingsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},se=class extends O{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Ie=class extends O{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Me=class extends O{constructor(e="[urun] recordings: retain requires a temp recording",t="retain_not_temp"){super(e,{status:409,code:t}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},Le=class extends O{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},xe=class extends O{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},Z=class extends O{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",r=400){super(e,{status:r,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function at(i){return/^(\d+[smhdw])+$/.test(i)}function kn(i){if(i==="pin")return{action:"pin"};if(at(i))return{action:"retain",duration:i};throw new Z(`[urun] recordings: "${i}" is not a duration or "pin"`)}function Sn(i,e,t){let r=t||e||`HTTP ${i}`;if(i===401)return new se(r,e??"unauthorized");if(i===404)return new Ie(r,e??"not_found");if(i===400)return new Z(r,e??"bad_request",400);if(i===409)switch(e){case"retain_not_temp":return new Me(r,e);case"pin_requires_active_temp":return new Le(r,e);case"permanent_locked":return new xe(r,e)}return new O(r,{status:i,code:e??`http_${i}`})}var ee=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let r=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(r)?r:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!at(t))throw new Z(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new O("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),s=await this._resolveToken(),o=await this._fetch(n,e,s,r.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await this._fetch(n,e,s,r.body))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw Sn(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let s={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:s};return n!==void 0&&(s["Content-Type"]="application/json",o.body=JSON.stringify(n)),fetch(e,o)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new se("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:n,message:s}=r;return{code:typeof n=="string"?n:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function _n(i){return new ee(i)}var Tn=1e3,An=12e3;function dt(i,e,t={}){let r=null,n=0,s=0,o=null,a=-1,d=()=>{let h=i.get("desired.billing.generationSeconds");if(typeof h!="number"||!Number.isFinite(h)||h<=0)return null;let b=i.get("desired.billing.epoch"),w=i.get("desired.billing.updatedAtMs");return{seconds:h,epoch:typeof b=="number"&&Number.isFinite(b)?b:0,updatedAtMs:typeof w=="number"&&Number.isFinite(w)?w:null}},c=()=>{if(r===null)return null;let h=Math.min(Math.max(0,Date.now()-n),s);return r+h/1e3},l=()=>{let h=t.creditsPerSecond;if(typeof h=="number"&&Number.isFinite(h)&&h>0)return h;let b=i.get("desired.billing.creditsPerSecond");return typeof b=="number"&&Number.isFinite(b)&&b>0?b:null},p=()=>{let h=c();if(h===null)return;let b=Math.floor(h);if(b<=a)return;a=b;let w={seconds:b},T=l();T!==null&&(w.estimatedCredits=b*T),e(w)},u=h=>{n=Date.now();let b=h===null?0:Math.max(0,n-h);s=Math.max(0,12e3-b)},f=()=>{let h=d();if(h!==null){if(o!==null&&h.epoch!==o){o=h.epoch,r=h.seconds,a=-1,u(h.updatedAtMs),p();return}r!==null&&h.seconds<=r||(o=h.epoch,r=h.seconds,u(h.updatedAtMs),p())}};f();let m=i.on("change",f),k=setInterval(p,1e3);return k.unref?.(),()=>{clearInterval(k),m()}}var nr="activity",ir="visibility",En=15e3,ct=["pointerdown","pointermove","keydown","wheel","touchstart"];function lt(i){let e=i.now??Date.now,t=i.mode==="explicit",r=t?null:i.windowTarget!==void 0?i.windowTarget:typeof window<"u"?window:null,n=t?null:i.documentTarget!==void 0?i.documentTarget:typeof document<"u"?document:null,s=!1,o,a=()=>{if(s)return;let u=e();if(!(o!==void 0&&u-o<15e3)){o=u;try{i.awareness.setLocalStateField(nr,{at:u})}catch{}}},d=()=>{if(!(s||!n||n.visibilityState===void 0))try{i.awareness.setLocalStateField(ir,n.visibilityState)}catch{}},c=()=>a(),l=()=>{d(),(!n||n.visibilityState===void 0||n.visibilityState==="visible")&&a()};if(r)for(let u of ct)r.addEventListener(u,c,{passive:!0,capture:!0});n&&n.addEventListener("visibilitychange",l);let p=null;return!t&&i.isProducing&&(p=setInterval(()=>{if(!s)try{i.isProducing?.()&&a()}catch{}},15e3),p.unref?.()),a(),d(),{touch:a,dispose(){if(!s){if(s=!0,r)for(let u of ct)r.removeEventListener(u,c,{capture:!0});n&&n.removeEventListener("visibilitychange",l),p&&(clearInterval(p),p=null)}}}}var or="user_activity",ar="focus",Rn=3e4;function sr(i){switch(i){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var oe=class{_awareness;_now;_win;_state="idle";_stateHandlers=new Set;_transportUnsubs=new Set;_disposed=!1;_counts={typing:0,pointer:0,tty:0,consumer_reads:0};_inflight=0;_visibility;_focus;_lastSignalAt;_lastPublishedAt;_trailing=null;_onWindowFocus=null;_onWindowBlur=null;constructor(e={}){this._awareness=e.awareness??null,this._now=e.now??Date.now,this._win=e.windowTarget!==void 0?e.windowTarget:typeof window<"u"?window:null;let t=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null;this._win&&t&&typeof t.hasFocus=="function"&&(this._onWindowFocus=()=>this.setFocus("focused"),this._onWindowBlur=()=>this.setFocus("unfocused"),this._win.addEventListener("focus",this._onWindowFocus),this._win.addEventListener("blur",this._onWindowBlur),this.setFocus(t.hasFocus()?"focused":"unfocused"))}get state(){return this._state}onState(e){return this._stateHandlers.add(e),()=>this._stateHandlers.delete(e)}transportConnecting(){this._setState("connecting")}transportReady(){this._setState("ready")}transportClosed(){this._setState("transient_failure")}attachTransport(e){if(this._disposed)return()=>{};this._setState(sr(e.state));let t=e.on("stateChange",n=>{this._setState(sr(n))}),r=()=>{t(),this._transportUnsubs.delete(r)};return this._transportUnsubs.add(r),r}_setState(e){if(!(this._disposed||e===this._state)){this._state=e;for(let t of this._stateHandlers)try{t(e)}catch{}}}interaction(e,t=1){this._disposed||!Number.isFinite(t)||t<=0||e==="pointer"&&this._focus==="unfocused"||(this._counts[e]+=t,this._signal())}consumerRead(e=1){this._disposed||!Number.isFinite(e)||e<=0||(this._counts.consumer_reads+=e,this._signal())}get inflight(){return this._inflight}workBegin(){if(this._disposed)return()=>{};this._inflight+=1,this._inflight===1&&this._publishNow();let e=!1;return()=>{e||this._disposed||(e=!0,this._inflight-=1,this._inflight===0&&this._publishNow())}}setVisibility(e){this._disposed||(this._visibility=e)}setFocus(e){if(!(this._disposed||e===this._focus)){this._focus=e;try{this._awareness?.setLocalStateField(ar,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(or,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 Cn=250;function ut(i){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let r=Date.now();r-e<250||(e=r,i())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function pt(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,i())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function ht(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{i()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var dr="video/mp4";function ft(i,e={}){let t=e.timesliceMs??1e3,r=null,n=null,s=!1,o=(a,d,c)=>{let l=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!l)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let p=e.mimeType??(typeof l.isTypeSupported=="function"&&l.isTypeSupported(dr)?dr:void 0),u=new MediaStream([a]),f=new l(u,p?{mimeType:p}:void 0);r=f;let m=Promise.resolve();f.ondataavailable=k=>{let h=k.data;s||!h||h.size===0||(m=m.then(async()=>{let b=new Uint8Array(await h.arrayBuffer());s||d(b)}))},f.onstop=()=>{m.then(()=>{s||c()})},f.onerror=()=>{m.then(()=>{s||c()})},f.start(t)};return{start(a,d){if(r||s)return;let c=i.track();if(c){o(c,a,d);return}n=i.onTrack(l=>{!l||r||s||(n?.(),n=null,o(l,a,d))})},stop(){if(s)return;s=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Dn(i){let e=i;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=i.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function cr(i,e){let t=null,r=!1,n=!1,s=new ReadableStream({pull(o){r||(r=!0,t=i(e),t.start(a=>{if(!n)try{o.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{o.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Dn(s)}import{encode as In,decode as Mn}from"@msgpack/msgpack";var lr=65536;function gt(i){let e=In(i),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var de=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>lr)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let n=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(Object.assign(Mn(n),{raw:n}))}return t}};function ur(i,e){let t=new DataView(i.buffer,i.byteOffset,i.byteLength),r=t.getUint8(0),n=(r&240)===128,s=r===222;if(!n&&!s&&!(r===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let a=n?r&15:s?t.getUint16(1,!1):t.getUint32(1,!1),d=n?1:s?3:5,c=[];c.push(i.subarray(0,d));for(let f=0;f<a;f++){let m=d,k=ae(i,t,d);d=k.end;let b=ae(i,t,d).end;if(Ln(t.getUint8(m))){let w=t.getUint8(m),T=(w&224)===160?1:w===217?2:w===218?3:5;if(new TextDecoder().decode(i.subarray(m+T,k.end))==="t"){c.push(i.subarray(m,k.end));let A=new TextEncoder().encode(e);if(A.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");c.push(new Uint8Array([160|A.byteLength]),A)}else c.push(i.subarray(m,b))}else c.push(i.subarray(m,b));d=b}let l=c.reduce((f,m)=>f+m.byteLength,0),p=new Uint8Array(l),u=0;for(let f of c)p.set(f,u),u+=f.byteLength;return p}function Ln(i){return(i&224)===160?!0:i===217||i===218||i===219}function ae(i,e,t){let r=e.getUint8(t),n=t;if(r<=127||r>=224)return{start:n,end:t+1};if((r&224)===160)return{start:n,end:t+1+(r&31)};if((r&240)===128||(r&240)===144){let o=r&15;t+=1;let a=(r&240)===128?o*2:o;for(let d=0;d<a;d++)t=ae(i,e,t).end;return{start:n,end:t}}let s={192:0,194:0,195:0,204:1,205:2,206:4,207:8,208:1,209:2,210:4,211:8,202:4,203:8};if(s[r]!==void 0)return{start:n,end:t+1+s[r]};if(r===217||r===196)return{start:n,end:t+2+e.getUint8(t+1)};if(r===218||r===197)return{start:n,end:t+3+e.getUint16(t+1,!1)};if(r===219||r===198)return{start:n,end:t+5+e.getUint32(t+1,!1)};if(r===220||r===221){let o=r===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===220?3:5;for(let a=0;a<o;a++)t=ae(i,e,t).end;return{start:n,end:t}}if(r===222||r===223){let o=r===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===222?3:5;for(let a=0;a<o*2;a++)t=ae(i,e,t).end;return{start:n,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${r.toString(16)} at byte ${n}`)}var M=12,mt=1,xn=0,Ue=1,pr=2;function ce(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&mt)===mt,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function vt(i){let e=new Uint8Array(M),t=new DataView(e.buffer);return t.setUint32(0,i.groupId,!0),t.setUint32(4,i.frameSeq,!0),t.setUint8(8,i.keyframe?mt:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??xn),e}var Un=100,hr=100,le=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??Un}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=ce(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.isSourceRestart(t.groupId,t.frameSeq))this.resync(t.groupId);else if(t.groupId<this.newestGroupSeen||(t.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t.groupId,this.needKeyframe=!0),t.frameSeq<=this.newestFrameDelivered))return;let r=this.pending.get(t.frameSeq);if(r||(r={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r)),!r.chunks[t.fragIndex]){r.chunks[t.fragIndex]=e.subarray(M),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let n of this.pending.keys())n<t.frameSeq-1&&(this.pending.delete(n),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-hr?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-hr}resync(e){this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e,this.newestFrameDelivered=-1,this.needKeyframe=!0,this.requestKeyframe()}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let r=t.chunks.reduce((o,a)=>o+a.byteLength,0),n=new Uint8Array(r),s=0;for(let o of t.chunks)n.set(o,s),s+=o.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:n})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Pn=/^avc[13]\.[0-9a-fA-F]{6}$/;function Wn(i){return Pn.test(i)?null:`codec ${JSON.stringify(i)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function wt(i,e){let t=Wn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var fr=1,Pe=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}if(this.name===null){if(this.buf.byteLength<2)return[];let r=this.buf[0];if(r!==fr)throw new Error(`[urun] wt data stream: unknown header version 0x${r.toString(16)} \u2014 rejecting stream`);let n=this.buf[1];if(n===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+n)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+n)),this.buf=this.buf.subarray(2+n)}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+r)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let n=nt(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),n===rt&&(this.ended=!0),t.push({name:this.name,payload:n})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return t}finish(){if(this.ended&&this.buf.byteLength===0)return;let e=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN without an END envelope`)}};async function bt(i,e){let t=i.getReader();for(;;){let{value:r,done:n}=await t.read();if(n)return;r&&On(r,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function On(i,e){let t=i.getReader(),r=new Pe;try{for(;;){let{value:n,done:s}=await t.read();if(s)break;if(!(!n||n.byteLength===0))for(let{name:o,payload:a}of r.push(n))e.onData(o,a)}r.finish()}catch(n){try{await t.cancel?.(n)}catch{}throw n}}var yt=40,St=48e3,Nn=64,Fn=100,kt=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=ce(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-Fn)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let r=this.pending.get(t.frameSeq);if(!r)for(r={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r);this.pending.size>Nn;){let a=1/0;for(let d of this.pending.keys())d<a&&(a=d);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=r.fragCount||r.chunks[t.fragIndex]||(r.chunks[t.fragIndex]=e.subarray(M),r.received++,r.received<r.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let n=r.chunks.reduce((a,d)=>a+(d?.byteLength??0),0),s=new Uint8Array(n),o=0;for(let a of r.chunks)s.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:r.timestamp,data:s})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},We=class{constructor(e,t){this.config=e;this.seam=t;let r=this.seam.jitterBufferTargetMs??yt;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${yt}ms`),r=yt),this.targetS=Math.max(0,r)/1e3}config;seam;decoder=null;ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;assembler=new kt(e=>this.decodeFrame(e));start(){let e=globalThis.AudioDecoder,t=globalThis.AudioContext;if(typeof e!="function"||typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new t({sampleRate:this.config.sampleRate}),this.dest=this.ctx.createMediaStreamDestination();try{this.initDecoder(e)}catch(r){throw this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,r}}stop(){if(!this.stopped){this.stopped=!0,this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ctx?.close().catch(()=>{})}}initDecoder(e){let t=new e({output:r=>this.schedule(r),error:r=>this.onDecoderError(r)});t.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels}),this.decoder=t}decodeFrame(e){let t=globalThis.EncodedAudioChunk;if(typeof t!="function"||this.stopped)return;if(!this.decoder){let n=globalThis.AudioDecoder;if(typeof n!="function")return;try{this.initDecoder(n)}catch{return}}let r=this.decoder;r&&r.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/St)),data:e.data}))}schedule(e){let t=this.ctx,r=this.dest;if(!t||!r||this.stopped){e.close();return}if(!this.trackSurfaced){this.trackSurfaced=!0,t.resume?.().catch(()=>{});let l=r.stream.getAudioTracks()[0];l&&(this.armBridgeEndedWatch(l),this.seam.onTrack(l))}let n=e.numberOfFrames,s=Math.max(1,e.numberOfChannels),o=t.createBuffer(s,n,e.sampleRate);for(let l=0;l<s;l++){let p=new Float32Array(n);e.copyTo(p,{planeIndex:l,format:"f32-planar"}),o.copyToChannel(p,l)}let a=n/e.sampleRate;e.close();let d=t.createBufferSource();d.buffer=o,d.connect(r);let c=Math.max(this.playhead,t.currentTime+this.targetS);d.start(c),this.playhead=c+a}armBridgeEndedWatch(e){e.addEventListener?.("ended",()=>{if(!this.stopped){console.warn("[urun] WT audio bridge track ENDED while the lane is live \u2014 rebuilding the WebAudio playout surface and re-delivering the bridge track");try{this.rebuildSurface()}catch(t){console.error(`[urun] WT audio bridge rebuild failed \u2014 the reply stays silent until the next lane death re-delivers: ${t instanceof Error?t.message:String(t)}`)}}},{once:!0})}rebuildSurface(){let e=globalThis.AudioContext;if(typeof e!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");let t=this.ctx,r=new e({sampleRate:this.config.sampleRate});this.ctx=r,this.dest=r.createMediaStreamDestination(),this.playhead=0,this.trackSurfaced=!0;let n=this.dest.stream.getAudioTracks()[0];if(!n)throw new Error("[urun] rebuilt playout produced no bridge track");this.armBridgeEndedWatch(n),t?.close().catch(()=>{}),this.seam.onTrack(n)}onDecoderError(e){if(this.stopped)return;console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=globalThis.AudioDecoder;if(typeof t=="function")try{this.initDecoder(t)}catch(r){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${r instanceof Error?r.message:String(r)}`)}}};function mr(i,e){let t=i.numberOfFrames;if(i.format==="f32-planar"){let r=new Float32Array(t);return i.copyTo(r,{planeIndex:e}),r}if(i.format==="f32"){let r=new Float32Array(t*i.numberOfChannels);i.copyTo(r,{planeIndex:0});let n=new Float32Array(t);for(let s=0;s<t;s++)n[s]=r[s*i.numberOfChannels+e];return n}if(i.format==="s16"){let r=new Int16Array(t*i.numberOfChannels);i.copyTo(r,{planeIndex:0});let n=new Float32Array(t);for(let s=0;s<t;s++)n[s]=r[s*i.numberOfChannels+e]/32768;return n}throw new Error(`unsupported AudioData format for mic uplink: ${i.format}`)}var Oe=class{srcRate;channels;pos=0;prevTail=null;rem=new Float32Array(0);outTs=0;outTsSeeded=!1;constructor(e,t){if(!Number.isFinite(e)||e<=0)throw new Error(`bad mic sample rate: ${e}`);if(!Number.isInteger(t)||t<=0)throw new Error(`bad mic channel count: ${t}`);this.srcRate=e,this.channels=t}push(e,t){let r=e[0].length;if(r===0)return null;let n;if(this.channels===1)n=e[0];else{n=new Float32Array(r);for(let u=0;u<r;u++){let f=0;for(let m of e)f+=m[u];n[u]=f/this.channels}}let s=this.srcRate/48e3,o=[],a=this.pos;for(;a<=r-1;){if(a<0){let u=a+1;o.push(this.prevTail===null?n[0]:this.prevTail*(1-u)+n[0]*u)}else{let u=Math.floor(a);if(u===r-1)o.push(n[u]);else{let f=a-u;o.push(n[u]*(1-f)+n[u+1]*f)}}a+=s}if(this.pos=a-r,this.prevTail=n[r-1],this.outTsSeeded||(this.outTsSeeded=!0,this.outTs=t),o.length===0)return null;let d=new Float32Array(this.rem.length+o.length);d.set(this.rem);for(let u=0;u<o.length;u++)d[this.rem.length+u]=o[u];let c=Math.floor(d.length/960);if(c===0)return this.rem=d,null;let l=new Float32Array(c*960);l.set(d.subarray(0,c*960)),this.rem=d.slice(c*960);let p=this.outTs;return this.outTs+=c*2e4,{samples:l,timestampMicros:p}}};var Y=1200,$n=3,qn=1e4;function Bn(i){return Math.round(i*(St/1e6))%2**32>>>0}function At(i,e,t,r,n){let s=r-M;if(s<=0)return null;let o=Math.max(1,Math.ceil(t.byteLength/s));if(o>255)return null;let a=[];for(let d=0;d<o;d++){let c=t.subarray(d*s,Math.min((d+1)*s,t.byteLength)),l=vt({groupId:e>>>0,frameSeq:i>>>0,keyframe:n?.keyframe??!0,fragIndex:d,fragCount:o,lane:n?.lane??Ue}),p=new Uint8Array(M+c.byteLength);p.set(l,0),p.set(c,M),a.push(p)}return a}var Ne=class{constructor(e){this.sink=e}sink;encoder=null;encoderConfig=null;normalizer=null;AudioDataCtor=null;encoderErrorsAt=[];frameSeq=0;stopped=!1;deadCb=null;lastInputAt=0;lastOutputAt=0;encoderQueueBacklog=!1;generation=0;cancelCapture=null;captureTrack=null;nodeBridge=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.captureTrack&&this.captureTrack.readyState==="live"||(this.teardownCapture(),e===null))return;let r=globalThis.MediaStreamTrackProcessor;if(typeof r!="function"){this.die("MediaStreamTrackProcessor is not available");return}let n;if(jn(e)){let d=e,c=d.context.createMediaStreamDestination();d.connect(c),this.nodeBridge={node:d,dest:c};let l=c.stream.getAudioTracks()[0];if(!l){this.die("AudioNode bridge produced no audio track");return}n=l}else n=e;let s=++this.generation,o=new r({track:n}).readable.getReader();this.captureTrack=n;let a=!1;this.cancelCapture=()=>{a=!0,o.cancel().catch(()=>{})},(async()=>{for(;!a&&!this.stopped&&s===this.generation;){let{value:d,done:c}=await o.read();if(c)break;if(d){if(a||this.stopped||s!==this.generation){d.close();break}this.feedAudioData(d)}}!a&&!this.stopped&&s===this.generation&&(this.captureTrack=null)})().catch(d=>{!a&&!this.stopped&&s===this.generation&&this.die(`capture: ${d instanceof Error?d.message:String(d)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){if(this.cancelCapture?.(),this.cancelCapture=null,this.captureTrack=null,this.normalizer=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}this.generation++}feedAudioData(e){if(this.lastInputAt=this.nowMs(),!this.encoder){let r=globalThis.AudioEncoder;if(typeof r!="function"){e.close(),this.die("AudioEncoder is not available");return}this.encoderConfig={sampleRate:48e3,numberOfChannels:1};try{this.initEncoder(r)}catch(n){e.close(),this.encoder=null,this.die(`encoder configure: ${n instanceof Error?n.message:String(n)}`);return}}let t=this.encoder;if(!t){e.close();return}try{e.sampleRate===48e3&&e.numberOfChannels===1?t.encode(e):this.encodeNormalized(e)}catch(r){this.onEncoderError(r instanceof Error?r:new Error(String(r)))}e.close()}encodeNormalized(e){if(!this.normalizer&&(this.normalizer=new Oe(e.sampleRate,e.numberOfChannels),this.AudioDataCtor=globalThis.AudioData??null,typeof this.AudioDataCtor!="function")){this.die("AudioData is not available for mic shape normalization");return}let t;try{t=[];for(let s=0;s<e.numberOfChannels;s++)t.push(mr(e,s))}catch(s){this.die(`mic capture: ${s instanceof Error?s.message:String(s)}`);return}let r=this.normalizer.push(t,e.timestamp);if(r===null||r.samples.length===0)return;let n=new this.AudioDataCtor({format:"f32-planar",sampleRate:48e3,numberOfFrames:r.samples.length,numberOfChannels:1,timestamp:r.timestampMicros,data:r.samples});this.encoder.encode(n),n.close()}initEncoder(e){let t=this.encoderConfig;this.encoder=new e({output:n=>this.sendFrame(n),error:n=>this.onEncoderError(n)});let r={codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3,opus:{frameDuration:2e4,useinbandfec:!0,usedtx:!0,packetlossperc:5}};try{this.encoder.configure(r)}catch{console.warn("[urun] WT mic uplink: opus fec/dtx options unsupported \u2014 encoding without them"),this.encoder.configure({codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3})}}sendFrame(e){if(this.stopped)return;this.lastOutputAt=this.nowMs();let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=At(this.frameSeq,Bn(e.timestamp),t,this.sink.maxDatagramSize()||Y);if(r===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let n of r)this.sink.send(n);this.frameSeq=this.frameSeq+1>>>0}heartbeat(e){if(this.stopped||!this.encoder)return;let t=this.encoder.encodeQueueSize??0,r=2e3,n=e-this.lastInputAt<r,s=e-this.lastOutputAt>r,o=n&&s&&t>0&&this.encoderQueueBacklog;this.encoderQueueBacklog=t>0,o&&this.onEncoderError(new Error(`encoder wedged: ${t} frames queued, no output for ${r}ms`))}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(n=>t-n<qn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=$n){this.die(`audio encoder: ${e.message}`);return}console.warn("[urun] WT mic uplink encoder error \u2014 re-initializing the encoder:",e.message);try{this.encoder?.close()}catch{}this.encoder=null;let r=globalThis.AudioEncoder;if(!(typeof r!="function"||!this.encoderConfig))try{this.initEncoder(r)}catch(n){this.die(`encoder re-init: ${n instanceof Error?n.message:String(n)}`)}}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function jn(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var gr="urun-mic-tap";var vr=`
|
|
1
|
+
import{$ as cn,A as Ze,B as Zr,C as en,D as tn,E as rn,F as nn,G as sn,H as J,I as Bt,J as Te,K as et,L as jt,M as Ht,N as Vt,O as tt,P as Kt,Q as Gt,R as on,S as zt,T as Ae,U as rt,V as an,W as nt,Y as Yt,_ as dn,a as qt,aa as ln,b as we,ba as un,c as K,ca as Ee,d as ze,e as be,ea as Re,f as ye,fa as Qt,g as Ye,ga as Xt,h as Qe,ha as Jt,i as Xe,ia as Zt,j as jr,k as Hr,l as ke,m as Je,n as Vr,o as Kr,p as Gr,q as zr,r as G,s as Se,v as _e,w as Yr,x as Qr,y as Xr,z as Jr}from"./chunk-GRC3SSMU.mjs";var pn=15e3,hn=45e3,fn=12e4,it="platform",st="activation",ot="desired.activation";function er(i){if(typeof i=="string"&&i.length>0)return i;if(i&&typeof i=="object"){let e=i.note;if(typeof e=="string"&&e.length>0)return e}}var mn=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],ne=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(t?.name==="error"||t?.name==="paused")&&this._park()})}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;_park(){this._liveAt=null;for(let e of this._watches.values())if(!e.done){for(let t of e.timers)clearTimeout(t);e.timers=[],e.startedAt=null,e.lastEvent=null}}watch(e,t){if(this._stopped||this._watches.has(e))return;let r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let n=()=>this._firstMedia(e);r.addEventListener("unmute",n,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",n));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of mn){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let n={state:t,elapsedMs:r,stream:e.name},s=er(this._options.hint());s!==void 0&&(n.hint=s),e.lastEvent=n;for(let o of Array.from(this._handlers))o(n)}};var I=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",n){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,n!==void 0&&(this.cause=n),Object.setPrototypeOf(this,new.target.prototype)}},Ce=class extends I{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},De=class extends I{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function ie(i){return{baseUrl:i.baseUrl,fallbackUrls:i.fallbackUrls,orgId:i.orgId,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}function gn(i){return new z(i)}var z=class{_options;constructor(e){this._options=e}async list(e){let r=rr(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new I("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(tr)}async getDownloadUrl(e,t){let r=rr(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!wn(n))throw new I("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:tr(r.artifact),downloadUrl:n}}async _request(e,t){let r=Bt(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let s of r)try{return await this._requestFromBase(s,e,t)}catch(o){if(n=o instanceof Error?o:new Error(String(o)),n instanceof I&&bn(n.status))throw n}throw n??new I("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${J(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,s=await this._resolveToken(),o=await fetch(n,{method:"GET",headers:this._headers(s)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await fetch(n,{method:"GET",headers:this._headers(s)}))}if(!o.ok){let{code:a,message:d}=await this._readError(o,e);throw yn(o.status,a,d)}try{return await o.json()}catch(a){throw new I(`[urun] runtime artifacts: invalid JSON response from ${J(e)}`,0,"bad_response",a)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let r=J(t);try{let s=(await e.json()).error;if(s&&typeof s=="object"){let{code:o,message:a}=s;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${r}: ${a}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}};function tr(i){if(!i||typeof i!="object")throw new I("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=i,t=q(e,"artifact_id")||q(e,"id"),r=q(e,"filename"),n=q(e,"kind"),s=q(e,"status")||"ready",o=vn(e,"size_bytes"),a=q(e,"sha256");if(!t||!r||!n||o==null||!a)throw new I("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:q(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:s,createdAt:q(e,"created_at"),expiresAt:q(e,"expires_at")}}function q(i,e){let t=i[e];return typeof t=="string"&&t.length>0?t:void 0}function vn(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function wn(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function bn(i){return i===401||i===403}function yn(i,e,t){return i===401?new Ce(t,e):i===404?new De(t,e):new I(t,i,e)}function rr(i){if(!i||typeof i!="object"||Array.isArray(i))throw new I("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var O=class extends Error{status;code;constructor(e,t){super(e),this.name="RecordingsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},se=class extends O{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Ie=class extends O{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Me=class extends O{constructor(e="[urun] recordings: retain requires a temp recording",t="retain_not_temp"){super(e,{status:409,code:t}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},Le=class extends O{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},xe=class extends O{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},Z=class extends O{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",r=400){super(e,{status:r,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function at(i){return/^(\d+[smhdw])+$/.test(i)}function kn(i){if(i==="pin")return{action:"pin"};if(at(i))return{action:"retain",duration:i};throw new Z(`[urun] recordings: "${i}" is not a duration or "pin"`)}function Sn(i,e,t){let r=t||e||`HTTP ${i}`;if(i===401)return new se(r,e??"unauthorized");if(i===404)return new Ie(r,e??"not_found");if(i===400)return new Z(r,e??"bad_request",400);if(i===409)switch(e){case"retain_not_temp":return new Me(r,e);case"pin_requires_active_temp":return new Le(r,e);case"permanent_locked":return new xe(r,e)}return new O(r,{status:i,code:e??`http_${i}`})}var ee=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let r=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(r)?r:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!at(t))throw new Z(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new O("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),s=await this._resolveToken(),o=await this._fetch(n,e,s,r.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await this._fetch(n,e,s,r.body))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw Sn(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let s={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:s};return n!==void 0&&(s["Content-Type"]="application/json",o.body=JSON.stringify(n)),fetch(e,o)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new se("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:n,message:s}=r;return{code:typeof n=="string"?n:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function _n(i){return new ee(i)}var Tn=1e3,An=12e3;function dt(i,e,t={}){let r=null,n=0,s=0,o=null,a=-1,d=()=>{let h=i.get("desired.billing.generationSeconds");if(typeof h!="number"||!Number.isFinite(h)||h<=0)return null;let b=i.get("desired.billing.epoch"),w=i.get("desired.billing.updatedAtMs");return{seconds:h,epoch:typeof b=="number"&&Number.isFinite(b)?b:0,updatedAtMs:typeof w=="number"&&Number.isFinite(w)?w:null}},c=()=>{if(r===null)return null;let h=Math.min(Math.max(0,Date.now()-n),s);return r+h/1e3},l=()=>{let h=t.creditsPerSecond;if(typeof h=="number"&&Number.isFinite(h)&&h>0)return h;let b=i.get("desired.billing.creditsPerSecond");return typeof b=="number"&&Number.isFinite(b)&&b>0?b:null},p=()=>{let h=c();if(h===null)return;let b=Math.floor(h);if(b<=a)return;a=b;let w={seconds:b},T=l();T!==null&&(w.estimatedCredits=b*T),e(w)},u=h=>{n=Date.now();let b=h===null?0:Math.max(0,n-h);s=Math.max(0,12e3-b)},f=()=>{let h=d();if(h!==null){if(o!==null&&h.epoch!==o){o=h.epoch,r=h.seconds,a=-1,u(h.updatedAtMs),p();return}r!==null&&h.seconds<=r||(o=h.epoch,r=h.seconds,u(h.updatedAtMs),p())}};f();let m=i.on("change",f),k=setInterval(p,1e3);return k.unref?.(),()=>{clearInterval(k),m()}}var nr="activity",ir="visibility",En=15e3,ct=["pointerdown","pointermove","keydown","wheel","touchstart"];function lt(i){let e=i.now??Date.now,t=i.mode==="explicit",r=t?null:i.windowTarget!==void 0?i.windowTarget:typeof window<"u"?window:null,n=t?null:i.documentTarget!==void 0?i.documentTarget:typeof document<"u"?document:null,s=!1,o,a=()=>{if(s)return;let u=e();if(!(o!==void 0&&u-o<15e3)){o=u;try{i.awareness.setLocalStateField(nr,{at:u})}catch{}}},d=()=>{if(!(s||!n||n.visibilityState===void 0))try{i.awareness.setLocalStateField(ir,n.visibilityState)}catch{}},c=()=>a(),l=()=>{d(),(!n||n.visibilityState===void 0||n.visibilityState==="visible")&&a()};if(r)for(let u of ct)r.addEventListener(u,c,{passive:!0,capture:!0});n&&n.addEventListener("visibilitychange",l);let p=null;return!t&&i.isProducing&&(p=setInterval(()=>{if(!s)try{i.isProducing?.()&&a()}catch{}},15e3),p.unref?.()),a(),d(),{touch:a,dispose(){if(!s){if(s=!0,r)for(let u of ct)r.removeEventListener(u,c,{capture:!0});n&&n.removeEventListener("visibilitychange",l),p&&(clearInterval(p),p=null)}}}}var or="user_activity",ar="focus",Rn=3e4;function sr(i){switch(i){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var oe=class{_awareness;_now;_win;_state="idle";_stateHandlers=new Set;_transportUnsubs=new Set;_disposed=!1;_counts={typing:0,pointer:0,tty:0,consumer_reads:0};_inflight=0;_visibility;_focus;_lastSignalAt;_lastPublishedAt;_trailing=null;_onWindowFocus=null;_onWindowBlur=null;constructor(e={}){this._awareness=e.awareness??null,this._now=e.now??Date.now,this._win=e.windowTarget!==void 0?e.windowTarget:typeof window<"u"?window:null;let t=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null;this._win&&t&&typeof t.hasFocus=="function"&&(this._onWindowFocus=()=>this.setFocus("focused"),this._onWindowBlur=()=>this.setFocus("unfocused"),this._win.addEventListener("focus",this._onWindowFocus),this._win.addEventListener("blur",this._onWindowBlur),this.setFocus(t.hasFocus()?"focused":"unfocused"))}get state(){return this._state}onState(e){return this._stateHandlers.add(e),()=>this._stateHandlers.delete(e)}transportConnecting(){this._setState("connecting")}transportReady(){this._setState("ready")}transportClosed(){this._setState("transient_failure")}attachTransport(e){if(this._disposed)return()=>{};this._setState(sr(e.state));let t=e.on("stateChange",n=>{this._setState(sr(n))}),r=()=>{t(),this._transportUnsubs.delete(r)};return this._transportUnsubs.add(r),r}_setState(e){if(!(this._disposed||e===this._state)){this._state=e;for(let t of this._stateHandlers)try{t(e)}catch{}}}interaction(e,t=1){this._disposed||!Number.isFinite(t)||t<=0||e==="pointer"&&this._focus==="unfocused"||(this._counts[e]+=t,this._signal())}consumerRead(e=1){this._disposed||!Number.isFinite(e)||e<=0||(this._counts.consumer_reads+=e,this._signal())}get inflight(){return this._inflight}workBegin(){if(this._disposed)return()=>{};this._inflight+=1,this._inflight===1&&this._publishNow();let e=!1;return()=>{e||this._disposed||(e=!0,this._inflight-=1,this._inflight===0&&this._publishNow())}}setVisibility(e){this._disposed||(this._visibility=e)}setFocus(e){if(!(this._disposed||e===this._focus)){this._focus=e;try{this._awareness?.setLocalStateField(ar,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(or,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 Cn=250;function ut(i){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let r=Date.now();r-e<250||(e=r,i())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function pt(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,i())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function ht(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{i()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var dr="video/mp4";function ft(i,e={}){let t=e.timesliceMs??1e3,r=null,n=null,s=!1,o=(a,d,c)=>{let l=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!l)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let p=e.mimeType??(typeof l.isTypeSupported=="function"&&l.isTypeSupported(dr)?dr:void 0),u=new MediaStream([a]),f=new l(u,p?{mimeType:p}:void 0);r=f;let m=Promise.resolve();f.ondataavailable=k=>{let h=k.data;s||!h||h.size===0||(m=m.then(async()=>{let b=new Uint8Array(await h.arrayBuffer());s||d(b)}))},f.onstop=()=>{m.then(()=>{s||c()})},f.onerror=()=>{m.then(()=>{s||c()})},f.start(t)};return{start(a,d){if(r||s)return;let c=i.track();if(c){o(c,a,d);return}n=i.onTrack(l=>{!l||r||s||(n?.(),n=null,o(l,a,d))})},stop(){if(s)return;s=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Dn(i){let e=i;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=i.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function cr(i,e){let t=null,r=!1,n=!1,s=new ReadableStream({pull(o){r||(r=!0,t=i(e),t.start(a=>{if(!n)try{o.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{o.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Dn(s)}import{encode as In,decode as Mn}from"@msgpack/msgpack";var lr=65536;function gt(i){let e=In(i),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var de=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>lr)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let n=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(Object.assign(Mn(n),{raw:n}))}return t}};function ur(i,e){let t=new DataView(i.buffer,i.byteOffset,i.byteLength),r=t.getUint8(0),n=(r&240)===128,s=r===222;if(!n&&!s&&!(r===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let a=n?r&15:s?t.getUint16(1,!1):t.getUint32(1,!1),d=n?1:s?3:5,c=[];c.push(i.subarray(0,d));for(let f=0;f<a;f++){let m=d,k=ae(i,t,d);d=k.end;let b=ae(i,t,d).end;if(Ln(t.getUint8(m))){let w=t.getUint8(m),T=(w&224)===160?1:w===217?2:w===218?3:5;if(new TextDecoder().decode(i.subarray(m+T,k.end))==="t"){c.push(i.subarray(m,k.end));let A=new TextEncoder().encode(e);if(A.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");c.push(new Uint8Array([160|A.byteLength]),A)}else c.push(i.subarray(m,b))}else c.push(i.subarray(m,b));d=b}let l=c.reduce((f,m)=>f+m.byteLength,0),p=new Uint8Array(l),u=0;for(let f of c)p.set(f,u),u+=f.byteLength;return p}function Ln(i){return(i&224)===160?!0:i===217||i===218||i===219}function ae(i,e,t){let r=e.getUint8(t),n=t;if(r<=127||r>=224)return{start:n,end:t+1};if((r&224)===160)return{start:n,end:t+1+(r&31)};if((r&240)===128||(r&240)===144){let o=r&15;t+=1;let a=(r&240)===128?o*2:o;for(let d=0;d<a;d++)t=ae(i,e,t).end;return{start:n,end:t}}let s={192:0,194:0,195:0,204:1,205:2,206:4,207:8,208:1,209:2,210:4,211:8,202:4,203:8};if(s[r]!==void 0)return{start:n,end:t+1+s[r]};if(r===217||r===196)return{start:n,end:t+2+e.getUint8(t+1)};if(r===218||r===197)return{start:n,end:t+3+e.getUint16(t+1,!1)};if(r===219||r===198)return{start:n,end:t+5+e.getUint32(t+1,!1)};if(r===220||r===221){let o=r===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===220?3:5;for(let a=0;a<o;a++)t=ae(i,e,t).end;return{start:n,end:t}}if(r===222||r===223){let o=r===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===222?3:5;for(let a=0;a<o*2;a++)t=ae(i,e,t).end;return{start:n,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${r.toString(16)} at byte ${n}`)}var M=12,mt=1,xn=0,Ue=1,pr=2;function ce(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&mt)===mt,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function vt(i){let e=new Uint8Array(M),t=new DataView(e.buffer);return t.setUint32(0,i.groupId,!0),t.setUint32(4,i.frameSeq,!0),t.setUint8(8,i.keyframe?mt:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??xn),e}var Un=100,hr=100,le=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??Un}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=ce(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.isSourceRestart(t.groupId,t.frameSeq))this.resync(t.groupId);else if(t.groupId<this.newestGroupSeen||(t.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t.groupId,this.needKeyframe=!0),t.frameSeq<=this.newestFrameDelivered))return;let r=this.pending.get(t.frameSeq);if(r||(r={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r)),!r.chunks[t.fragIndex]){r.chunks[t.fragIndex]=e.subarray(M),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let n of this.pending.keys())n<t.frameSeq-1&&(this.pending.delete(n),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-hr?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-hr}resync(e){this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e,this.newestFrameDelivered=-1,this.needKeyframe=!0,this.requestKeyframe()}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let r=t.chunks.reduce((o,a)=>o+a.byteLength,0),n=new Uint8Array(r),s=0;for(let o of t.chunks)n.set(o,s),s+=o.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:n})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Pn=/^avc[13]\.[0-9a-fA-F]{6}$/;function Wn(i){return Pn.test(i)?null:`codec ${JSON.stringify(i)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function wt(i,e){let t=Wn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var fr=1,Pe=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}if(this.name===null){if(this.buf.byteLength<2)return[];let r=this.buf[0];if(r!==fr)throw new Error(`[urun] wt data stream: unknown header version 0x${r.toString(16)} \u2014 rejecting stream`);let n=this.buf[1];if(n===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+n)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+n)),this.buf=this.buf.subarray(2+n)}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+r)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let n=nt(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),n===rt&&(this.ended=!0),t.push({name:this.name,payload:n})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return t}finish(){if(this.ended&&this.buf.byteLength===0)return;let e=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN without an END envelope`)}};async function bt(i,e){let t=i.getReader();for(;;){let{value:r,done:n}=await t.read();if(n)return;r&&On(r,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function On(i,e){let t=i.getReader(),r=new Pe;try{for(;;){let{value:n,done:s}=await t.read();if(s)break;if(!(!n||n.byteLength===0))for(let{name:o,payload:a}of r.push(n))e.onData(o,a)}r.finish()}catch(n){try{await t.cancel?.(n)}catch{}throw n}}var yt=40,St=48e3,Nn=64,Fn=100,kt=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=ce(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-Fn)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let r=this.pending.get(t.frameSeq);if(!r)for(r={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r);this.pending.size>Nn;){let a=1/0;for(let d of this.pending.keys())d<a&&(a=d);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=r.fragCount||r.chunks[t.fragIndex]||(r.chunks[t.fragIndex]=e.subarray(M),r.received++,r.received<r.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let n=r.chunks.reduce((a,d)=>a+(d?.byteLength??0),0),s=new Uint8Array(n),o=0;for(let a of r.chunks)s.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:r.timestamp,data:s})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},We=class{constructor(e,t){this.config=e;this.seam=t;let r=this.seam.jitterBufferTargetMs??yt;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${yt}ms`),r=yt),this.targetS=Math.max(0,r)/1e3}config;seam;decoder=null;ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;assembler=new kt(e=>this.decodeFrame(e));start(){let e=globalThis.AudioDecoder,t=globalThis.AudioContext;if(typeof e!="function"||typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new t({sampleRate:this.config.sampleRate}),this.dest=this.ctx.createMediaStreamDestination();try{this.initDecoder(e)}catch(r){throw this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,r}}stop(){if(!this.stopped){this.stopped=!0,this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ctx?.close().catch(()=>{})}}initDecoder(e){let t=new e({output:r=>this.schedule(r),error:r=>this.onDecoderError(r)});t.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels}),this.decoder=t}decodeFrame(e){let t=globalThis.EncodedAudioChunk;if(typeof t!="function"||this.stopped)return;if(!this.decoder){let n=globalThis.AudioDecoder;if(typeof n!="function")return;try{this.initDecoder(n)}catch{return}}let r=this.decoder;r&&r.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/St)),data:e.data}))}schedule(e){let t=this.ctx,r=this.dest;if(!t||!r||this.stopped){e.close();return}if(!this.trackSurfaced){this.trackSurfaced=!0,t.resume?.().catch(()=>{});let l=r.stream.getAudioTracks()[0];l&&(this.armBridgeEndedWatch(l),this.seam.onTrack(l))}let n=e.numberOfFrames,s=Math.max(1,e.numberOfChannels),o=t.createBuffer(s,n,e.sampleRate);for(let l=0;l<s;l++){let p=new Float32Array(n);e.copyTo(p,{planeIndex:l,format:"f32-planar"}),o.copyToChannel(p,l)}let a=n/e.sampleRate;e.close();let d=t.createBufferSource();d.buffer=o,d.connect(r);let c=Math.max(this.playhead,t.currentTime+this.targetS);d.start(c),this.playhead=c+a}armBridgeEndedWatch(e){e.addEventListener?.("ended",()=>{if(!this.stopped){console.warn("[urun] WT audio bridge track ENDED while the lane is live \u2014 rebuilding the WebAudio playout surface and re-delivering the bridge track");try{this.rebuildSurface()}catch(t){console.error(`[urun] WT audio bridge rebuild failed \u2014 the reply stays silent until the next lane death re-delivers: ${t instanceof Error?t.message:String(t)}`)}}},{once:!0})}rebuildSurface(){let e=globalThis.AudioContext;if(typeof e!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");let t=this.ctx,r=new e({sampleRate:this.config.sampleRate});this.ctx=r,this.dest=r.createMediaStreamDestination(),this.playhead=0,this.trackSurfaced=!0;let n=this.dest.stream.getAudioTracks()[0];if(!n)throw new Error("[urun] rebuilt playout produced no bridge track");this.armBridgeEndedWatch(n),t?.close().catch(()=>{}),this.seam.onTrack(n)}onDecoderError(e){if(this.stopped)return;console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=globalThis.AudioDecoder;if(typeof t=="function")try{this.initDecoder(t)}catch(r){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${r instanceof Error?r.message:String(r)}`)}}};function mr(i,e){let t=i.numberOfFrames;if(i.format==="f32-planar"){let r=new Float32Array(t);return i.copyTo(r,{planeIndex:e}),r}if(i.format==="f32"){let r=new Float32Array(t*i.numberOfChannels);i.copyTo(r,{planeIndex:0});let n=new Float32Array(t);for(let s=0;s<t;s++)n[s]=r[s*i.numberOfChannels+e];return n}if(i.format==="s16"){let r=new Int16Array(t*i.numberOfChannels);i.copyTo(r,{planeIndex:0});let n=new Float32Array(t);for(let s=0;s<t;s++)n[s]=r[s*i.numberOfChannels+e]/32768;return n}throw new Error(`unsupported AudioData format for mic uplink: ${i.format}`)}var Oe=class{srcRate;channels;pos=0;prevTail=null;rem=new Float32Array(0);outTs=0;outTsSeeded=!1;constructor(e,t){if(!Number.isFinite(e)||e<=0)throw new Error(`bad mic sample rate: ${e}`);if(!Number.isInteger(t)||t<=0)throw new Error(`bad mic channel count: ${t}`);this.srcRate=e,this.channels=t}push(e,t){let r=e[0].length;if(r===0)return null;let n;if(this.channels===1)n=e[0];else{n=new Float32Array(r);for(let u=0;u<r;u++){let f=0;for(let m of e)f+=m[u];n[u]=f/this.channels}}let s=this.srcRate/48e3,o=[],a=this.pos;for(;a<=r-1;){if(a<0){let u=a+1;o.push(this.prevTail===null?n[0]:this.prevTail*(1-u)+n[0]*u)}else{let u=Math.floor(a);if(u===r-1)o.push(n[u]);else{let f=a-u;o.push(n[u]*(1-f)+n[u+1]*f)}}a+=s}if(this.pos=a-r,this.prevTail=n[r-1],this.outTsSeeded||(this.outTsSeeded=!0,this.outTs=t),o.length===0)return null;let d=new Float32Array(this.rem.length+o.length);d.set(this.rem);for(let u=0;u<o.length;u++)d[this.rem.length+u]=o[u];let c=Math.floor(d.length/960);if(c===0)return this.rem=d,null;let l=new Float32Array(c*960);l.set(d.subarray(0,c*960)),this.rem=d.slice(c*960);let p=this.outTs;return this.outTs+=c*2e4,{samples:l,timestampMicros:p}}};var Y=1200,$n=3,qn=1e4;function Bn(i){return Math.round(i*(St/1e6))%2**32>>>0}function At(i,e,t,r,n){let s=r-M;if(s<=0)return null;let o=Math.max(1,Math.ceil(t.byteLength/s));if(o>255)return null;let a=[];for(let d=0;d<o;d++){let c=t.subarray(d*s,Math.min((d+1)*s,t.byteLength)),l=vt({groupId:e>>>0,frameSeq:i>>>0,keyframe:n?.keyframe??!0,fragIndex:d,fragCount:o,lane:n?.lane??Ue}),p=new Uint8Array(M+c.byteLength);p.set(l,0),p.set(c,M),a.push(p)}return a}var Ne=class{constructor(e){this.sink=e}sink;encoder=null;encoderConfig=null;normalizer=null;AudioDataCtor=null;encoderErrorsAt=[];frameSeq=0;stopped=!1;deadCb=null;lastInputAt=0;lastOutputAt=0;encoderQueueBacklog=!1;generation=0;cancelCapture=null;captureTrack=null;nodeBridge=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.captureTrack&&this.captureTrack.readyState==="live"||(this.teardownCapture(),e===null))return;let r=globalThis.MediaStreamTrackProcessor;if(typeof r!="function"){this.die("MediaStreamTrackProcessor is not available");return}let n;if(jn(e)){let d=e,c=d.context.createMediaStreamDestination();d.connect(c),this.nodeBridge={node:d,dest:c};let l=c.stream.getAudioTracks()[0];if(!l){this.die("AudioNode bridge produced no audio track");return}n=l}else n=e;let s=++this.generation,o=new r({track:n}).readable.getReader();this.captureTrack=n;let a=!1;this.cancelCapture=()=>{a=!0,o.cancel().catch(()=>{})},(async()=>{for(;!a&&!this.stopped&&s===this.generation;){let{value:d,done:c}=await o.read();if(c)break;if(d){if(a||this.stopped||s!==this.generation){d.close();break}this.feedAudioData(d)}}!a&&!this.stopped&&s===this.generation&&(this.captureTrack=null)})().catch(d=>{!a&&!this.stopped&&s===this.generation&&this.die(`capture: ${d instanceof Error?d.message:String(d)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){if(this.cancelCapture?.(),this.cancelCapture=null,this.captureTrack=null,this.normalizer=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}this.generation++}feedAudioData(e){if(this.lastInputAt=this.nowMs(),!this.encoder){let r=globalThis.AudioEncoder;if(typeof r!="function"){e.close(),this.die("AudioEncoder is not available");return}this.encoderConfig={sampleRate:48e3,numberOfChannels:1};try{this.initEncoder(r)}catch(n){e.close(),this.encoder=null,this.die(`encoder configure: ${n instanceof Error?n.message:String(n)}`);return}}let t=this.encoder;if(!t){e.close();return}try{e.sampleRate===48e3&&e.numberOfChannels===1?t.encode(e):this.encodeNormalized(e)}catch(r){this.onEncoderError(r instanceof Error?r:new Error(String(r)))}e.close()}encodeNormalized(e){if(!this.normalizer&&(this.normalizer=new Oe(e.sampleRate,e.numberOfChannels),this.AudioDataCtor=globalThis.AudioData??null,typeof this.AudioDataCtor!="function")){this.die("AudioData is not available for mic shape normalization");return}let t;try{t=[];for(let s=0;s<e.numberOfChannels;s++)t.push(mr(e,s))}catch(s){this.die(`mic capture: ${s instanceof Error?s.message:String(s)}`);return}let r=this.normalizer.push(t,e.timestamp);if(r===null||r.samples.length===0)return;let n=new this.AudioDataCtor({format:"f32-planar",sampleRate:48e3,numberOfFrames:r.samples.length,numberOfChannels:1,timestamp:r.timestampMicros,data:r.samples});this.encoder.encode(n),n.close()}initEncoder(e){let t=this.encoderConfig;this.encoder=new e({output:n=>this.sendFrame(n),error:n=>this.onEncoderError(n)});let r={codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3,opus:{frameDuration:2e4,useinbandfec:!0,usedtx:!0,packetlossperc:5}};try{this.encoder.configure(r)}catch{console.warn("[urun] WT mic uplink: opus fec/dtx options unsupported \u2014 encoding without them"),this.encoder.configure({codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3})}}sendFrame(e){if(this.stopped)return;this.lastOutputAt=this.nowMs();let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=At(this.frameSeq,Bn(e.timestamp),t,this.sink.maxDatagramSize()||Y);if(r===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let n of r)this.sink.send(n);this.frameSeq=this.frameSeq+1>>>0}heartbeat(e){if(this.stopped||!this.encoder)return;let t=this.encoder.encodeQueueSize??0,r=2e3,n=e-this.lastInputAt<r,s=e-this.lastOutputAt>r,o=n&&s&&t>0&&this.encoderQueueBacklog;this.encoderQueueBacklog=t>0,o&&this.onEncoderError(new Error(`encoder wedged: ${t} frames queued, no output for ${r}ms`))}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(n=>t-n<qn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=$n){this.die(`audio encoder: ${e.message}`);return}console.warn("[urun] WT mic uplink encoder error \u2014 re-initializing the encoder:",e.message);try{this.encoder?.close()}catch{}this.encoder=null;let r=globalThis.AudioEncoder;if(!(typeof r!="function"||!this.encoderConfig))try{this.initEncoder(r)}catch(n){this.die(`encoder re-init: ${n instanceof Error?n.message:String(n)}`)}}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function jn(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var gr="urun-mic-tap";var vr=`
|
|
2
2
|
class UrunMicTap extends AudioWorkletProcessor {
|
|
3
3
|
constructor(options) {
|
|
4
4
|
super(options)
|