@urun-sh/core 0.2.38 → 0.2.39
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/index.browser.d.mts +2 -0
- package/dist/index.browser.d.ts +2 -0
- package/dist/index.browser.js +2 -2
- package/dist/index.browser.mjs +1 -1
- package/dist/index.d.mts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +5 -5
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __urunCreateRequire } from 'node:module'; const require = globalThis.require ?? __urunCreateRequire(import.meta.url);
|
|
2
|
-
import{A as Ke,B as ye,C as Ge,D as ze,E as Ye,F as Nt,G as Z,I as ee,J as te,L as Je,N as re,P as Xe,Q as Qe,R as Ze,S as et,T as tt,a as Ve,b as J,c as F,d as Tt,e as X,f as fe,g as me,h as he,i as At,j as Rt,k as Q,l as ge,m as Ct,n as Et,o as It,p as ve,q as Pt,r as Mt,s as we,t as xt,u as Ot,v as Dt,w as Ut,x as Lt,y as Ft,z as D}from"./chunk-TQBKKR7C.mjs";var qt=15e3,Wt=45e3,jt=12e4,be="platform",_e="activation",Se="desired.activation";function rt(s){if(typeof s=="string"&&s.length>0)return s;if(s&&typeof s=="object"){let e=s.note;if(typeof e=="string"&&e.length>0)return e}}var $t=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],N=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(t?.name==="error"||t?.name==="ended"||t?.name==="expired")&&this.dispose()}),this._stopped&&(this._offPhase(),this._offPhase=null)}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;watch(e,t){if(this._stopped||this._watches.has(e))return;let r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let n=()=>this._firstMedia(e);r.addEventListener("unmute",n,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",n));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of $t){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let n={state:t,elapsedMs:r,stream:e.name},o=rt(this._options.hint());o!==void 0&&(n.hint=o),e.lastEvent=n;for(let i of Array.from(this._handlers))i(n)}};var b=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)}},ne=class extends b{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},se=class extends b{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function q(s){return{baseUrl:s.baseUrl,fallbackUrls:s.fallbackUrls,orgId:s.orgId,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}function Ht(s){return new I(s)}var I=class{_options;constructor(e){this._options=e}async list(e){let r=st(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new b("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(nt)}async getDownloadUrl(e,t){let r=st(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!Vt(n))throw new b("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:nt(r.artifact),downloadUrl:n}}async _request(e,t){let r=Ke(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let o of r)try{return await this._requestFromBase(o,e,t)}catch(i){if(n=i instanceof Error?i:new Error(String(i)),n instanceof b&&Kt(n.status))throw n}throw n??new b("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${D(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,o=await this._resolveToken(),i=await fetch(n,{method:"GET",headers:this._headers(o)});if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await fetch(n,{method:"GET",headers:this._headers(o)}))}if(!i.ok){let{code:a,message:c}=await this._readError(i,e);throw Gt(i.status,a,c)}try{return await i.json()}catch(a){throw new b(`[urun] runtime artifacts: invalid JSON response from ${D(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=D(t);try{let o=(await e.json()).error;if(o&&typeof o=="object"){let{code:i,message:a}=o;return{code:typeof i=="string"&&i.length>0?i:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${r}: ${a}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}};function nt(s){if(!s||typeof s!="object")throw new b("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=s,t=R(e,"artifact_id")||R(e,"id"),r=R(e,"filename"),n=R(e,"kind"),o=R(e,"status")||"ready",i=Bt(e,"size_bytes"),a=R(e,"sha256");if(!t||!r||!n||i==null||!a)throw new b("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:R(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:R(e,"created_at"),expiresAt:R(e,"expires_at")}}function R(s,e){let t=s[e];return typeof t=="string"&&t.length>0?t:void 0}function Bt(s,e){let t=s[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function Vt(s){try{return new URL(s).protocol==="https:"}catch{return!1}}function Kt(s){return s===401||s===403}function Gt(s,e,t){return s===401?new ne(t,e):s===404?new se(t,e):new b(t,s,e)}function st(s){if(!s||typeof s!="object"||Array.isArray(s))throw new b("[urun] runtime artifacts: malformed response",0,"bad_response");return s}var S=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)}},W=class extends S{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 S{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 S{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)}},ae=class extends S{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},ce=class extends S{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},U=class extends S{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 ke(s){return/^(\d+[smhdw])+$/.test(s)}function zt(s){if(s==="pin")return{action:"pin"};if(ke(s))return{action:"retain",duration:s};throw new U(`[urun] recordings: "${s}" is not a duration or "pin"`)}function Yt(s,e,t){let r=t||e||`HTTP ${s}`;if(s===401)return new W(r,e??"unauthorized");if(s===404)return new ie(r,e??"not_found");if(s===400)return new U(r,e??"bad_request",400);if(s===409)switch(e){case"retain_not_temp":return new oe(r,e);case"pin_requires_active_temp":return new ae(r,e);case"permanent_locked":return new ce(r,e)}return new S(r,{status:s,code:e??`http_${s}`})}var L=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(!ke(t))throw new U(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new S("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),o=await this._resolveToken(),i=await this._fetch(n,e,o,r.body);if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await this._fetch(n,e,o,r.body))}if(!i.ok){let{code:a,message:c}=await this._readError(i);throw Yt(i.status,a,c)}return this._readJson(i)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,i])=>`${encodeURIComponent(o)}=${encodeURIComponent(i)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let o={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(o["X-Auth-Provider"]=this._options.authProvider);let i={method:t,headers:o};return n!==void 0&&(o["Content-Type"]="application/json",i.body=JSON.stringify(n)),fetch(e,i)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new W("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:n,message:o}=r;return{code:typeof n=="string"?n:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Jt(s){return new L(s)}var it="activity",ot="visibility",Xt=15e3,Te=["pointerdown","pointermove","keydown","wheel","touchstart"];function Ae(s){let e=s.now??Date.now,t=s.windowTarget!==void 0?s.windowTarget:typeof window<"u"?window:null,r=s.documentTarget!==void 0?s.documentTarget:typeof document<"u"?document:null,n=!1,o,i=()=>{if(n)return;let f=e();if(!(o!==void 0&&f-o<15e3)){o=f;try{s.awareness.setLocalStateField(it,{at:f})}catch{}}},a=()=>{if(!(n||!r||r.visibilityState===void 0))try{s.awareness.setLocalStateField(ot,r.visibilityState)}catch{}},c=()=>i(),p=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&i()};if(t)for(let f of Te)t.addEventListener(f,c,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",p);let d=null;return s.isProducing&&(d=setInterval(()=>{if(!n)try{s.isProducing?.()&&i()}catch{}},15e3),d.unref?.()),i(),a(),{touch:i,dispose(){if(!n){if(n=!0,t)for(let f of Te)t.removeEventListener(f,c,{capture:!0});r&&r.removeEventListener("visibilitychange",p),d&&(clearInterval(d),d=null)}}}}var Qt=250;function Re(s){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,s())};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 Ce(s){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,s())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}var at="video/mp4";function Ee(s,e={}){let t=e.timesliceMs??1e3,r=null,n=null,o=!1,i=(a,c,p)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let f=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(at)?at:void 0),l=new MediaStream([a]),g=new d(l,f?{mimeType:f}:void 0);r=g;let u=Promise.resolve();g.ondataavailable=w=>{let y=w.data;o||!y||y.size===0||(u=u.then(async()=>{let _=new Uint8Array(await y.arrayBuffer());o||c(_)}))},g.onstop=()=>{u.then(()=>{o||p()})},g.onerror=()=>{u.then(()=>{o||p()})},g.start(t)};return{start(a,c){if(r||o)return;let p=s.track();if(p){i(p,a,c);return}n=s.onTrack(d=>{!d||r||o||(n?.(),n=null,i(d,a,c))})},stop(){if(o)return;o=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Zt(s){let e=s;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=s.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 ct(s,e){let t=null,r=!1,n=!1,o=new ReadableStream({pull(i){r||(r=!0,t=s(e),t.start(a=>{if(!n)try{i.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{i.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Zt(o)}import{encode as er,decode as tr}from"@msgpack/msgpack";var dt=65536;function Pe(s){let e=er(s),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var j=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>dt)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let n=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(tr(n))}return t}},$=12,Ie=1;function Me(s){let e=s.getUint8(8);return{groupId:s.getUint32(0,!0),frameSeq:s.getUint32(4,!0),keyframe:(e&Ie)===Ie,fragIndex:s.getUint8(9),fragCount:s.getUint8(10)}}function rr(s){let e=new Uint8Array($),t=new DataView(e.buffer);return t.setUint32(0,s.groupId,!0),t.setUint32(4,s.frameSeq,!0),t.setUint8(8,s.keyframe?Ie:0),t.setUint8(9,s.fragIndex),t.setUint8(10,s.fragCount),t.setUint8(11,0),e}var nr=100,H=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??nr}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<$)return;let t=Me(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,t.groupId<this.newestGroupSeen||(t.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t.groupId,this.needKeyframe=!0),t.frameSeq<=this.newestFrameDelivered))return;let r=this.pending.get(t.frameSeq);if(r||(r={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r)),!r.chunks[t.fragIndex]){r.chunks[t.fragIndex]=e.subarray($),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let n of this.pending.keys())n<t.frameSeq-1&&(this.pending.delete(n),this.framesAbandoned++)}}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let r=t.chunks.reduce((i,a)=>i+a.byteLength,0),n=new Uint8Array(r),o=0;for(let i of t.chunks)n.set(i,o),o+=i.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:n})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var sr=/^avc[13]\.[0-9a-fA-F]{6}$/;function ir(s){return sr.test(s)?null:`codec ${JSON.stringify(s)} 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 xe(s,e){let t=ir(s);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var or=250,ar=3,cr=1e4,Oe=2500,B=class{constructor(e,t,r){this.offer=e;this.sessionId=t;this.canvas=r;this.firstMedia=new Promise((n,o)=>{this.firstFrameResolve=n,this.firstFrameReject=o}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorsAt=[];writer;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;reassembler=new H({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};firstFrameResolve=null;firstFrameReject=null;firstFrameOutput=!1;firstDecodeTimer=null;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");xe(this.offer.codec,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(a=>({algorithm:"sha-256",value:Uint8Array.from(atob(a),c=>c.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let t=await this.wt.createBidirectionalStream();this.writer=t.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let r=t.readable.getReader(),n=new j,o=[],i=await this.readControl(r,n,o);if(i?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");xe(i.codec,"hello-ack"),this.initDecoder(i.codec,i.width,i.height),this.controlLoop(r,n,o).catch(a=>this.die(`control loop: ${a}`)),this.datagramLoop().catch(a=>this.die(`datagram loop: ${a}`)),this.feedbackLoop(),this.wt.closed.then(()=>this.die("connection closed")).catch(a=>this.die(`connection error: ${a}`))}async stop(){this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}onDead(e){this.deadCb=e}stats(){return this.lastStats}initDecoder(e,t,r){let n=globalThis.VideoDecoder;if(typeof n!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let o=this.canvas.getContext("2d");if(!o)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r},this.decoder=new n({output:i=>{this.firstFrameOutput=!0,this.firstDecodeTimer&&(clearTimeout(this.firstDecodeTimer),this.firstDecodeTimer=null),this.canvas.width=i.displayWidth,this.canvas.height=i.displayHeight,o.drawImage(i,0,0),i.close()},error:i=>this.onDecoderError(i)}),this.decoder.configure({codec:e,...t>0&&r>0?{codedWidth:t,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"})}onDecoderError(e){if(this.stopped||this.deadFired)return;let t=performance.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(n=>t-n<cr),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=ar){this.die(`decoder: ${e.message}`);return}console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=this.decoderConfig;if(!r){this.die(`decoder: ${e.message} (no config to re-init from)`);return}try{this.initDecoder(r.codec,r.width,r.height)}catch(n){this.die(`decoder re-init: ${n instanceof Error?n.message:String(n)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}armFirstDecodeDeadline(){if(this.firstDecodeTimer||this.firstFrameOutput||this.stopped||this.deadFired)return;let e=setTimeout(()=>{this.firstDecodeTimer=null,!(this.firstFrameOutput||this.stopped||this.deadFired)&&(console.error(`[urun] webtransport: media datagrams arriving but NO frame decoded within ${Oe}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${Oe}ms`))},Oe);e.unref?.(),this.firstDecodeTimer=e}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:r}=await e.read();if(r)break;if(!t)continue;this.armFirstDecodeDeadline();let n=performance.now();if(this.lastArrivalTs>0){let o=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(o-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=n,this.reassembler.push(t)}}decodeFrame(e,t,r){let n=globalThis.EncodedVideoChunk;!this.decoder||typeof n!="function"||(this.decoder.decode(new n({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}async sendControl(e){await this.writer.write(Pe(e))}async readControl(e,t,r=[]){for(;;){let n=r.shift();if(n)return n;let{value:o,done:i}=await e.read();if(i)return null;o&&r.push(...t.push(o))}}async controlLoop(e,t,r){for(;!this.stopped;){let n=await this.readControl(e,t,r);if(!n)break;n.t==="ping"&&this.sendControl({t:"pong",ts:n.ts}).catch(()=>{})}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),r=(t-e)/1e3;e=t;let n=this.reassembler.drainWindow(),o=n.delivered+n.abandoned;this.lastStats={recvBps:r>0?n.bytes*8/r:0,lossPct:o>0?100*n.abandoned/o:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},or)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var dr=2500,ur=["av01.0.08M.08","avc1.42E01F","avc1.640028"],V=class{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;get activeTransport(){return this.session?.kind??null}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,o={webtransport:t&&r&&n,webcodecs:r,codecs:ur};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:o});let i=o.webtransport&&!!this.offer.webtransport;if(o.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),i){let a=null;try{return a=this.createWebTransportSession(),await lr(a.start(),this.opts.quicDeadlineMs??dr,"quic connect deadline"),this.session=a,this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(c){console.warn("[urun] webtransport failed, falling back to webrtc:",c),a?.stop().catch(()=>{}),this.notifyEstablished("webrtc",String(c instanceof Error?c.message:c))}}return this.session=await this.startWebRtc(),i||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){await this.session?.stop(),this.session=null}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new B(e,this.sessionId,this.opts.canvas)}async startWebRtc(){let e=this.opts.createWebRtcSession();return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}armFailover(){let e=this.session;e.onDead(t=>{console.warn("[urun] quic died mid-session, failing over to webrtc:",t),e.stop().catch(()=>{}),(async()=>{try{this.session=await this.startWebRtc(),this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(r){this.session=null,console.error("[urun] failover to webrtc also failed:",r)}})()})}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function lr(s,e,t){return new Promise((r,n)=>{let o=setTimeout(()=>n(new Error(t)),e);s.then(i=>{clearTimeout(o),r(i)},i=>{clearTimeout(o),n(i)})})}var pr=1e4,K=class{constructor(e,t=pr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=te();return new Promise((n,o)=>{let i=setTimeout(()=>{a(),o(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(i),a(),c.error){o(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:p,requestId:d,...f}=c;n(f)});this.carrier.sendSignal({type:e,requestId:r,...t})})}notify(e,t){this.carrier.sendSignal({type:e,...t})}on(e,t){return this.carrier.onSignal(r=>{r.type===e&&t(r)})}};var fr="video",G=class{constructor(e,t=fr){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,n)=>{this.firstMediaResolve=r,this.firstMediaReject=n}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};var mr="video";function ut(s,e,t){let r=globalThis,n=r.document;if(!(typeof n?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let i=n.createElement("canvas"),a=!1,c=null,p=!1,d=()=>{if(c){for(let u of c.getVideoTracks())try{u.stop()}catch{}c=null}p&&(p=!1,t.onOverrideTrack(null))},f=new V(new K(s),e,{canvas:i,createWebRtcSession:t.createWebRtcSession??(()=>new G(s,t.streamName??mr)),createWebTransportSession:t.createWebTransportSession,onTransportChange:(u,w)=>{u==="webrtc"&&d(),t.onTransportChange?.(u,w)}}),l=null,g=()=>{l!==null&&(clearTimeout(l),l=null)};return(async()=>{let u=await f.connect();if(a||u.kind!=="webtransport")return;let w=t.firstMediaWarnMs??1e4;if(l=setTimeout(()=>{a||f.activeTransport!=="webtransport"||console.warn(`[urun] webtransport established but no QUIC media after ${w}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)},w),await u.firstMedia,g(),a||f.activeTransport!=="webtransport"||typeof i.captureStream!="function")return;c=i.captureStream();let y=c.getVideoTracks()[0];y&&(p=!0,t.onOverrideTrack(y))})().catch(u=>{g(),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",u)}),{activeTransport:()=>f.activeTransport,dispose(){a=!0,g(),d(),f.disconnect().catch(()=>{})}}}var hr=new Set;function Le(s){if(s.functionsUrl)return{functionsUrl:s.functionsUrl,orgId:s.orgId,apiKey:s.apiKey,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}var gr="rpc",pt=3e4,vr="rpc-resp";function wr(s){return`${vr}:${s}`}function De(){return te()}function yr(s){if(s&&typeof s=="object"){let e=s.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof s=="string"?s:JSON.stringify(s)}}function br(s,e,t,r,n,o,i,a,c,p){let d=[],f=null,l=!1,g=null,u=!1,w,y,_=new Promise((m,E)=>{w=m,y=E});_.catch(()=>{});let T=i(),k=null,A=null,h=null,v=null,C=!0,M=()=>{h&&(clearTimeout(h),h=null),v&&(v(),v=null)},We=!1,je=()=>{We||!u||(We=!0,s.set({rpc:{[e]:null}}))},Y=()=>{C=!1,M(),k?.(),k=null,A?.(),A=null,a?.removeEventListener("abort",He),T.dispose(),je()},pe=()=>{if(f){if(d.length>0){let m=f;f=null,m.resolve({value:d.shift(),done:!1})}else if(g!==null){let m=f;f=null,m.reject(g)}else if(l){let m=f;f=null,m.resolve({value:void 0,done:!0})}}},_t=m=>{l||(d.push(m),pe())},x=m=>{l||(g=m,l=!0,y(m),Y(),pe())},$e=m=>{l||(l=!0,w(m),Y(),pe())},He=()=>{let m=a?.reason;x(m instanceof X?m:new Q(e))},St=m=>{if(!(l||!m||typeof m!="object"))switch(je(),m.t){case"delta":typeof m.delta=="string"&&_t(m.delta);break;case"response":$e(m.body);break;case"error":{let{message:E,code:O}=yr(m.body);x(new X(E,{requestId:e,code:m.code??O}));break}}},kt=()=>{let m=T.messages()[Symbol.asyncIterator]();k=()=>{m.return?.(void 0)};let E=()=>{C&&m.next().then(O=>{if(C){if(O.done){l||$e(void 0);return}St(O.value),E()}},O=>{C&&x(O)})};E()},Be=()=>{if(!u){if(u=!0,a){if(a.aborted){x(new Q(e));return}a.addEventListener("abort",He,{once:!0})}A=c?.(m=>x(m))??null,kt(),s.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:o}}}),p&&p>0&&!s.synced&&(h=setTimeout(()=>{h=null,!l&&!s.synced&&x(new me(p,e))},p),v=s.onSynced(()=>M()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Be(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(g!==null){let m=g;return g=null,Promise.reject(m)}return l?Promise.resolve({value:void 0,done:!0}):new Promise((m,E)=>{f={resolve:m,reject:E}})},return(){return l||(l=!0,w(void 0),Y()),Promise.resolve({value:void 0,done:!0})},throw(m){return l||(l=!0,y(m),Y()),Promise.reject(m)}}}},body:_,start:Be}}function lt(s){if(s&&typeof s=="object"){let{epoch:e,by:t}=s,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function _r(s,e){let r=s.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:n,rt:o,br:i}=r,a={};(n==="audio"||n==="video"||n==="data")&&(a.kind=n);let c=lt(o);c&&(a.rt=c);let p=lt(i);return p&&(a.br=p),a}var Ue=class{constructor(e,t,r,n,o){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=n;this._onActivity=o;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,n=!1,o={push(a){if(!n)if(r){let c=r;r=null,c({value:a,done:!1})}else t.push(a)},end(){if(n=!0,r){let a=r;r=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(o);let i=()=>{n=!0,e._messageConsumers.delete(o)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):n?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{r=a})},return(){return i(),Promise.resolve({value:void 0,done:!0})}}}}}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let n of r)n(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=_r(t,this._name),n=r?.br;if(n?.by==="runtime")throw new he(this._name,"runtime","browser");if(n)return;let o={br:{epoch:1}};r?.rt&&(o.rt=r.rt);let i=r?.kind??e;i&&(o.kind=i),t.set({streams:{[this._name]:o}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??Ee;return ct(t,{track:()=>this.track,onTrack:n=>this.on("track",n)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},z=class s{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Ze;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_dialNegotiationStarted=!1;constructor(e,t,r,n,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=n,this._artifactsAuth=o,this._streamData=Je(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Re(()=>this.recover()),this._activity=Ae({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new N({onPhase:i=>this.onPhase(i),hint:()=>this.doc(be).get(_e)??this.doc("control").get(Se),onData:(i,a)=>this._streamData.onData(i,a)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await Ye({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),n=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,o=new J,i=new re({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new s(e,o,i,Le(t),q({...t,baseUrl:r.baseUrl}));return i.on("connected",()=>{i.multiplexer&&o.setTarget(i.multiplexer)}),i.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),i.setEndsAt(r.endsAt),Z()&&await ee(),a.setDocTransport({wsUrl:r.wsUrl,token:n}),await i.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}whenLive(e){return we(this,e)}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new L(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,n)=>t.retain(r,n),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new I(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new I(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}setEndHandler(e){this._endHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new Ue(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._activity?.touch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new et(e,this._sessionId,hr.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=tt(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=Xe(e.wsUrl),r=`${t}\0${e.token??""}\0${this._sessionId}`;r!==this._docEndpointKey&&(this._docEndpointKey=r,this.connectDocs(Qe({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let r=De(),n=new AbortController;t.signal&&(t.signal.aborted?n.abort(t.signal.reason):t.signal.addEventListener("abort",()=>n.abort(t.signal.reason),{once:!0}));let o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;o=setTimeout(()=>n.abort(new fe(a,r)),a)}let i=this._consumeResponse(r,e,!1,n.signal);return i.start(),i.body.finally(()=>{o&&clearTimeout(o)})}_consumeResponse(e,t,r,n,o){this._activity?.touch();let i=this.doc(gr),a=wr(e);return br(i,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??pt)}requestStream(e,t={}){let r=De();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=De(),n=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return n.start(),n.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=ut(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t)}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.disconnect(),e)),this._endPromise):Promise.reject(new F)}disconnect(){let e=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let r of e)try{r()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._activation.dispose(),this._recoveryHooks.clear();let t=Array.from(this._activeRequests);this._activeRequests.clear();for(let r of t)try{r(new ge)}catch{}for(let r of this._docs.values())r.dispose();this._docs.clear();for(let r of this._streams.values())r.dispose();this._streams.clear(),this._transport.disconnect()}};function ft(s){return`urun:logical:v1:${s.orgId}:${s.app}:${s.functionName}`}function Fe(){try{return globalThis.sessionStorage??null}catch{return null}}function mt(s){let e=Fe();if(!e)return null;try{let t=e.getItem(s);if(!t)return null;let r=JSON.parse(t);return typeof r?.logicalId!="string"||r.logicalId.length===0?null:{logicalId:r.logicalId}}catch{return null}}function ht(s,e){let t=Fe();if(t)try{t.setItem(s,JSON.stringify({logicalId:e.logicalId}))}catch{}}function de(s){let e=Fe();if(e)try{e.removeItem(s)}catch{}}var Sr=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function kr(s,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(t,r){if(!(Sr.has(r)||typeof r!="string"))return n=>{let o=n??{},i=ft({orgId:e.orgId,app:s,functionName:r}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,c=a(),p=e.jwt,d=e.getAccessToken?async h=>{let v=await e.getAccessToken(h);return v&&(p=v),v}:void 0,f={...e,getAccessToken:d},l=new J,g=new re({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c}),u=new z(c,l,g,Le(f),q(f)),w,y,_=new Promise(h=>{y=h}),T=h=>{w=h,y({status:"ready",handle:h})};u.setEndHandler(async()=>{let h=w?{status:"ready",handle:w}:await _;if(h.status==="unavailable")throw new F("[urun] session allocation failed before a releasable request was created",{cause:h.cause});let v=h.handle;return de(i),Ge({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider})});let k=async h=>{let v=await ze({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:s,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider,idempotencyKey:h,sessionKey:e.sessionKey??mt(i)?.logicalId,priority:e.priority,onAdmission:M=>g.reportAdmission(M),onRequest:T}),C=d?await d()??void 0:e.jwt;return e.sessionKey||ht(i,{logicalId:v.sessionId}),u.setSessionId(v.sessionId),u.setArtifactsAuth(q({...f,baseUrl:v.baseUrl})),g.setEndsAt(v.endsAt),{url:v.wsUrl,sessionId:v.sessionId,jwt:C,iceServers:v.response.ice_servers,endsAt:v.endsAt}},A;if(g.setConnectionResolver(async()=>{let h=await k(a());return A=h.jwt,h}),g.on("connected",()=>{g.multiplexer&&l.setTarget(g.multiplexer);let h=g.connectedUrl;h&&u.setDocTransport({wsUrl:h,token:A})}),(async()=>{let h;try{h=await k(c)}catch(v){console.error(`[urun] Failed to create session for ${r}:`,v),de(i);let C=v instanceof Error?v:new Error(String(v)),M=v instanceof ve?v.httpStatus:void 0;g.reportAllocationFailure(C,M),y({status:"unavailable",cause:v});return}g.setAuth({jwt:h.jwt,authProvider:e.authProvider,orgId:e.orgId}),g.setConnection({url:h.url,sessionId:h.sessionId,iceServers:h.iceServers}),Z()&&await ee(),A=h.jwt,u.setDocTransport({wsUrl:h.url,token:h.jwt}),await g.connect({app:s,functionName:r,args:o}),u.negotiateMediaTransport({allowWebTransport:e.allowWebTransport})})().catch(h=>{console.error(`[urun] Failed to connect session for ${r}:`,h)}),e.releaseOnLeave!==!1){let h=Ce(()=>{let v=w;v&&(de(i),ye({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider}))});u.onDisconnect(h)}return u}}})}var gt="https://api.urun.sh",P=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Tr(s,e={}){if(!s)throw new P("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=D(e.baseUrl??gt),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata);let o;try{o=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(n)})}catch(l){throw new P(`[urun] client token mint request failed: ${l instanceof Error?l.message:String(l)}`)}let i={};try{i=await o.json()}catch{}if(!o.ok){let l=typeof i.message=="string"?i.message:`HTTP ${o.status}`;throw new P(`[urun] client token mint failed: ${l}`,o.status)}let a=typeof i.token=="string"?i.token:"",c=typeof i.org_id=="string"?i.org_id:"",p=typeof i.expires_at=="string"?Date.parse(i.expires_at):Number.NaN,d=typeof i.expires_in=="number"?i.expires_in:void 0;if(!a)throw new P("[urun] client token mint returned no token (control-plane contract violation)",o.status);let f=Number.isFinite(p)?new Date(p):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:f,orgId:c}}var vt=3e4,wt="stream:",Ne=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let n;try{n=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(n.rpcId&&this._pendingRpc.has(n.rpcId)){let o=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(o.timer),n.error?o.reject(new Error(n.error)):o.resolve(n.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${wt}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${wt}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let o=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),n(new Error(`RPC request "${e}" timed out after ${vt}ms`)))},vt);this._pendingRpc.set(o,{resolve:r,reject:n,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Ar(s){let r=`${s.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(s.orgId)}`,n=new WebSocket(r);(s.jwt||s.apiKey)&&n.addEventListener("open",()=>{n.send(JSON.stringify({type:"auth",orgId:s.orgId,jwt:s.jwt,authProvider:s.authProvider,apiKey:s.apiKey}))});let o=new Ve(n);return new Ne(n,o)}var Rr='video/mp4; codecs="avc1.42E01E"';function Cr(s,e){let t=e?.codec??Rr,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,o=URL.createObjectURL(n);r.src=o,n.addEventListener("sourceopen",()=>{let l;try{l=n.addSourceBuffer(t)}catch(y){throw y instanceof DOMException&&y.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):y}let g=s.getReader();function u(){return l.updating?new Promise(y=>{l.addEventListener("updateend",()=>y(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:y,value:_}=await g.read();if(y){await u(),n.readyState==="open"&&n.endOfStream();return}await u();try{l.appendBuffer(_)}catch(T){if(T instanceof DOMException&&T.name==="QuotaExceededError"){let k=l.buffered;if(k.length>0){let A=k.start(k.length-1);l.remove(0,A),await u(),l.appendBuffer(_)}else throw T}else throw T}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}w()}),r.play().catch(()=>{});let i=r,a=i.captureStream??i.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),p=c.getTracks(),d=0,f=p.length;if(f===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let l of p)l.addEventListener("ended",()=>{d++,d>=f&&URL.revokeObjectURL(o)});return c}function Er(s){return s.status.startsWith("pending_")}var ue=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function yt(s){let e=[];return s.audio&&e.push("audio"),s.video&&e.push("video"),e.join("+")}function Ir(s,e){return e==="audio"?s.getAudioTracks():s.getVideoTracks()}function Pr(s,e){let t=s.getTracks();if(t.length===1&&t[0]===e)return s;try{return new MediaStream([e])}catch{return s}}function qe(s,e){for(let t of[...s.lostListeners])try{t(e)}catch{}}var le=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let r=this.claims.get(e);r&&(this.claims.delete(e),r.released=!0,r.track=null,r.stream=null,qe(r,new Error(`${e} capture claim superseded by a newer claim`)));let n=this.createState(e,t);return this.claims.set(e,n),await this.converge(n),n.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new ue;return t=>e.getUserMedia(t)}async converge(e){for(let i of this.claims.values())i.track&&(i.track.stop(),i.track=null,i.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},n;try{n=await t(r)}catch(i){let a=`one-capture getUserMedia(${yt(r)}) failed`,c=i instanceof Error?i.message:String(i);for(let p of[...this.claims.values()])if(this.claims.delete(p.kind),p.released=!0,p!==e){let d=new Error(`${a} \u2014 ${p.kind} capture lost: ${c||i}`);d.cause=i,qe(p,d)}throw i}let o=[...this.claims.values()].sort((i,a)=>i===e?1:a===e?-1:0);for(let i of o){let a=Ir(n,i.kind)[0]??null;if(i.released){a?.stop();continue}if(!a){this.claims.delete(i.kind),i.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${yt(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===e)throw c;qe(i,c);continue}if(i.track=a,i.stream=Pr(n,a),i!==e)for(let c of[...i.trackListeners])try{c(a,i.stream)}catch{}}}createState(e,t){let r=this,n={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return n.track},get stream(){return n.stream},update(o){return r.enqueue(async()=>{if(n.released)throw new Error(`${e} capture claim already released`);if(n.constraints=o,await r.converge(n),!n.track)throw new Error(`${e} capture update yielded no track`);return n.track})},release(){n.released||(n.released=!0,r.claims.get(e)===n&&r.claims.delete(e),n.track?.stop(),n.track=null,n.stream=null)},onTrack(o){return n.trackListeners.add(o),()=>n.trackListeners.delete(o)},onLost(o){return n.lostListeners.add(o),()=>n.lostListeners.delete(o)}}};return n}},Mr=null;function xr(){return Mr??=new le}var bt="input",Or=30;function Dr(s){let e=s.now??Date.now,t=s.field??bt,r=1e3/Math.max(s.hz??30,.001),n=new Set,o=0,i=0,a=0,c=0,p,d=null,f=!1,l=()=>{if(f)return;p=e(),c+=1;let u={keys:[...n],buttons:o,pointer:{x:i,y:a},seq:c,at:p};try{s.awareness.setLocalStateField(t,u)}catch{}},g=()=>{if(f)return;let u=e();if(p===void 0||u-p>=r){d&&(clearTimeout(d),d=null),l();return}if(d)return;let w=Math.max(r-(u-p),0);d=setTimeout(()=>{d=null,l()},w),d.unref?.()};return{keyDown(u){let w=String(u).toLowerCase();n.has(w)||(n.add(w),g())},keyUp(u){let w=String(u).toLowerCase();n.delete(w)&&g()},setButtons(u){let w=Number.isFinite(u)?Number(u):0;w!==o&&(o=w,g())},movePointer(u,w){let y=Number.isFinite(u)?Number(u):0,_=Number.isFinite(w)?Number(w):0;y===0&&_===0||(i+=y,a+=_,g())},heldKeys(){return[...n]},clear(){f||(n.clear(),o=0,d&&(clearTimeout(d),d=null),l())},dispose(){if(f)return;let u=n.size>0||o!==0;n.clear(),o=0,d&&(clearTimeout(d),d=null),u&&l(),f=!0}}}export{Wt as ACTIVATION_COLD_BOOT_AFTER_MS,jt as ACTIVATION_DEGRADED_AFTER_MS,_e as ACTIVATION_HINT_PATH,qt as ACTIVATION_STILL_AFTER_MS,Te as ACTIVITY_DOM_EVENTS,it as ACTIVITY_FIELD,Xt as ACTIVITY_STAMP_MIN_INTERVAL_MS,N as ActivationMonitor,kr as App,Ot as BACKOFF_BASE_MS,Ut as BACKOFF_MAX_ATTEMPTS,Dt as BACKOFF_MAX_MS,le as CaptureController,ue as CaptureUnavailableError,P as ClientTokenError,pt as DEFAULT_DOC_SYNC_TIMEOUT_MS,gt as DEFAULT_GATEWAY_URL,At as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Mt as DEFAULT_WHEN_LIVE_TIMEOUT_MS,$ as DGRAM_HEADER_BYTES,Qt as FOREGROUND_COALESCE_MS,H as FrameReassembler,Or as INPUT_PRESENCE_DEFAULT_HZ,bt as INPUT_PRESENCE_FIELD,U as InvalidDurationError,Se as LEGACY_ACTIVATION_HINT_PATH,be as PLATFORM_DOC_NAME,ce as PermanentLockedError,ae as PinRequiresActiveTempError,Rt as ProduceAckTimeoutError,ie as RecordingNotFoundError,L as RecordingsClient,S as RecordingsError,W as RecordingsUnauthorizedError,Q as RequestAbortError,ge as RequestCancelledError,me as RequestDocSyncError,X as RequestError,fe as RequestTimeoutError,oe as RetainNotTempError,se as RuntimeArtifactNotFoundError,I as RuntimeArtifactsClient,b as RuntimeArtifactsError,ne as RuntimeArtifactsUnauthorizedError,z as Session,ve as SessionAllocationError,Tt as SessionEndError,F as SessionEndUnavailableError,Et as SessionFailedError,he as StreamDirectionConflict,V as TransportNegotiator,K as TransportSessionSignaling,ot as VISIBILITY_FIELD,dt as WT_CONTROL_FRAME_MAX,G as WebRtcSession,B as WebTransportSession,j as WtControlDecoder,rt as activationHintFrom,Lt as computeBackoffDelay,Ae as createActivityTracker,Tr as createClientToken,Dr as createInputPresencePublisher,Jt as createRecordingsClient,Ht as createRuntimeArtifactsClient,Ar as createStore,Ct as describeSessionFailure,xt as describeSessionPhase,Pe as encodeWtControlFrame,ke as isDurationString,Er as isPendingRecording,Ft as isRetryableSessionError,Pt as isWakingPhase,Ee as mediaRecorderChunkSource,zt as normalizeRetention,Re as observePageLifecycle,Ce as observePageTeardown,Me as parseDgramHeader,Nt as prewake,ye as releaseSessionBeacon,It as sessionFailureFromMediaError,xr as sharedCaptureController,Cr as videoStream,we as whenLive,rr as writeDgramHeader};
|
|
2
|
+
import{A as Ke,B as ye,C as Ge,D as ze,E as Ye,F as jt,G as Z,I as ee,J as te,L as Je,N as re,P as Xe,Q as Qe,R as Ze,S as et,T as tt,a as Ve,b as J,c as F,d as Ct,e as X,f as fe,g as me,h as he,i as Et,j as It,k as Q,l as ge,m as Pt,n as Mt,o as xt,p as ve,q as Ot,r as Dt,s as we,t as Ut,u as Lt,v as Ft,w as Nt,x as qt,y as Wt,z as D}from"./chunk-TQBKKR7C.mjs";var $t=15e3,Ht=45e3,Bt=12e4,be="platform",_e="activation",Se="desired.activation";function rt(s){if(typeof s=="string"&&s.length>0)return s;if(s&&typeof s=="object"){let e=s.note;if(typeof e=="string"&&e.length>0)return e}}var Vt=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],N=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(t?.name==="error"||t?.name==="ended"||t?.name==="expired")&&this.dispose()}),this._stopped&&(this._offPhase(),this._offPhase=null)}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;watch(e,t){if(this._stopped||this._watches.has(e))return;let r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let n=()=>this._firstMedia(e);r.addEventListener("unmute",n,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",n));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of Vt){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let n={state:t,elapsedMs:r,stream:e.name},o=rt(this._options.hint());o!==void 0&&(n.hint=o),e.lastEvent=n;for(let i of Array.from(this._handlers))i(n)}};var S=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)}},ne=class extends S{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},se=class extends S{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function q(s){return{baseUrl:s.baseUrl,fallbackUrls:s.fallbackUrls,orgId:s.orgId,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}function Kt(s){return new I(s)}var I=class{_options;constructor(e){this._options=e}async list(e){let r=st(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new S("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(nt)}async getDownloadUrl(e,t){let r=st(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!zt(n))throw new S("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:nt(r.artifact),downloadUrl:n}}async _request(e,t){let r=Ke(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let o of r)try{return await this._requestFromBase(o,e,t)}catch(i){if(n=i instanceof Error?i:new Error(String(i)),n instanceof S&&Yt(n.status))throw n}throw n??new S("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${D(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,o=await this._resolveToken(),i=await fetch(n,{method:"GET",headers:this._headers(o)});if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await fetch(n,{method:"GET",headers:this._headers(o)}))}if(!i.ok){let{code:a,message:c}=await this._readError(i,e);throw Jt(i.status,a,c)}try{return await i.json()}catch(a){throw new S(`[urun] runtime artifacts: invalid JSON response from ${D(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=D(t);try{let o=(await e.json()).error;if(o&&typeof o=="object"){let{code:i,message:a}=o;return{code:typeof i=="string"&&i.length>0?i:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${r}: ${a}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}};function nt(s){if(!s||typeof s!="object")throw new S("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=s,t=C(e,"artifact_id")||C(e,"id"),r=C(e,"filename"),n=C(e,"kind"),o=C(e,"status")||"ready",i=Gt(e,"size_bytes"),a=C(e,"sha256");if(!t||!r||!n||i==null||!a)throw new S("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:C(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:C(e,"created_at"),expiresAt:C(e,"expires_at")}}function C(s,e){let t=s[e];return typeof t=="string"&&t.length>0?t:void 0}function Gt(s,e){let t=s[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function zt(s){try{return new URL(s).protocol==="https:"}catch{return!1}}function Yt(s){return s===401||s===403}function Jt(s,e,t){return s===401?new ne(t,e):s===404?new se(t,e):new S(t,s,e)}function st(s){if(!s||typeof s!="object"||Array.isArray(s))throw new S("[urun] runtime artifacts: malformed response",0,"bad_response");return s}var A=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)}},W=class extends A{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 A{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 A{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)}},ae=class extends A{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},ce=class extends A{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},U=class extends A{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 ke(s){return/^(\d+[smhdw])+$/.test(s)}function Xt(s){if(s==="pin")return{action:"pin"};if(ke(s))return{action:"retain",duration:s};throw new U(`[urun] recordings: "${s}" is not a duration or "pin"`)}function Qt(s,e,t){let r=t||e||`HTTP ${s}`;if(s===401)return new W(r,e??"unauthorized");if(s===404)return new ie(r,e??"not_found");if(s===400)return new U(r,e??"bad_request",400);if(s===409)switch(e){case"retain_not_temp":return new oe(r,e);case"pin_requires_active_temp":return new ae(r,e);case"permanent_locked":return new ce(r,e)}return new A(r,{status:s,code:e??`http_${s}`})}var L=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(!ke(t))throw new U(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new A("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),o=await this._resolveToken(),i=await this._fetch(n,e,o,r.body);if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await this._fetch(n,e,o,r.body))}if(!i.ok){let{code:a,message:c}=await this._readError(i);throw Qt(i.status,a,c)}return this._readJson(i)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,i])=>`${encodeURIComponent(o)}=${encodeURIComponent(i)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let o={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(o["X-Auth-Provider"]=this._options.authProvider);let i={method:t,headers:o};return n!==void 0&&(o["Content-Type"]="application/json",i.body=JSON.stringify(n)),fetch(e,i)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new W("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:n,message:o}=r;return{code:typeof n=="string"?n:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Zt(s){return new L(s)}var it="activity",ot="visibility",er=15e3,Te=["pointerdown","pointermove","keydown","wheel","touchstart"];function Re(s){let e=s.now??Date.now,t=s.windowTarget!==void 0?s.windowTarget:typeof window<"u"?window:null,r=s.documentTarget!==void 0?s.documentTarget:typeof document<"u"?document:null,n=!1,o,i=()=>{if(n)return;let p=e();if(!(o!==void 0&&p-o<15e3)){o=p;try{s.awareness.setLocalStateField(it,{at:p})}catch{}}},a=()=>{if(!(n||!r||r.visibilityState===void 0))try{s.awareness.setLocalStateField(ot,r.visibilityState)}catch{}},c=()=>i(),f=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&i()};if(t)for(let p of Te)t.addEventListener(p,c,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",f);let d=null;return s.isProducing&&(d=setInterval(()=>{if(!n)try{s.isProducing?.()&&i()}catch{}},15e3),d.unref?.()),i(),a(),{touch:i,dispose(){if(!n){if(n=!0,t)for(let p of Te)t.removeEventListener(p,c,{capture:!0});r&&r.removeEventListener("visibilitychange",f),d&&(clearInterval(d),d=null)}}}}var tr=250;function Ae(s){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,s())};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 Ce(s){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,s())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}var at="video/mp4";function Ee(s,e={}){let t=e.timesliceMs??1e3,r=null,n=null,o=!1,i=(a,c,f)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let p=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(at)?at:void 0),l=new MediaStream([a]),v=new d(l,p?{mimeType:p}:void 0);r=v;let h=Promise.resolve();v.ondataavailable=y=>{let w=y.data;o||!w||w.size===0||(h=h.then(async()=>{let b=new Uint8Array(await w.arrayBuffer());o||c(b)}))},v.onstop=()=>{h.then(()=>{o||f()})},v.onerror=()=>{h.then(()=>{o||f()})},v.start(t)};return{start(a,c){if(r||o)return;let f=s.track();if(f){i(f,a,c);return}n=s.onTrack(d=>{!d||r||o||(n?.(),n=null,i(d,a,c))})},stop(){if(o)return;o=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function rr(s){let e=s;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=s.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 ct(s,e){let t=null,r=!1,n=!1,o=new ReadableStream({pull(i){r||(r=!0,t=s(e),t.start(a=>{if(!n)try{i.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{i.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return rr(o)}import{encode as nr,decode as sr}from"@msgpack/msgpack";var dt=65536;function Pe(s){let e=nr(s),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var j=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>dt)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let n=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(sr(n))}return t}},$=12,Ie=1;function Me(s){let e=s.getUint8(8);return{groupId:s.getUint32(0,!0),frameSeq:s.getUint32(4,!0),keyframe:(e&Ie)===Ie,fragIndex:s.getUint8(9),fragCount:s.getUint8(10)}}function ir(s){let e=new Uint8Array($),t=new DataView(e.buffer);return t.setUint32(0,s.groupId,!0),t.setUint32(4,s.frameSeq,!0),t.setUint8(8,s.keyframe?Ie:0),t.setUint8(9,s.fragIndex),t.setUint8(10,s.fragCount),t.setUint8(11,0),e}var or=100,H=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??or}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<$)return;let t=Me(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,t.groupId<this.newestGroupSeen||(t.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t.groupId,this.needKeyframe=!0),t.frameSeq<=this.newestFrameDelivered))return;let r=this.pending.get(t.frameSeq);if(r||(r={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r)),!r.chunks[t.fragIndex]){r.chunks[t.fragIndex]=e.subarray($),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let n of this.pending.keys())n<t.frameSeq-1&&(this.pending.delete(n),this.framesAbandoned++)}}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let r=t.chunks.reduce((i,a)=>i+a.byteLength,0),n=new Uint8Array(r),o=0;for(let i of t.chunks)n.set(i,o),o+=i.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:n})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var ar=/^avc[13]\.[0-9a-fA-F]{6}$/;function cr(s){return ar.test(s)?null:`codec ${JSON.stringify(s)} 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 xe(s,e){let t=cr(s);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var dr=250,ur=3,lr=1e4,Oe=2500,B=class{constructor(e,t,r){this.offer=e;this.sessionId=t;this.canvas=r;this.firstMedia=new Promise((n,o)=>{this.firstFrameResolve=n,this.firstFrameReject=o}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorsAt=[];writer;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;reassembler=new H({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};firstFrameResolve=null;firstFrameReject=null;firstFrameOutput=!1;firstDecodeTimer=null;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");xe(this.offer.codec,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(a=>({algorithm:"sha-256",value:Uint8Array.from(atob(a),c=>c.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let t=await this.wt.createBidirectionalStream();this.writer=t.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let r=t.readable.getReader(),n=new j,o=[],i=await this.readControl(r,n,o);if(i?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");xe(i.codec,"hello-ack"),this.initDecoder(i.codec,i.width,i.height),this.controlLoop(r,n,o).catch(a=>this.die(`control loop: ${a}`)),this.datagramLoop().catch(a=>this.die(`datagram loop: ${a}`)),this.feedbackLoop(),this.wt.closed.then(()=>this.die("connection closed")).catch(a=>this.die(`connection error: ${a}`))}async stop(){this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}onDead(e){this.deadCb=e}stats(){return this.lastStats}initDecoder(e,t,r){let n=globalThis.VideoDecoder;if(typeof n!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let o=this.canvas.getContext("2d");if(!o)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r},this.decoder=new n({output:i=>{this.firstFrameOutput=!0,this.firstDecodeTimer&&(clearTimeout(this.firstDecodeTimer),this.firstDecodeTimer=null),this.canvas.width=i.displayWidth,this.canvas.height=i.displayHeight,o.drawImage(i,0,0),i.close()},error:i=>this.onDecoderError(i)}),this.decoder.configure({codec:e,...t>0&&r>0?{codedWidth:t,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"})}onDecoderError(e){if(this.stopped||this.deadFired)return;let t=performance.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(n=>t-n<lr),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=ur){this.die(`decoder: ${e.message}`);return}console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=this.decoderConfig;if(!r){this.die(`decoder: ${e.message} (no config to re-init from)`);return}try{this.initDecoder(r.codec,r.width,r.height)}catch(n){this.die(`decoder re-init: ${n instanceof Error?n.message:String(n)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}armFirstDecodeDeadline(){if(this.firstDecodeTimer||this.firstFrameOutput||this.stopped||this.deadFired)return;let e=setTimeout(()=>{this.firstDecodeTimer=null,!(this.firstFrameOutput||this.stopped||this.deadFired)&&(console.error(`[urun] webtransport: media datagrams arriving but NO frame decoded within ${Oe}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${Oe}ms`))},Oe);e.unref?.(),this.firstDecodeTimer=e}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:r}=await e.read();if(r)break;if(!t)continue;this.armFirstDecodeDeadline();let n=performance.now();if(this.lastArrivalTs>0){let o=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(o-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=n,this.reassembler.push(t)}}decodeFrame(e,t,r){let n=globalThis.EncodedVideoChunk;!this.decoder||typeof n!="function"||(this.decoder.decode(new n({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}async sendControl(e){await this.writer.write(Pe(e))}async readControl(e,t,r=[]){for(;;){let n=r.shift();if(n)return n;let{value:o,done:i}=await e.read();if(i)return null;o&&r.push(...t.push(o))}}async controlLoop(e,t,r){for(;!this.stopped;){let n=await this.readControl(e,t,r);if(!n)break;n.t==="ping"&&this.sendControl({t:"pong",ts:n.ts}).catch(()=>{})}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),r=(t-e)/1e3;e=t;let n=this.reassembler.drainWindow(),o=n.delivered+n.abandoned;this.lastStats={recvBps:r>0?n.bytes*8/r:0,lossPct:o>0?100*n.abandoned/o:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},dr)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var ut=2500,lt=["av01.0.08M.08","avc1.42E01F","avc1.640028"],V=class{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;get activeTransport(){return this.session?.kind??null}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,o={webtransport:t&&r&&n,webcodecs:r,codecs:lt};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:o});let i=o.webtransport&&!!this.offer.webtransport;if(o.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),i){let a=null;try{return a=this.createWebTransportSession(),await pt(a.start(),this.opts.quicDeadlineMs??ut,"quic connect deadline"),this.session=a,this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(c){console.warn("[urun] webtransport failed, falling back to webrtc:",c),a?.stop().catch(()=>{}),this.notifyEstablished("webrtc",String(c instanceof Error?c.message:c))}}return this.session=await this.startWebRtc(),i||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){await this.session?.stop(),this.session=null}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let r=this.session;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:lt}}),!this.offer.webtransport)return null;let n=this.createWebTransportSession();try{await pt(n.start(),this.opts.quicDeadlineMs??ut,"quic connect deadline")}catch(o){throw n.stop().catch(()=>{}),o}return this.session!==r?(n.stop().catch(()=>{}),null):(this.session=n,this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),n)}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new B(e,this.sessionId,this.opts.canvas)}async startWebRtc(){let e=this.opts.createWebRtcSession();return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}armFailover(){let e=this.session;e.onDead(t=>{console.warn("[urun] quic died mid-session, failing over to webrtc:",t),e.stop().catch(()=>{}),(async()=>{try{this.session=await this.startWebRtc(),this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(r){this.session=null,console.error("[urun] failover to webrtc also failed:",r)}})()})}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function pt(s,e,t){return new Promise((r,n)=>{let o=setTimeout(()=>n(new Error(t)),e);s.then(i=>{clearTimeout(o),r(i)},i=>{clearTimeout(o),n(i)})})}var pr=1e4,K=class{constructor(e,t=pr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=te();return new Promise((n,o)=>{let i=setTimeout(()=>{a(),o(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(i),a(),c.error){o(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:f,requestId:d,...p}=c;n(p)});this.carrier.sendSignal({type:e,requestId:r,...t})})}notify(e,t){this.carrier.sendSignal({type:e,...t})}on(e,t){return this.carrier.onSignal(r=>{r.type===e&&t(r)})}};var fr="video",G=class{constructor(e,t=fr){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,n)=>{this.firstMediaResolve=r,this.firstMediaReject=n}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};var mr="video";function ft(s,e,t){let r=globalThis,n=r.document;if(!(typeof n?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let i=n.createElement("canvas"),a=!1,c=null,f=!1,d=()=>{if(c){for(let u of c.getVideoTracks())try{u.stop()}catch{}c=null}f&&(f=!1,t.onOverrideTrack(null))},p=new V(new K(s),e,{canvas:i,createWebRtcSession:t.createWebRtcSession??(()=>new G(s,t.streamName??mr)),createWebTransportSession:t.createWebTransportSession,onTransportChange:(u,m)=>{u==="webrtc"&&(d(),_()),t.onTransportChange?.(u,m)}}),l=null,v=()=>{l!==null&&(clearTimeout(l),l=null)},h=t.wtRetryBaseMs??2e3,y=t.wtRetryCapMs??3e4,w=null,b=0,_=()=>{if(a||w!==null||p.activeTransport==="webtransport")return;let u=Math.min(h*2**b,y);w=setTimeout(()=>{w=null,b+=1,p.retryWebTransport().then(m=>{if(!a){if(m)return console.debug(`[urun] webtransport upgraded in background (retry ${b})`),b=0,T(m);_()}}).catch(m=>{a||(console.debug(`[urun] webtransport background retry ${b} failed:`,m),_())})},u)},k=()=>{w!==null&&(clearTimeout(w),w=null)},T=async u=>{if(a||u.kind!=="webtransport")return;let m=t.firstMediaWarnMs??1e4;if(v(),l=setTimeout(()=>{a||p.activeTransport!=="webtransport"||console.warn(`[urun] webtransport established but no QUIC media after ${m}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)},m),await u.firstMedia,v(),a||p.activeTransport!=="webtransport"||typeof i.captureStream!="function")return;c=i.captureStream();let R=c.getVideoTracks()[0];R&&(f=!0,t.onOverrideTrack(R))};return(async()=>{let u=await p.connect();await T(u)})().catch(u=>{v(),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",u),_()}),{activeTransport:()=>p.activeTransport,dispose(){a=!0,v(),k(),d(),p.disconnect().catch(()=>{})}}}var hr=new Set;function Le(s){if(s.functionsUrl)return{functionsUrl:s.functionsUrl,orgId:s.orgId,apiKey:s.apiKey,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}var gr="rpc",ht=3e4,vr="rpc-resp";function wr(s){return`${vr}:${s}`}function De(){return te()}function yr(s){if(s&&typeof s=="object"){let e=s.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof s=="string"?s:JSON.stringify(s)}}function br(s,e,t,r,n,o,i,a,c,f){let d=[],p=null,l=!1,v=null,h=!1,y,w,b=new Promise((g,E)=>{y=g,w=E});b.catch(()=>{});let _=i(),k=null,T=null,u=null,m=null,R=!0,M=()=>{u&&(clearTimeout(u),u=null),m&&(m(),m=null)},We=!1,je=()=>{We||!h||(We=!0,s.set({rpc:{[e]:null}}))},Y=()=>{R=!1,M(),k?.(),k=null,T?.(),T=null,a?.removeEventListener("abort",He),_.dispose(),je()},pe=()=>{if(p){if(d.length>0){let g=p;p=null,g.resolve({value:d.shift(),done:!1})}else if(v!==null){let g=p;p=null,g.reject(v)}else if(l){let g=p;p=null,g.resolve({value:void 0,done:!0})}}},Tt=g=>{l||(d.push(g),pe())},x=g=>{l||(v=g,l=!0,w(g),Y(),pe())},$e=g=>{l||(l=!0,y(g),Y(),pe())},He=()=>{let g=a?.reason;x(g instanceof X?g:new Q(e))},Rt=g=>{if(!(l||!g||typeof g!="object"))switch(je(),g.t){case"delta":typeof g.delta=="string"&&Tt(g.delta);break;case"response":$e(g.body);break;case"error":{let{message:E,code:O}=yr(g.body);x(new X(E,{requestId:e,code:g.code??O}));break}}},At=()=>{let g=_.messages()[Symbol.asyncIterator]();k=()=>{g.return?.(void 0)};let E=()=>{R&&g.next().then(O=>{if(R){if(O.done){l||$e(void 0);return}Rt(O.value),E()}},O=>{R&&x(O)})};E()},Be=()=>{if(!h){if(h=!0,a){if(a.aborted){x(new Q(e));return}a.addEventListener("abort",He,{once:!0})}T=c?.(g=>x(g))??null,At(),s.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:o}}}),f&&f>0&&!s.synced&&(u=setTimeout(()=>{u=null,!l&&!s.synced&&x(new me(f,e))},f),m=s.onSynced(()=>M()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Be(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(v!==null){let g=v;return v=null,Promise.reject(g)}return l?Promise.resolve({value:void 0,done:!0}):new Promise((g,E)=>{p={resolve:g,reject:E}})},return(){return l||(l=!0,y(void 0),Y()),Promise.resolve({value:void 0,done:!0})},throw(g){return l||(l=!0,w(g),Y()),Promise.reject(g)}}}},body:b,start:Be}}function mt(s){if(s&&typeof s=="object"){let{epoch:e,by:t}=s,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function _r(s,e){let r=s.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:n,rt:o,br:i}=r,a={};(n==="audio"||n==="video"||n==="data")&&(a.kind=n);let c=mt(o);c&&(a.rt=c);let f=mt(i);return f&&(a.br=f),a}var Ue=class{constructor(e,t,r,n,o){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=n;this._onActivity=o;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,n=!1,o={push(a){if(!n)if(r){let c=r;r=null,c({value:a,done:!1})}else t.push(a)},end(){if(n=!0,r){let a=r;r=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(o);let i=()=>{n=!0,e._messageConsumers.delete(o)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):n?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{r=a})},return(){return i(),Promise.resolve({value:void 0,done:!0})}}}}}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let n of r)n(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=_r(t,this._name),n=r?.br;if(n?.by==="runtime")throw new he(this._name,"runtime","browser");if(n)return;let o={br:{epoch:1}};r?.rt&&(o.rt=r.rt);let i=r?.kind??e;i&&(o.kind=i),t.set({streams:{[this._name]:o}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??Ee;return ct(t,{track:()=>this.track,onTrack:n=>this.on("track",n)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},z=class s{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Ze;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_dialNegotiationStarted=!1;constructor(e,t,r,n,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=n,this._artifactsAuth=o,this._streamData=Je(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Ae(()=>this.recover()),this._activity=Re({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new N({onPhase:i=>this.onPhase(i),hint:()=>this.doc(be).get(_e)??this.doc("control").get(Se),onData:(i,a)=>this._streamData.onData(i,a)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await Ye({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),n=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,o=new J,i=new re({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new s(e,o,i,Le(t),q({...t,baseUrl:r.baseUrl}));return i.on("connected",()=>{i.multiplexer&&o.setTarget(i.multiplexer)}),i.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),i.setEndsAt(r.endsAt),Z()&&await ee(),a.setDocTransport({wsUrl:r.wsUrl,token:n}),await i.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}whenLive(e){return we(this,e)}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new L(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,n)=>t.retain(r,n),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new I(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new I(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}setEndHandler(e){this._endHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new Ue(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._activity?.touch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new et(e,this._sessionId,hr.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=tt(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=Xe(e.wsUrl),r=`${t}\0${e.token??""}\0${this._sessionId}`;r!==this._docEndpointKey&&(this._docEndpointKey=r,this.connectDocs(Qe({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let r=De(),n=new AbortController;t.signal&&(t.signal.aborted?n.abort(t.signal.reason):t.signal.addEventListener("abort",()=>n.abort(t.signal.reason),{once:!0}));let o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;o=setTimeout(()=>n.abort(new fe(a,r)),a)}let i=this._consumeResponse(r,e,!1,n.signal);return i.start(),i.body.finally(()=>{o&&clearTimeout(o)})}_consumeResponse(e,t,r,n,o){this._activity?.touch();let i=this.doc(gr),a=wr(e);return br(i,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??ht)}requestStream(e,t={}){let r=De();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=De(),n=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return n.start(),n.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=ft(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t)}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.disconnect(),e)),this._endPromise):Promise.reject(new F)}disconnect(){let e=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let r of e)try{r()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._activation.dispose(),this._recoveryHooks.clear();let t=Array.from(this._activeRequests);this._activeRequests.clear();for(let r of t)try{r(new ge)}catch{}for(let r of this._docs.values())r.dispose();this._docs.clear();for(let r of this._streams.values())r.dispose();this._streams.clear(),this._transport.disconnect()}};function gt(s){return`urun:logical:v1:${s.orgId}:${s.app}:${s.functionName}`}function Fe(){try{return globalThis.sessionStorage??null}catch{return null}}function vt(s){let e=Fe();if(!e)return null;try{let t=e.getItem(s);if(!t)return null;let r=JSON.parse(t);return typeof r?.logicalId!="string"||r.logicalId.length===0?null:{logicalId:r.logicalId}}catch{return null}}function wt(s,e){let t=Fe();if(t)try{t.setItem(s,JSON.stringify({logicalId:e.logicalId}))}catch{}}function de(s){let e=Fe();if(e)try{e.removeItem(s)}catch{}}var Sr=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function kr(s,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(t,r){if(!(Sr.has(r)||typeof r!="string"))return n=>{let o=n??{},i=gt({orgId:e.orgId,app:s,functionName:r}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,c=a(),f=e.jwt,d=e.getAccessToken?async u=>{let m=await e.getAccessToken(u);return m&&(f=m),m}:void 0,p={...e,getAccessToken:d},l=new J,v=new re({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c}),h=new z(c,l,v,Le(p),q(p)),y,w,b=new Promise(u=>{w=u}),_=u=>{y=u,w({status:"ready",handle:u})};h.setEndHandler(async()=>{let u=y?{status:"ready",handle:y}:await b;if(u.status==="unavailable")throw new F("[urun] session allocation failed before a releasable request was created",{cause:u.cause});let m=u.handle;return de(i),Ge({baseUrl:m.baseUrl,requestId:m.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider})});let k=async u=>{let m=await ze({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:s,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider,idempotencyKey:u,sessionKey:e.sessionKey??vt(i)?.logicalId,priority:e.priority,onAdmission:M=>v.reportAdmission(M),onRequest:_}),R=d?await d()??void 0:e.jwt;return e.sessionKey||wt(i,{logicalId:m.sessionId}),h.setSessionId(m.sessionId),h.setArtifactsAuth(q({...p,baseUrl:m.baseUrl})),v.setEndsAt(m.endsAt),{url:m.wsUrl,sessionId:m.sessionId,jwt:R,iceServers:m.response.ice_servers,endsAt:m.endsAt}},T;if(v.setConnectionResolver(async()=>{let u=await k(a());return T=u.jwt,u}),v.on("connected",()=>{v.multiplexer&&l.setTarget(v.multiplexer);let u=v.connectedUrl;u&&h.setDocTransport({wsUrl:u,token:T})}),(async()=>{let u;try{u=await k(c)}catch(m){console.error(`[urun] Failed to create session for ${r}:`,m),de(i);let R=m instanceof Error?m:new Error(String(m)),M=m instanceof ve?m.httpStatus:void 0;v.reportAllocationFailure(R,M),w({status:"unavailable",cause:m});return}v.setAuth({jwt:u.jwt,authProvider:e.authProvider,orgId:e.orgId}),v.setConnection({url:u.url,sessionId:u.sessionId,iceServers:u.iceServers}),Z()&&await ee(),T=u.jwt,h.setDocTransport({wsUrl:u.url,token:u.jwt}),await v.connect({app:s,functionName:r,args:o}),h.negotiateMediaTransport({allowWebTransport:e.allowWebTransport})})().catch(u=>{console.error(`[urun] Failed to connect session for ${r}:`,u)}),e.releaseOnLeave!==!1){let u=Ce(()=>{let m=y;m&&(de(i),ye({baseUrl:m.baseUrl,requestId:m.requestId,orgId:e.orgId,jwt:f,authProvider:e.authProvider}))});h.onDisconnect(u)}return h}}})}var yt="https://api.urun.sh",P=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Tr(s,e={}){if(!s)throw new P("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=D(e.baseUrl??yt),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata);let o;try{o=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(n)})}catch(l){throw new P(`[urun] client token mint request failed: ${l instanceof Error?l.message:String(l)}`)}let i={};try{i=await o.json()}catch{}if(!o.ok){let l=typeof i.message=="string"?i.message:`HTTP ${o.status}`;throw new P(`[urun] client token mint failed: ${l}`,o.status)}let a=typeof i.token=="string"?i.token:"",c=typeof i.org_id=="string"?i.org_id:"",f=typeof i.expires_at=="string"?Date.parse(i.expires_at):Number.NaN,d=typeof i.expires_in=="number"?i.expires_in:void 0;if(!a)throw new P("[urun] client token mint returned no token (control-plane contract violation)",o.status);let p=Number.isFinite(f)?new Date(f):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:p,orgId:c}}var bt=3e4,_t="stream:",Ne=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let n;try{n=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(n.rpcId&&this._pendingRpc.has(n.rpcId)){let o=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(o.timer),n.error?o.reject(new Error(n.error)):o.resolve(n.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${_t}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${_t}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let o=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),n(new Error(`RPC request "${e}" timed out after ${bt}ms`)))},bt);this._pendingRpc.set(o,{resolve:r,reject:n,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Rr(s){let r=`${s.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(s.orgId)}`,n=new WebSocket(r);(s.jwt||s.apiKey)&&n.addEventListener("open",()=>{n.send(JSON.stringify({type:"auth",orgId:s.orgId,jwt:s.jwt,authProvider:s.authProvider,apiKey:s.apiKey}))});let o=new Ve(n);return new Ne(n,o)}var Ar='video/mp4; codecs="avc1.42E01E"';function Cr(s,e){let t=e?.codec??Ar,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,o=URL.createObjectURL(n);r.src=o,n.addEventListener("sourceopen",()=>{let l;try{l=n.addSourceBuffer(t)}catch(w){throw w instanceof DOMException&&w.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):w}let v=s.getReader();function h(){return l.updating?new Promise(w=>{l.addEventListener("updateend",()=>w(),{once:!0})}):Promise.resolve()}async function y(){try{for(;;){let{done:w,value:b}=await v.read();if(w){await h(),n.readyState==="open"&&n.endOfStream();return}await h();try{l.appendBuffer(b)}catch(_){if(_ instanceof DOMException&&_.name==="QuotaExceededError"){let k=l.buffered;if(k.length>0){let T=k.start(k.length-1);l.remove(0,T),await h(),l.appendBuffer(b)}else throw _}else throw _}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}y()}),r.play().catch(()=>{});let i=r,a=i.captureStream??i.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),f=c.getTracks(),d=0,p=f.length;if(p===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let l of f)l.addEventListener("ended",()=>{d++,d>=p&&URL.revokeObjectURL(o)});return c}function Er(s){return s.status.startsWith("pending_")}var ue=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function St(s){let e=[];return s.audio&&e.push("audio"),s.video&&e.push("video"),e.join("+")}function Ir(s,e){return e==="audio"?s.getAudioTracks():s.getVideoTracks()}function Pr(s,e){let t=s.getTracks();if(t.length===1&&t[0]===e)return s;try{return new MediaStream([e])}catch{return s}}function qe(s,e){for(let t of[...s.lostListeners])try{t(e)}catch{}}var le=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let r=this.claims.get(e);r&&(this.claims.delete(e),r.released=!0,r.track=null,r.stream=null,qe(r,new Error(`${e} capture claim superseded by a newer claim`)));let n=this.createState(e,t);return this.claims.set(e,n),await this.converge(n),n.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new ue;return t=>e.getUserMedia(t)}async converge(e){for(let i of this.claims.values())i.track&&(i.track.stop(),i.track=null,i.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},n;try{n=await t(r)}catch(i){let a=`one-capture getUserMedia(${St(r)}) failed`,c=i instanceof Error?i.message:String(i);for(let f of[...this.claims.values()])if(this.claims.delete(f.kind),f.released=!0,f!==e){let d=new Error(`${a} \u2014 ${f.kind} capture lost: ${c||i}`);d.cause=i,qe(f,d)}throw i}let o=[...this.claims.values()].sort((i,a)=>i===e?1:a===e?-1:0);for(let i of o){let a=Ir(n,i.kind)[0]??null;if(i.released){a?.stop();continue}if(!a){this.claims.delete(i.kind),i.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${St(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===e)throw c;qe(i,c);continue}if(i.track=a,i.stream=Pr(n,a),i!==e)for(let c of[...i.trackListeners])try{c(a,i.stream)}catch{}}}createState(e,t){let r=this,n={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return n.track},get stream(){return n.stream},update(o){return r.enqueue(async()=>{if(n.released)throw new Error(`${e} capture claim already released`);if(n.constraints=o,await r.converge(n),!n.track)throw new Error(`${e} capture update yielded no track`);return n.track})},release(){n.released||(n.released=!0,r.claims.get(e)===n&&r.claims.delete(e),n.track?.stop(),n.track=null,n.stream=null)},onTrack(o){return n.trackListeners.add(o),()=>n.trackListeners.delete(o)},onLost(o){return n.lostListeners.add(o),()=>n.lostListeners.delete(o)}}};return n}},Mr=null;function xr(){return Mr??=new le}var kt="input",Or=30;function Dr(s){let e=s.now??Date.now,t=s.field??kt,r=1e3/Math.max(s.hz??30,.001),n=new Set,o=0,i=0,a=0,c=0,f,d=null,p=!1,l=()=>{if(p)return;f=e(),c+=1;let h={keys:[...n],buttons:o,pointer:{x:i,y:a},seq:c,at:f};try{s.awareness.setLocalStateField(t,h)}catch{}},v=()=>{if(p)return;let h=e();if(f===void 0||h-f>=r){d&&(clearTimeout(d),d=null),l();return}if(d)return;let y=Math.max(r-(h-f),0);d=setTimeout(()=>{d=null,l()},y),d.unref?.()};return{keyDown(h){let y=String(h).toLowerCase();n.has(y)||(n.add(y),v())},keyUp(h){let y=String(h).toLowerCase();n.delete(y)&&v()},setButtons(h){let y=Number.isFinite(h)?Number(h):0;y!==o&&(o=y,v())},movePointer(h,y){let w=Number.isFinite(h)?Number(h):0,b=Number.isFinite(y)?Number(y):0;w===0&&b===0||(i+=w,a+=b,v())},heldKeys(){return[...n]},clear(){p||(n.clear(),o=0,d&&(clearTimeout(d),d=null),l())},dispose(){if(p)return;let h=n.size>0||o!==0;n.clear(),o=0,d&&(clearTimeout(d),d=null),h&&l(),p=!0}}}export{Ht as ACTIVATION_COLD_BOOT_AFTER_MS,Bt as ACTIVATION_DEGRADED_AFTER_MS,_e as ACTIVATION_HINT_PATH,$t as ACTIVATION_STILL_AFTER_MS,Te as ACTIVITY_DOM_EVENTS,it as ACTIVITY_FIELD,er as ACTIVITY_STAMP_MIN_INTERVAL_MS,N as ActivationMonitor,kr as App,Lt as BACKOFF_BASE_MS,Nt as BACKOFF_MAX_ATTEMPTS,Ft as BACKOFF_MAX_MS,le as CaptureController,ue as CaptureUnavailableError,P as ClientTokenError,ht as DEFAULT_DOC_SYNC_TIMEOUT_MS,yt as DEFAULT_GATEWAY_URL,Et as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Dt as DEFAULT_WHEN_LIVE_TIMEOUT_MS,$ as DGRAM_HEADER_BYTES,tr as FOREGROUND_COALESCE_MS,H as FrameReassembler,Or as INPUT_PRESENCE_DEFAULT_HZ,kt as INPUT_PRESENCE_FIELD,U as InvalidDurationError,Se as LEGACY_ACTIVATION_HINT_PATH,be as PLATFORM_DOC_NAME,ce as PermanentLockedError,ae as PinRequiresActiveTempError,It as ProduceAckTimeoutError,ie as RecordingNotFoundError,L as RecordingsClient,A as RecordingsError,W as RecordingsUnauthorizedError,Q as RequestAbortError,ge as RequestCancelledError,me as RequestDocSyncError,X as RequestError,fe as RequestTimeoutError,oe as RetainNotTempError,se as RuntimeArtifactNotFoundError,I as RuntimeArtifactsClient,S as RuntimeArtifactsError,ne as RuntimeArtifactsUnauthorizedError,z as Session,ve as SessionAllocationError,Ct as SessionEndError,F as SessionEndUnavailableError,Mt as SessionFailedError,he as StreamDirectionConflict,V as TransportNegotiator,K as TransportSessionSignaling,ot as VISIBILITY_FIELD,dt as WT_CONTROL_FRAME_MAX,G as WebRtcSession,B as WebTransportSession,j as WtControlDecoder,rt as activationHintFrom,qt as computeBackoffDelay,Re as createActivityTracker,Tr as createClientToken,Dr as createInputPresencePublisher,Zt as createRecordingsClient,Kt as createRuntimeArtifactsClient,Rr as createStore,Pt as describeSessionFailure,Ut as describeSessionPhase,Pe as encodeWtControlFrame,ke as isDurationString,Er as isPendingRecording,Wt as isRetryableSessionError,Ot as isWakingPhase,Ee as mediaRecorderChunkSource,Xt as normalizeRetention,Ae as observePageLifecycle,Ce as observePageTeardown,Me as parseDgramHeader,jt as prewake,ye as releaseSessionBeacon,xt as sessionFailureFromMediaError,xr as sharedCaptureController,Cr as videoStream,we as whenLive,ir as writeDgramHeader};
|