@urun-sh/core 0.2.47 → 0.2.49
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/CHANGELOG.md +45 -0
- package/dist/chunk-BQIH7RYF.mjs +8 -0
- package/dist/chunk-PQCL4SUQ.mjs +3 -0
- package/dist/index.browser.d.mts +2 -2
- package/dist/index.browser.d.ts +2 -2
- package/dist/index.browser.js +2 -2
- package/dist/index.browser.mjs +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -5
- package/dist/index.mjs +1 -1
- package/dist/internal.browser.d.mts +1 -1
- package/dist/internal.browser.d.ts +1 -1
- package/dist/internal.browser.js +2 -2
- package/dist/internal.browser.mjs +1 -1
- package/dist/internal.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +5 -5
- package/dist/internal.mjs +1 -1
- package/dist/{stream-data-DVQgPiJ2.d.mts → stream-data-TWBl_kh7.d.mts} +42 -24
- package/dist/{stream-data-DVQgPiJ2.d.ts → stream-data-TWBl_kh7.d.ts} +42 -24
- package/package.json +1 -1
- package/dist/chunk-FFQBRQM7.mjs +0 -3
- package/dist/chunk-MFBAY7ST.mjs +0 -8
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 N,B as Xe,C as Se,D as Qe,E as Ze,F as et,G as Jt,H as ne,J as se,K as ie,M as tt,O as Xt,P as Qt,Q as Zt,R as oe,T as rt,U as nt,V as st,W as it,X as ot,a as Je,b as ee,c as $,d as Ut,e as te,f as ge,g as ve,h as we,i as Lt,j as Nt,k as re,l as ye,m as Ft,n as Wt,o as qt,p as jt,q as be,r as $t,s as Bt,t as _e,u as Ht,v as Vt,w as Kt,x as Gt,y as zt,z as Yt}from"./chunk-MFBAY7ST.mjs";var er=15e3,tr=45e3,rr=12e4,Te="platform",ke="activation",Re="desired.activation";function at(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 nr=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],B=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 nr){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=at(this._options.hint());o!==void 0&&(n.hint=o),e.lastEvent=n;for(let i of Array.from(this._handlers))i(n)}};var T=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)}},ae=class extends T{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},ce=class extends T{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function H(s){return{baseUrl:s.baseUrl,fallbackUrls:s.fallbackUrls,orgId:s.orgId,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}function sr(s){return new D(s)}var D=class{_options;constructor(e){this._options=e}async list(e){let r=dt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new T("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(ct)}async getDownloadUrl(e,t){let r=dt(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!or(n))throw new T("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:ct(r.artifact),downloadUrl:n}}async _request(e,t){let r=Xe(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 T&&ar(n.status))throw n}throw n??new T("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${N(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 cr(i.status,a,c)}try{return await i.json()}catch(a){throw new T(`[urun] runtime artifacts: invalid JSON response from ${N(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=N(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 ct(s){if(!s||typeof s!="object")throw new T("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=s,t=P(e,"artifact_id")||P(e,"id"),r=P(e,"filename"),n=P(e,"kind"),o=P(e,"status")||"ready",i=ir(e,"size_bytes"),a=P(e,"sha256");if(!t||!r||!n||i==null||!a)throw new T("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:P(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:P(e,"created_at"),expiresAt:P(e,"expires_at")}}function P(s,e){let t=s[e];return typeof t=="string"&&t.length>0?t:void 0}function ir(s,e){let t=s[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function or(s){try{return new URL(s).protocol==="https:"}catch{return!1}}function ar(s){return s===401||s===403}function cr(s,e,t){return s===401?new ae(t,e):s===404?new ce(t,e):new T(t,s,e)}function dt(s){if(!s||typeof s!="object"||Array.isArray(s))throw new T("[urun] runtime artifacts: malformed response",0,"bad_response");return s}var C=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)}},V=class extends C{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},de=class extends C{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},ue=class extends C{constructor(e="[urun] recordings: retain requires a temp recording",t="retain_not_temp"){super(e,{status:409,code:t}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},le=class extends C{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)}},pe=class extends C{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},F=class extends C{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 Ae(s){return/^(\d+[smhdw])+$/.test(s)}function dr(s){if(s==="pin")return{action:"pin"};if(Ae(s))return{action:"retain",duration:s};throw new F(`[urun] recordings: "${s}" is not a duration or "pin"`)}function ur(s,e,t){let r=t||e||`HTTP ${s}`;if(s===401)return new V(r,e??"unauthorized");if(s===404)return new de(r,e??"not_found");if(s===400)return new F(r,e??"bad_request",400);if(s===409)switch(e){case"retain_not_temp":return new ue(r,e);case"pin_requires_active_temp":return new le(r,e);case"permanent_locked":return new pe(r,e)}return new C(r,{status:s,code:e??`http_${s}`})}var W=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(!Ae(t))throw new F(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new C("[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 ur(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 V("[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 lr(s){return new W(s)}var ut="activity",lt="visibility",pr=15e3,Ee=["pointerdown","pointermove","keydown","wheel","touchstart"];function Ce(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 m=e();if(!(o!==void 0&&m-o<15e3)){o=m;try{s.awareness.setLocalStateField(ut,{at:m})}catch{}}},a=()=>{if(!(n||!r||r.visibilityState===void 0))try{s.awareness.setLocalStateField(lt,r.visibilityState)}catch{}},c=()=>i(),u=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&i()};if(t)for(let m of Ee)t.addEventListener(m,c,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",u);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 m of Ee)t.removeEventListener(m,c,{capture:!0});r&&r.removeEventListener("visibilitychange",u),d&&(clearInterval(d),d=null)}}}}var fr=250;function Ie(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 Pe(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)}}function Me(s){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{s()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var pt="video/mp4";function xe(s,e={}){let t=e.timesliceMs??1e3,r=null,n=null,o=!1,i=(a,c,u)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let m=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(pt)?pt:void 0),p=new MediaStream([a]),l=new d(p,m?{mimeType:m}:void 0);r=l;let f=Promise.resolve();l.ondataavailable=w=>{let y=w.data;o||!y||y.size===0||(f=f.then(async()=>{let _=new Uint8Array(await y.arrayBuffer());o||c(_)}))},l.onstop=()=>{f.then(()=>{o||u()})},l.onerror=()=>{f.then(()=>{o||u()})},l.start(t)};return{start(a,c){if(r||o)return;let u=s.track();if(u){i(u,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 mr(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 ft(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 mr(o)}import{encode as hr,decode as gr}from"@msgpack/msgpack";var mt=65536;function Oe(s){let e=hr(s),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var K=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>mt)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(gr(n))}return t}},G=12,De=1;function Ue(s){let e=s.getUint8(8);return{groupId:s.getUint32(0,!0),frameSeq:s.getUint32(4,!0),keyframe:(e&De)===De,fragIndex:s.getUint8(9),fragCount:s.getUint8(10)}}function vr(s){let e=new Uint8Array(G),t=new DataView(e.buffer);return t.setUint32(0,s.groupId,!0),t.setUint32(4,s.frameSeq,!0),t.setUint8(8,s.keyframe?De:0),t.setUint8(9,s.fragIndex),t.setUint8(10,s.fragCount),t.setUint8(11,0),e}var wr=100,z=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??wr}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<G)return;let t=Ue(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(G),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 yr=/^avc[13]\.[0-9a-fA-F]{6}$/;function br(s){return yr.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 Le(s,e){let t=br(s);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var _r=250,Sr=3,Tr=1e4,Ne=2500,Y=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 z({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");Le(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 K,o=[],i=await this.readControl(r,n,o);if(i?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");Le(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<Tr),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=Sr){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 ${Ne}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${Ne}ms`))},Ne);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(Oe(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(()=>{})},_r)}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 ht=2500,gt=["av01.0.08M.08","avc1.42E01F","avc1.640028"],J=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:gt};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 vt(a.start(),this.opts.quicDeadlineMs??ht,"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:gt}}),!this.offer.webtransport)return null;let n=this.createWebTransportSession();try{await vt(n.start(),this.opts.quicDeadlineMs??ht,"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 Y(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 vt(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 kr=1e4,X=class{constructor(e,t=kr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=ie();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:u,requestId:d,...m}=c;n(m)});this.carrier.sendSignal({type:e,requestId:r,...t})})}notify(e,t){this.carrier.sendSignal({type:e,...t})}on(e,t){return this.carrier.onSignal(r=>{r.type===e&&t(r)})}};var Rr="video",Q=class{constructor(e,t=Rr){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 Ar="video";function wt(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,u=!1,d=()=>{if(c){for(let b of c.getVideoTracks())try{b.stop()}catch{}c=null}u&&(u=!1,t.onOverrideTrack(null))},m=new J(new X(s),e,{canvas:i,createWebRtcSession:t.createWebRtcSession??(()=>new Q(s,t.streamName??Ar)),createWebTransportSession:t.createWebTransportSession,onTransportChange:(b,h)=>{b==="webrtc"&&(d(),S()),t.onTransportChange?.(b,h)}}),p=null,l=()=>{p!==null&&(clearTimeout(p),p=null)},f=t.wtRetryBaseMs??2e3,w=t.wtRetryCapMs??3e4,y=null,_=0,S=()=>{if(a||y!==null||m.activeTransport==="webtransport")return;let b=Math.min(f*2**_,w);y=setTimeout(()=>{y=null,_+=1,m.retryWebTransport().then(h=>{if(!a){if(h)return console.debug(`[urun] webtransport upgraded in background (retry ${_})`),_=0,k(h);S()}}).catch(h=>{a||(console.debug(`[urun] webtransport background retry ${_} failed:`,h),S())})},b)},R=()=>{y!==null&&(clearTimeout(y),y=null)},k=async b=>{if(a||b.kind!=="webtransport")return;let h=t.firstMediaWarnMs??1e4;if(l(),p=setTimeout(()=>{a||m.activeTransport!=="webtransport"||console.warn(`[urun] webtransport established but no QUIC media after ${h}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)},h),await b.firstMedia,l(),a||m.activeTransport!=="webtransport"||typeof i.captureStream!="function")return;c=i.captureStream();let v=c.getVideoTracks()[0];v&&(u=!0,t.onOverrideTrack(v))};return(async()=>{let b=await m.connect();await k(b)})().catch(b=>{l(),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",b),S()}),{activeTransport:()=>m.activeTransport,dispose(){a=!0,l(),R(),d(),m.disconnect().catch(()=>{})}}}var Er=new Set;function qe(s){if(s.functionsUrl)return{functionsUrl:s.functionsUrl,orgId:s.orgId,apiKey:s.apiKey,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}var Cr="rpc",bt=3e4,Ir="rpc-resp";function Pr(s){return`${Ir}:${s}`}function Fe(){return ie()}function Mr(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 xr(s,e,t,r,n,o,i,a,c,u){let d=[],m=null,p=!1,l=null,f=!1,w,y,_=new Promise((g,M)=>{w=g,y=M});_.catch(()=>{});let S=i(),R=null,k=null,b=null,h=null,v=!0,I=()=>{b&&(clearTimeout(b),b=null),h&&(h(),h=null)},E=!1,j=()=>{E||!f||(E=!0,s.set({rpc:{[e]:null}}))},A=()=>{v=!1,I(),R?.(),R=null,k?.(),k=null,a?.removeEventListener("abort",ze),S.dispose(),j()},x=()=>{if(m){if(d.length>0){let g=m;m=null,g.resolve({value:d.shift(),done:!1})}else if(l!==null){let g=m;m=null,g.reject(l)}else if(p){let g=m;m=null,g.resolve({value:void 0,done:!0})}}},xt=g=>{p||(d.push(g),x())},U=g=>{p||(l=g,p=!0,y(g),A(),x())},Ge=g=>{p||(p=!0,w(g),A(),x())},ze=()=>{let g=a?.reason;U(g instanceof te?g:new re(e))},Dt=g=>{if(!(p||!g||typeof g!="object"))switch(j(),g.t){case"delta":typeof g.delta=="string"&&xt(g.delta);break;case"response":Ge(g.body);break;case"error":{let{message:M,code:L}=Mr(g.body);U(new te(M,{requestId:e,code:g.code??L}));break}}},Ot=()=>{let g=S.messages()[Symbol.asyncIterator]();R=()=>{g.return?.(void 0)};let M=()=>{v&&g.next().then(L=>{if(v){if(L.done){p||Ge(void 0);return}Dt(L.value),M()}},L=>{v&&U(L)})};M()},Ye=()=>{if(!f){if(f=!0,a){if(a.aborted){U(new re(e));return}a.addEventListener("abort",ze,{once:!0})}k=c?.(g=>U(g))??null,Ot(),s.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:o}}}),u&&u>0&&!s.synced&&(b=setTimeout(()=>{b=null,!p&&!s.synced&&U(new ve(u,e))},u),h=s.onSynced(()=>I()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Ye(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(l!==null){let g=l;return l=null,Promise.reject(g)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((g,M)=>{m={resolve:g,reject:M}})},return(){return p||(p=!0,w(void 0),A()),Promise.resolve({value:void 0,done:!0})},throw(g){return p||(p=!0,y(g),A()),Promise.reject(g)}}}},body:_,start:Ye}}function yt(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 Dr(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=yt(o);c&&(a.rt=c);let u=yt(i);return u&&(a.br=u),a}var We=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=Dr(t,this._name),n=r?.br;if(n?.by==="runtime")throw new we(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??xe;return ft(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 st;_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=tt(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Ie(()=>this.recover()),this._activity=Ce({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new B({onPhase:i=>this.onPhase(i),hint:()=>this.doc(Te).get(ke)??this.doc("control").get(Re),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 et({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 ee,i=new oe({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new s(e,o,i,qe(t),H({...t,baseUrl:r.baseUrl}));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),ne()&&await se();let c=t.getAccessToken,u=c?async()=>await c()??n:n;return a.setDocTransport({wsUrl:r.wsUrl,token:u}),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 _e(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 W(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 D(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new D(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 We(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 it(e,this._sessionId,Er.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=ot(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=rt(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",n=`${t}\0${r}\0${this._sessionId}`;n!==this._docEndpointKey&&(this._docEndpointKey=n,this.connectDocs(nt({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=Fe(),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 ge(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(Cr),a=Pr(e);return xr(i,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??bt)}requestStream(e,t={}){let r=Fe();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Fe(),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=wt(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 $)}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 ye)}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 _t(s){return`urun:logical:v1:${s.orgId}:${s.app}:${s.functionName}`}function je(){try{return globalThis.sessionStorage??null}catch{return null}}function St(s){let e=je();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 Tt(s,e){let t=je();if(t)try{t.setItem(s,JSON.stringify({logicalId:e.logicalId}))}catch{}}function fe(s){let e=je();if(e)try{e.removeItem(s)}catch{}}var Or=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Ur(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(!(Or.has(r)||typeof r!="string"))return n=>{let o=n??{},i=_t({orgId:e.orgId,app:s,functionName:r}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,c=a(),u=e.jwt,d=e.getAccessToken?async h=>{let v=await e.getAccessToken(h);return v&&(u=v),v}:void 0,m={...e,getAccessToken:d},p=new ee,l=new oe({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c}),f=new Z(c,p,l,qe(m),H(m)),w,y,_=new Promise(h=>{y=h}),S=h=>{w=h,y({status:"ready",handle:h})};f.setEndHandler(async()=>{let h=w?{status:"ready",handle:w}:await _;if(h.status==="unavailable")throw new $("[urun] session allocation failed before a releasable request was created",{cause:h.cause});let v=h.handle;return fe(i),Qe({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider})});let R=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??St(i)?.logicalId,priority:e.priority,onAdmission:E=>l.reportAdmission(E),onRequest:S}),I=d?await d()??void 0:e.jwt;return e.sessionKey||Tt(i,{logicalId:v.sessionId}),f.setSessionId(v.sessionId),f.setArtifactsAuth(H({...m,baseUrl:v.baseUrl})),l.setEndsAt(v.endsAt),{url:v.wsUrl,sessionId:v.sessionId,jwt:I,iceServers:v.response.ice_servers,endsAt:v.endsAt}},k,b=d?async()=>await d()??k:()=>k;if(l.setConnectionResolver(async()=>{let h=await R(a());return k=h.jwt,h}),l.on("connected",()=>{l.multiplexer&&p.setTarget(l.multiplexer);let h=l.connectedUrl;h&&f.setDocTransport({wsUrl:h,token:b})}),(async()=>{let h;try{h=await R(c)}catch(v){console.error(`[urun] Failed to create session for ${r}:`,v),fe(i);let I=v instanceof Error?v:new Error(String(v)),E=v instanceof be?v.httpStatus:void 0;l.reportAllocationFailure(I,E),y({status:"unavailable",cause:v});return}l.setAuth({jwt:h.jwt,authProvider:e.authProvider,orgId:e.orgId}),l.setConnection({url:h.url,sessionId:h.sessionId,iceServers:h.iceServers}),ne()&&await se(),k=h.jwt,f.setDocTransport({wsUrl:h.url,token:b}),await l.connect({app:s,functionName:r,args:o}),f.negotiateMediaTransport({allowWebTransport:e.allowWebTransport})})().catch(h=>{console.error(`[urun] Failed to connect session for ${r}:`,h)}),e.releaseOnLeave!==!1){let h=Pe(()=>{if(l.leaveLeg()||l.connectedUrl!==null)return;let A=w;A&&(fe(i),Se({baseUrl:A.baseUrl,requestId:A.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))});f.onDisconnect(h);let v,I,E=!1,j=()=>{E||(E=!0,v?.(),I?.())};_.then(A=>{A.status!=="ready"||E||(v=Me(()=>w!==void 0))}),I=f.onPhase(A=>{let x=A?.name;(x==="ended"||x==="expired"||x==="error")&&j()}),E&&I(),f.onDisconnect(j)}return f}}})}var kt="https://api.urun.sh",O=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Lr(s,e={}){if(!s)throw new O("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=N(e.baseUrl??kt),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(p){throw new O(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let i={};try{i=await o.json()}catch{}if(!o.ok){let p=typeof i.message=="string"?i.message:`HTTP ${o.status}`;throw new O(`[urun] client token mint failed: ${p}`,o.status)}let a=typeof i.token=="string"?i.token:"",c=typeof i.org_id=="string"?i.org_id:"",u=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 O("[urun] client token mint returned no token (control-plane contract violation)",o.status);let m=Number.isFinite(u)?new Date(u):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:m,orgId:c}}var Rt=3e4,At="stream:",$e=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=`${At}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${At}${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 ${Rt}ms`)))},Rt);this._pendingRpc.set(o,{resolve:r,reject:n,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Nr(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 Je(n);return new $e(n,o)}var Fr='video/mp4; codecs="avc1.42E01E"';function Wr(s,e){let t=e?.codec??Fr,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 p;try{p=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 l=s.getReader();function f(){return p.updating?new Promise(y=>{p.addEventListener("updateend",()=>y(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:y,value:_}=await l.read();if(y){await f(),n.readyState==="open"&&n.endOfStream();return}await f();try{p.appendBuffer(_)}catch(S){if(S instanceof DOMException&&S.name==="QuotaExceededError"){let R=p.buffered;if(R.length>0){let k=R.start(R.length-1);p.remove(0,k),await f(),p.appendBuffer(_)}else throw S}else throw S}}}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),u=c.getTracks(),d=0,m=u.length;if(m===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{d++,d>=m&&URL.revokeObjectURL(o)});return c}function qr(s){return s.status.startsWith("pending_")}var me=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 Et(s){let e=[];return s.audio&&e.push("audio"),s.video&&e.push("video"),e.join("+")}function jr(s,e){return e==="audio"?s.getAudioTracks():s.getVideoTracks()}function $r(s,e){let t=s.getTracks();if(t.length===1&&t[0]===e)return s;try{return new MediaStream([e])}catch{return s}}function Be(s,e){for(let t of[...s.lostListeners])try{t(e)}catch{}}var he=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,Be(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 me;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(${Et(r)}) failed`,c=i instanceof Error?i.message:String(i);for(let u of[...this.claims.values()])if(this.claims.delete(u.kind),u.released=!0,u!==e){let d=new Error(`${a} \u2014 ${u.kind} capture lost: ${c||i}`);d.cause=i,Be(u,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=jr(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(${Et(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===e)throw c;Be(i,c);continue}if(i.track=a,i.stream=$r(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}},Br=null;function Hr(){return Br??=new he}var Ct="input",Vr=30;function Kr(s){let e=s.now??Date.now,t=s.field??Ct,r=1e3/Math.max(s.hz??30,.001),n=new Set,o=0,i=0,a=0,c=0,u,d=null,m=!1,p=()=>{if(m)return;u=e(),c+=1;let f={keys:[...n],buttons:o,pointer:{x:i,y:a},seq:c,at:u};try{s.awareness.setLocalStateField(t,f)}catch{}},l=()=>{if(m)return;let f=e();if(u===void 0||f-u>=r){d&&(clearTimeout(d),d=null),p();return}if(d)return;let w=Math.max(r-(f-u),0);d=setTimeout(()=>{d=null,p()},w),d.unref?.()};return{keyDown(f){let w=String(f).toLowerCase();n.has(w)||(n.add(w),l())},keyUp(f){let w=String(f).toLowerCase();n.delete(w)&&l()},setButtons(f){let w=Number.isFinite(f)?Number(f):0;w!==o&&(o=w,l())},movePointer(f,w){let y=Number.isFinite(f)?Number(f):0,_=Number.isFinite(w)?Number(w):0;y===0&&_===0||(i+=y,a+=_,l())},heldKeys(){return[...n]},clear(){m||(n.clear(),o=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(m)return;let f=n.size>0||o!==0;n.clear(),o=0,d&&(clearTimeout(d),d=null),f&&p(),m=!0}}}var Gr=1024,zr=.92,Yr=262144,Jr=256e3,He=[.9,.8,.7,.6,.5],It=.8,Xr=8;function Ke(s,e,t){if(!(s>0)||!(e>0))throw new Error(`reference image has no pixels (${s}x${e})`);let r=Math.min(1,t/Math.max(s,e));return{width:Math.max(1,Math.round(s*r)),height:Math.max(1,Math.round(e*r))}}async function Qr(s){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(s,{imageOrientation:"from-image"})}async function Mt(s,e,t){let r=await new Promise(n=>{s.toBlob(n,e,e==="image/jpeg"?t:void 0)});if(!r)throw new Error(`could not encode the reference image as ${e}`);return r}function Pt(s,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${s} -> ${e} bytes`)}async function Ve(s,e,t,r,n){let o=document.createElement("canvas");o.width=e,o.height=t;let i=o.getContext("2d");if(!i)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(i.fillStyle="#fff",i.fillRect(0,0,e,t)),i.drawImage(s,0,0,e,t),await Mt(o,r,n)}async function Zr(s,e,t,r){let{width:n,height:o}=e,i=await Ve(s,n,o,t,r);if(i.size<=256e3)return{blob:i,width:n,height:o};if(t==="image/jpeg"){for(let c of He)if(!(c>=r)&&(i=await Ve(s,n,o,t,c),i.size<=256e3))return Pt(`quality ${r} -> ${c}`,i.size),{blob:i,width:n,height:o}}let a=t==="image/jpeg"?He[He.length-1]:r;for(let c=0;c<Xr;c++)if(n=Math.max(16,Math.round(n*It)),o=Math.max(16,Math.round(o*It)),i=await Ve(s,n,o,t,a),i.size<=256e3)return Pt(`downscaled to ${n}x${o} @ q${a}`,i.size),{blob:i,width:n,height:o};throw new Error(`this image cannot be sent: even at ${n}x${o} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function en(s,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:o}=e,i=await Qr(s);try{let a=Ke(i.width,i.height,t),c=await Zr(i,a,r,n);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:r,width:c.width,height:c.height,source:o}}finally{i.close()}}function tn(s){let e=s instanceof Error?s.name:"",t=s instanceof Error?s.message:String(s);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function rn(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function nn(s,e){let t=s.videoWidth,r=s.videoHeight;if(!(t>0)||!(r>0))throw new Error("the camera has not shown a frame yet");let{maxSize:n=1024,type:o="image/jpeg",quality:i=.92}=e??{},a=Ke(t,r,n),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let u=c.getContext("2d");if(!u)throw new Error("could not prepare the reference image (no 2d canvas context)");o==="image/jpeg"&&(u.fillStyle="#fff",u.fillRect(0,0,a.width,a.height)),u.drawImage(s,0,0,a.width,a.height);let d=await Mt(c,o,i);return{bytes:new Uint8Array(await d.arrayBuffer()),type:o,width:a.width,height:a.height,source:"camera"}}var sn=new Set(["w","a","s","d"]),q=(s,e)=>Math.min(e,Math.max(-e,s));function on(s={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:n=900,frameRelax:o=.06,maxPan:i=.12,maxLogZoom:a=.22}=s,c=0,u=0,d=0,m=null,p=new Set;return{pointerDelta(l,f){c=q(c-l*e,i),u=q(u-f*e,i)},keyDown(l){let f=l.toLowerCase();sn.has(f)&&p.add(f)},keyUp(l){p.delete(l.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let l=1-o;c*=l,u*=l,d*=l},tick(l){if(m===null){m=l;return}let f=Math.max(0,Math.min(100,l-m))/1e3;m=l,p.has("w")&&(d=q(d+t*f,a)),p.has("s")&&(d=q(d-t*f,a)),p.has("a")&&(c=q(c+r*f,i)),p.has("d")&&(c=q(c-r*f,i));let w=Math.exp(-f*1e3/n);c*=w,u*=w,d*=w},transform(){return{translateX:c,translateY:u,scale:Math.exp(d)}},isIdentity(l=5e-4){return Math.abs(c)<l&&Math.abs(u)<l&&Math.abs(d)<l},reset(){c=0,u=0,d=0,p.clear()}}}export{tr as ACTIVATION_COLD_BOOT_AFTER_MS,rr as ACTIVATION_DEGRADED_AFTER_MS,ke as ACTIVATION_HINT_PATH,er as ACTIVATION_STILL_AFTER_MS,Ee as ACTIVITY_DOM_EVENTS,ut as ACTIVITY_FIELD,pr as ACTIVITY_STAMP_MIN_INTERVAL_MS,B as ActivationMonitor,Ur as App,Vt as BACKOFF_BASE_MS,Gt as BACKOFF_MAX_ATTEMPTS,Kt as BACKOFF_MAX_MS,he as CaptureController,me as CaptureUnavailableError,O as ClientTokenError,Yr as DATA_CHANNEL_MESSAGE_CEILING,bt as DEFAULT_DOC_SYNC_TIMEOUT_MS,kt as DEFAULT_GATEWAY_URL,Lt as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,zr as DEFAULT_REFERENCE_JPEG_QUALITY,Gr as DEFAULT_REFERENCE_MAX_SIZE,Bt as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Xt as DERIVED_LEG_SEP,G as DGRAM_HEADER_BYTES,fr as FOREGROUND_COALESCE_MS,z as FrameReassembler,Vr as INPUT_PRESENCE_DEFAULT_HZ,Ct as INPUT_PRESENCE_FIELD,F as InvalidDurationError,Re as LEGACY_ACTIVATION_HINT_PATH,Te as PLATFORM_DOC_NAME,pe as PermanentLockedError,le as PinRequiresActiveTempError,Nt as ProduceAckTimeoutError,de as RecordingNotFoundError,W as RecordingsClient,C as RecordingsError,V as RecordingsUnauthorizedError,re as RequestAbortError,ye as RequestCancelledError,ve as RequestDocSyncError,te as RequestError,ge as RequestTimeoutError,ue as RetainNotTempError,ce as RuntimeArtifactNotFoundError,D as RuntimeArtifactsClient,T as RuntimeArtifactsError,ae as RuntimeArtifactsUnauthorizedError,Z as Session,be as SessionAllocationError,Ut as SessionEndError,$ as SessionEndUnavailableError,Wt as SessionFailedError,we as StreamDirectionConflict,J as TransportNegotiator,jt as TransportSessionMismatchError,X as TransportSessionSignaling,lt as VISIBILITY_FIELD,Jr as WIRE_MESSAGE_BUDGET,mt as WT_CONTROL_FRAME_MAX,Q as WebRtcSession,Y as WebTransportSession,K as WtControlDecoder,at as activationHintFrom,rn as cameraCaptureAvailable,nn as captureStillFromVideo,zt as computeBackoffDelay,Ce as createActivityTracker,on as createCameraWarp,Lr as createClientToken,Kr as createInputPresencePublisher,lr as createRecordingsClient,sr as createRuntimeArtifactsClient,Nr as createStore,Zt as derivedLegName,Qt as derivedLegRole,Ft as describeSessionFailure,Ht as describeSessionPhase,Oe as encodeWtControlFrame,Ke as fitWithin,Ae as isDurationString,qr as isPendingRecording,Yt as isRetryableSessionError,$t as isWakingPhase,xe as mediaRecorderChunkSource,en as normalizeReferenceImage,dr as normalizeRetention,Me as observeLeaveConfirm,Ie as observePageLifecycle,Pe as observePageTeardown,Ue as parseDgramHeader,Jt as prewake,tn as referenceImageErrorMessage,Se as releaseSessionBeacon,qt as sessionFailureFromMediaError,Hr as sharedCaptureController,Wr as videoStream,_e as whenLive,vr as writeDgramHeader};
|
|
2
|
+
import{A as N,B as Xe,C as Se,D as Qe,E as Ze,F as et,G as Jt,H as ne,J as se,K as ie,M as tt,O as Xt,P as Qt,Q as Zt,R as oe,T as rt,U as nt,V as st,W as it,X as ot,a as Je,b as ee,c as B,d as Ut,e as te,f as ge,g as ve,h as we,i as Lt,j as Nt,k as re,l as ye,m as Ft,n as Wt,o as qt,p as jt,q as be,r as Bt,s as $t,t as _e,u as Ht,v as Vt,w as Kt,x as Gt,y as zt,z as Yt}from"./chunk-BQIH7RYF.mjs";var er=15e3,tr=45e3,rr=12e4,ke="platform",Te="activation",Re="desired.activation";function at(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 nr=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],$=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 nr){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=at(this._options.hint());o!==void 0&&(n.hint=o),e.lastEvent=n;for(let i of Array.from(this._handlers))i(n)}};var k=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)}},ae=class extends k{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},ce=class extends k{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function H(s){return{baseUrl:s.baseUrl,fallbackUrls:s.fallbackUrls,orgId:s.orgId,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}function sr(s){return new D(s)}var D=class{_options;constructor(e){this._options=e}async list(e){let r=dt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new k("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(ct)}async getDownloadUrl(e,t){let r=dt(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!or(n))throw new k("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:ct(r.artifact),downloadUrl:n}}async _request(e,t){let r=Xe(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 k&&ar(n.status))throw n}throw n??new k("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${N(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 cr(i.status,a,c)}try{return await i.json()}catch(a){throw new k(`[urun] runtime artifacts: invalid JSON response from ${N(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=N(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 ct(s){if(!s||typeof s!="object")throw new k("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=s,t=P(e,"artifact_id")||P(e,"id"),r=P(e,"filename"),n=P(e,"kind"),o=P(e,"status")||"ready",i=ir(e,"size_bytes"),a=P(e,"sha256");if(!t||!r||!n||i==null||!a)throw new k("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:P(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:P(e,"created_at"),expiresAt:P(e,"expires_at")}}function P(s,e){let t=s[e];return typeof t=="string"&&t.length>0?t:void 0}function ir(s,e){let t=s[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function or(s){try{return new URL(s).protocol==="https:"}catch{return!1}}function ar(s){return s===401||s===403}function cr(s,e,t){return s===401?new ae(t,e):s===404?new ce(t,e):new k(t,s,e)}function dt(s){if(!s||typeof s!="object"||Array.isArray(s))throw new k("[urun] runtime artifacts: malformed response",0,"bad_response");return s}var C=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)}},V=class extends C{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},de=class extends C{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},ue=class extends C{constructor(e="[urun] recordings: retain requires a temp recording",t="retain_not_temp"){super(e,{status:409,code:t}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},le=class extends C{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)}},pe=class extends C{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},F=class extends C{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 Ae(s){return/^(\d+[smhdw])+$/.test(s)}function dr(s){if(s==="pin")return{action:"pin"};if(Ae(s))return{action:"retain",duration:s};throw new F(`[urun] recordings: "${s}" is not a duration or "pin"`)}function ur(s,e,t){let r=t||e||`HTTP ${s}`;if(s===401)return new V(r,e??"unauthorized");if(s===404)return new de(r,e??"not_found");if(s===400)return new F(r,e??"bad_request",400);if(s===409)switch(e){case"retain_not_temp":return new ue(r,e);case"pin_requires_active_temp":return new le(r,e);case"permanent_locked":return new pe(r,e)}return new C(r,{status:s,code:e??`http_${s}`})}var W=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(!Ae(t))throw new F(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new C("[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 ur(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 V("[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 lr(s){return new W(s)}var ut="activity",lt="visibility",pr=15e3,Ee=["pointerdown","pointermove","keydown","wheel","touchstart"];function Ce(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(ut,{at:f})}catch{}}},a=()=>{if(!(n||!r||r.visibilityState===void 0))try{s.awareness.setLocalStateField(lt,r.visibilityState)}catch{}},c=()=>i(),u=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&i()};if(t)for(let f of Ee)t.addEventListener(f,c,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",u);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 Ee)t.removeEventListener(f,c,{capture:!0});r&&r.removeEventListener("visibilitychange",u),d&&(clearInterval(d),d=null)}}}}var mr=250;function Ie(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 Pe(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)}}function Me(s){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{s()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var pt="video/mp4";function xe(s,e={}){let t=e.timesliceMs??1e3,r=null,n=null,o=!1,i=(a,c,u)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let f=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(pt)?pt:void 0),p=new MediaStream([a]),l=new d(p,f?{mimeType:f}:void 0);r=l;let m=Promise.resolve();l.ondataavailable=w=>{let y=w.data;o||!y||y.size===0||(m=m.then(async()=>{let _=new Uint8Array(await y.arrayBuffer());o||c(_)}))},l.onstop=()=>{m.then(()=>{o||u()})},l.onerror=()=>{m.then(()=>{o||u()})},l.start(t)};return{start(a,c){if(r||o)return;let u=s.track();if(u){i(u,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 fr(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 mt(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 fr(o)}import{encode as hr,decode as gr}from"@msgpack/msgpack";var ft=65536;function Oe(s){let e=hr(s),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var K=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>ft)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(gr(n))}return t}},G=12,De=1;function Ue(s){let e=s.getUint8(8);return{groupId:s.getUint32(0,!0),frameSeq:s.getUint32(4,!0),keyframe:(e&De)===De,fragIndex:s.getUint8(9),fragCount:s.getUint8(10)}}function vr(s){let e=new Uint8Array(G),t=new DataView(e.buffer);return t.setUint32(0,s.groupId,!0),t.setUint32(4,s.frameSeq,!0),t.setUint8(8,s.keyframe?De:0),t.setUint8(9,s.fragIndex),t.setUint8(10,s.fragCount),t.setUint8(11,0),e}var wr=100,z=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??wr}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<G)return;let t=Ue(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(G),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 yr=/^avc[13]\.[0-9a-fA-F]{6}$/;function br(s){return yr.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 Le(s,e){let t=br(s);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var _r=250,Sr=3,kr=1e4,Ne=2500,Y=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 z({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");Le(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 K,o=[],i=await this.readControl(r,n,o);if(i?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");Le(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<kr),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=Sr){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 ${Ne}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${Ne}ms`))},Ne);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(Oe(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(()=>{})},_r)}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 ht=2500,gt=["av01.0.08M.08","avc1.42E01F","avc1.640028"],J=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:gt};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 vt(a.start(),this.opts.quicDeadlineMs??ht,"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:gt}}),!this.offer.webtransport)return null;let n=this.createWebTransportSession();try{await vt(n.start(),this.opts.quicDeadlineMs??ht,"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 Y(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 vt(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 Tr=1e4,X=class{constructor(e,t=Tr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=ie();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:u,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 Rr="video",Q=class{constructor(e,t=Rr){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 Ar="video";function wt(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,u=!1,d=()=>{if(c){for(let b of c.getVideoTracks())try{b.stop()}catch{}c=null}u&&(u=!1,t.onOverrideTrack(null))},f=new J(new X(s),e,{canvas:i,createWebRtcSession:t.createWebRtcSession??(()=>new Q(s,t.streamName??Ar)),createWebTransportSession:t.createWebTransportSession,onTransportChange:(b,h)=>{b==="webrtc"&&(d(),S()),t.onTransportChange?.(b,h)}}),p=null,l=()=>{p!==null&&(clearTimeout(p),p=null)},m=t.wtRetryBaseMs??2e3,w=t.wtRetryCapMs??3e4,y=null,_=0,S=()=>{if(a||y!==null||f.activeTransport==="webtransport")return;let b=Math.min(m*2**_,w);y=setTimeout(()=>{y=null,_+=1,f.retryWebTransport().then(h=>{if(!a){if(h)return console.debug(`[urun] webtransport upgraded in background (retry ${_})`),_=0,T(h);S()}}).catch(h=>{a||(console.debug(`[urun] webtransport background retry ${_} failed:`,h),S())})},b)},R=()=>{y!==null&&(clearTimeout(y),y=null)},T=async b=>{if(a||b.kind!=="webtransport")return;let h=t.firstMediaWarnMs??1e4;if(l(),p=setTimeout(()=>{a||f.activeTransport!=="webtransport"||console.warn(`[urun] webtransport established but no QUIC media after ${h}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)},h),await b.firstMedia,l(),a||f.activeTransport!=="webtransport"||typeof i.captureStream!="function")return;c=i.captureStream();let v=c.getVideoTracks()[0];v&&(u=!0,t.onOverrideTrack(v))};return(async()=>{let b=await f.connect();await T(b)})().catch(b=>{l(),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",b),S()}),{activeTransport:()=>f.activeTransport,dispose(){a=!0,l(),R(),d(),f.disconnect().catch(()=>{})}}}var Er=new Set;function qe(s){if(s.functionsUrl)return{functionsUrl:s.functionsUrl,orgId:s.orgId,apiKey:s.apiKey,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}var Cr="rpc",bt=3e4,Ir="rpc-resp";function Pr(s){return`${Ir}:${s}`}function Fe(){return ie()}function Mr(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 xr(s,e,t,r,n,o,i,a,c,u){let d=[],f=null,p=!1,l=null,m=!1,w,y,_=new Promise((g,M)=>{w=g,y=M});_.catch(()=>{});let S=i(),R=null,T=null,b=null,h=null,v=!0,I=()=>{b&&(clearTimeout(b),b=null),h&&(h(),h=null)},E=!1,j=()=>{E||!m||(E=!0,s.set({rpc:{[e]:null}}))},A=()=>{v=!1,I(),R?.(),R=null,T?.(),T=null,a?.removeEventListener("abort",ze),S.dispose(),j()},x=()=>{if(f){if(d.length>0){let g=f;f=null,g.resolve({value:d.shift(),done:!1})}else if(l!==null){let g=f;f=null,g.reject(l)}else if(p){let g=f;f=null,g.resolve({value:void 0,done:!0})}}},xt=g=>{p||(d.push(g),x())},U=g=>{p||(l=g,p=!0,y(g),A(),x())},Ge=g=>{p||(p=!0,w(g),A(),x())},ze=()=>{let g=a?.reason;U(g instanceof te?g:new re(e))},Dt=g=>{if(!(p||!g||typeof g!="object"))switch(j(),g.t){case"delta":typeof g.delta=="string"&&xt(g.delta);break;case"response":Ge(g.body);break;case"error":{let{message:M,code:L}=Mr(g.body);U(new te(M,{requestId:e,code:g.code??L}));break}}},Ot=()=>{let g=S.messages()[Symbol.asyncIterator]();R=()=>{g.return?.(void 0)};let M=()=>{v&&g.next().then(L=>{if(v){if(L.done){p||Ge(void 0);return}Dt(L.value),M()}},L=>{v&&U(L)})};M()},Ye=()=>{if(!m){if(m=!0,a){if(a.aborted){U(new re(e));return}a.addEventListener("abort",ze,{once:!0})}T=c?.(g=>U(g))??null,Ot(),s.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:o}}}),u&&u>0&&!s.synced&&(b=setTimeout(()=>{b=null,!p&&!s.synced&&U(new ve(u,e))},u),h=s.onSynced(()=>I()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Ye(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(l!==null){let g=l;return l=null,Promise.reject(g)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((g,M)=>{f={resolve:g,reject:M}})},return(){return p||(p=!0,w(void 0),A()),Promise.resolve({value:void 0,done:!0})},throw(g){return p||(p=!0,y(g),A()),Promise.reject(g)}}}},body:_,start:Ye}}function yt(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 Dr(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=yt(o);c&&(a.rt=c);let u=yt(i);return u&&(a.br=u),a}var We=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=Dr(t,this._name),n=r?.br;if(n?.by==="runtime")throw new we(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??xe;return mt(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 st;_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=tt(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Ie(()=>this.recover()),this._activity=Ce({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new $({onPhase:i=>this.onPhase(i),hint:()=>this.doc(ke).get(Te)??this.doc("control").get(Re),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 et({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 ee,i=new oe({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new s(e,o,i,qe(t),H({...t,baseUrl:r.baseUrl}));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),ne()&&await se();let c=t.getAccessToken,u=c?async()=>await c()??n:n;return a.setDocTransport({wsUrl:r.wsUrl,token:u}),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 _e(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 W(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 D(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new D(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 We(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 it(e,this._sessionId,Er.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=ot(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=rt(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",n=`${t}\0${r}\0${this._sessionId}`;n!==this._docEndpointKey&&(this._docEndpointKey=n,this.connectDocs(nt({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=Fe(),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 ge(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(Cr),a=Pr(e);return xr(i,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??bt)}requestStream(e,t={}){let r=Fe();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Fe(),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=wt(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 B)}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 ye)}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 _t(s){return`urun:logical:v1:${s.orgId}:${s.app}:${s.functionName}`}function je(){try{return globalThis.sessionStorage??null}catch{return null}}function St(s){let e=je();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 kt(s,e){let t=je();if(t)try{t.setItem(s,JSON.stringify({logicalId:e.logicalId}))}catch{}}function me(s){let e=je();if(e)try{e.removeItem(s)}catch{}}var Or=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Ur(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(!(Or.has(r)||typeof r!="string"))return n=>{let o=n??{},i=_t({orgId:e.orgId,app:s,functionName:r}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,c=a(),u=e.jwt,d=e.getAccessToken?async h=>{let v=await e.getAccessToken(h);return v&&(u=v),v}:void 0,f={...e,getAccessToken:d},p=new ee,l=new oe({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c}),m=new Z(c,p,l,qe(f),H(f)),w,y,_=new Promise(h=>{y=h}),S=h=>{w=h,y({status:"ready",handle:h})};m.setEndHandler(async()=>{let h=w?{status:"ready",handle:w}:await _;if(h.status==="unavailable")throw new B("[urun] session allocation failed before a releasable request was created",{cause:h.cause});let v=h.handle;return me(i),Qe({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider})});let R=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??St(i)?.logicalId,priority:e.priority,onAdmission:E=>l.reportAdmission(E),onRequest:S}),I=d?await d()??void 0:e.jwt;return e.sessionKey||kt(i,{logicalId:v.sessionId}),m.setSessionId(v.sessionId),m.setArtifactsAuth(H({...f,baseUrl:v.baseUrl})),l.setEndsAt(v.endsAt),{url:v.wsUrl,sessionId:v.sessionId,jwt:I,iceServers:v.response.ice_servers,endsAt:v.endsAt}},T,b=d?async()=>await d()??T:()=>T;if(l.setConnectionResolver(async()=>{let h=await R(a());return T=h.jwt,h}),l.on("connected",()=>{l.multiplexer&&p.setTarget(l.multiplexer);let h=l.connectedUrl;h&&m.setDocTransport({wsUrl:h,token:b})}),(async()=>{let h;try{h=await R(c)}catch(v){console.error(`[urun] Failed to create session for ${r}:`,v),me(i);let I=v instanceof Error?v:new Error(String(v)),E=v instanceof be?v.httpStatus:void 0;l.reportAllocationFailure(I,E),y({status:"unavailable",cause:v});return}l.setAuth({jwt:h.jwt,authProvider:e.authProvider,orgId:e.orgId}),l.setConnection({url:h.url,sessionId:h.sessionId,iceServers:h.iceServers}),ne()&&await se(),T=h.jwt,m.setDocTransport({wsUrl:h.url,token:b}),await l.connect({app:s,functionName:r,args:o}),m.negotiateMediaTransport({allowWebTransport:e.allowWebTransport})})().catch(h=>{console.error(`[urun] Failed to connect session for ${r}:`,h)}),e.releaseOnLeave!==!1){let h=Pe(()=>{if(l.leaveLeg()||l.connectedUrl!==null)return;let A=w;A&&(me(i),Se({baseUrl:A.baseUrl,requestId:A.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))});m.onDisconnect(h);let v,I,E=!1,j=()=>{E||(E=!0,v?.(),I?.())};_.then(A=>{A.status!=="ready"||E||(v=Me(()=>w!==void 0))}),I=m.onPhase(A=>{let x=A?.name;(x==="ended"||x==="expired"||x==="error")&&j()}),E&&I(),m.onDisconnect(j)}return m}}})}var Tt="https://api.urun.sh",O=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Lr(s,e={}){if(!s)throw new O("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=N(e.baseUrl??Tt),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(p){throw new O(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let i={};try{i=await o.json()}catch{}if(!o.ok){let p=typeof i.message=="string"?i.message:`HTTP ${o.status}`;throw new O(`[urun] client token mint failed: ${p}`,o.status)}let a=typeof i.token=="string"?i.token:"",c=typeof i.org_id=="string"?i.org_id:"",u=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 O("[urun] client token mint returned no token (control-plane contract violation)",o.status);let f=Number.isFinite(u)?new Date(u):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:f,orgId:c}}var Rt=3e4,At="stream:",Be=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=`${At}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${At}${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 ${Rt}ms`)))},Rt);this._pendingRpc.set(o,{resolve:r,reject:n,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Nr(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 Je(n);return new Be(n,o)}var Fr='video/mp4; codecs="avc1.42E01E"';function Wr(s,e){let t=e?.codec??Fr,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 p;try{p=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 l=s.getReader();function m(){return p.updating?new Promise(y=>{p.addEventListener("updateend",()=>y(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:y,value:_}=await l.read();if(y){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{p.appendBuffer(_)}catch(S){if(S instanceof DOMException&&S.name==="QuotaExceededError"){let R=p.buffered;if(R.length>0){let T=R.start(R.length-1);p.remove(0,T),await m(),p.appendBuffer(_)}else throw S}else throw S}}}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),u=c.getTracks(),d=0,f=u.length;if(f===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{d++,d>=f&&URL.revokeObjectURL(o)});return c}function qr(s){return s.status.startsWith("pending_")}var fe=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 Et(s){let e=[];return s.audio&&e.push("audio"),s.video&&e.push("video"),e.join("+")}function jr(s,e){return e==="audio"?s.getAudioTracks():s.getVideoTracks()}function Br(s,e){let t=s.getTracks();if(t.length===1&&t[0]===e)return s;try{return new MediaStream([e])}catch{return s}}function $e(s,e){for(let t of[...s.lostListeners])try{t(e)}catch{}}var he=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,$e(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 fe;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(${Et(r)}) failed`,c=i instanceof Error?i.message:String(i);for(let u of[...this.claims.values()])if(this.claims.delete(u.kind),u.released=!0,u!==e){let d=new Error(`${a} \u2014 ${u.kind} capture lost: ${c||i}`);d.cause=i,$e(u,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=jr(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(${Et(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===e)throw c;$e(i,c);continue}if(i.track=a,i.stream=Br(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}},$r=null;function Hr(){return $r??=new he}var Ct="input",Vr=30;function Kr(s){let e=s.now??Date.now,t=s.field??Ct,r=1e3/Math.max(s.hz??30,.001),n=new Set,o=0,i=0,a=0,c=0,u,d=null,f=!1,p=()=>{if(f)return;u=e(),c+=1;let m={keys:[...n],buttons:o,pointer:{x:i,y:a},seq:c,at:u};try{s.awareness.setLocalStateField(t,m)}catch{}},l=()=>{if(f)return;let m=e();if(u===void 0||m-u>=r){d&&(clearTimeout(d),d=null),p();return}if(d)return;let w=Math.max(r-(m-u),0);d=setTimeout(()=>{d=null,p()},w),d.unref?.()};return{keyDown(m){let w=String(m).toLowerCase();n.has(w)||(n.add(w),l())},keyUp(m){let w=String(m).toLowerCase();n.delete(w)&&l()},setButtons(m){let w=Number.isFinite(m)?Number(m):0;w!==o&&(o=w,l())},movePointer(m,w){let y=Number.isFinite(m)?Number(m):0,_=Number.isFinite(w)?Number(w):0;y===0&&_===0||(i+=y,a+=_,l())},heldKeys(){return[...n]},clear(){f||(n.clear(),o=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(f)return;let m=n.size>0||o!==0;n.clear(),o=0,d&&(clearTimeout(d),d=null),m&&p(),f=!0}}}var Gr=1024,zr=.92,Yr=262144,Jr=256e3,He=[.9,.8,.7,.6,.5],It=.8,Xr=8;function Ke(s,e,t){if(!(s>0)||!(e>0))throw new Error(`reference image has no pixels (${s}x${e})`);let r=Math.min(1,t/Math.max(s,e));return{width:Math.max(1,Math.round(s*r)),height:Math.max(1,Math.round(e*r))}}async function Qr(s){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(s,{imageOrientation:"from-image"})}async function Mt(s,e,t){let r=await new Promise(n=>{s.toBlob(n,e,e==="image/jpeg"?t:void 0)});if(!r)throw new Error(`could not encode the reference image as ${e}`);return r}function Pt(s,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${s} -> ${e} bytes`)}async function Ve(s,e,t,r,n){let o=document.createElement("canvas");o.width=e,o.height=t;let i=o.getContext("2d");if(!i)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(i.fillStyle="#fff",i.fillRect(0,0,e,t)),i.drawImage(s,0,0,e,t),await Mt(o,r,n)}async function Zr(s,e,t,r){let{width:n,height:o}=e,i=await Ve(s,n,o,t,r);if(i.size<=256e3)return{blob:i,width:n,height:o};if(t==="image/jpeg"){for(let c of He)if(!(c>=r)&&(i=await Ve(s,n,o,t,c),i.size<=256e3))return Pt(`quality ${r} -> ${c}`,i.size),{blob:i,width:n,height:o}}let a=t==="image/jpeg"?He[He.length-1]:r;for(let c=0;c<Xr;c++)if(n=Math.max(16,Math.round(n*It)),o=Math.max(16,Math.round(o*It)),i=await Ve(s,n,o,t,a),i.size<=256e3)return Pt(`downscaled to ${n}x${o} @ q${a}`,i.size),{blob:i,width:n,height:o};throw new Error(`this image cannot be sent: even at ${n}x${o} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function en(s,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:o}=e,i=await Qr(s);try{let a=Ke(i.width,i.height,t),c=await Zr(i,a,r,n);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:r,width:c.width,height:c.height,source:o}}finally{i.close()}}function tn(s){let e=s instanceof Error?s.name:"",t=s instanceof Error?s.message:String(s);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function rn(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function nn(s,e){let t=s.videoWidth,r=s.videoHeight;if(!(t>0)||!(r>0))throw new Error("the camera has not shown a frame yet");let{maxSize:n=1024,type:o="image/jpeg",quality:i=.92}=e??{},a=Ke(t,r,n),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let u=c.getContext("2d");if(!u)throw new Error("could not prepare the reference image (no 2d canvas context)");o==="image/jpeg"&&(u.fillStyle="#fff",u.fillRect(0,0,a.width,a.height)),u.drawImage(s,0,0,a.width,a.height);let d=await Mt(c,o,i);return{bytes:new Uint8Array(await d.arrayBuffer()),type:o,width:a.width,height:a.height,source:"camera"}}var sn=new Set(["w","a","s","d"]),q=(s,e)=>Math.min(e,Math.max(-e,s));function on(s={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:n=900,frameRelax:o=.06,maxPan:i=.12,maxLogZoom:a=.22}=s,c=0,u=0,d=0,f=null,p=new Set;return{pointerDelta(l,m){c=q(c-l*e,i),u=q(u-m*e,i)},keyDown(l){let m=l.toLowerCase();sn.has(m)&&p.add(m)},keyUp(l){p.delete(l.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let l=1-o;c*=l,u*=l,d*=l},tick(l){if(f===null){f=l;return}let m=Math.max(0,Math.min(100,l-f))/1e3;f=l,p.has("w")&&(d=q(d+t*m,a)),p.has("s")&&(d=q(d-t*m,a)),p.has("a")&&(c=q(c+r*m,i)),p.has("d")&&(c=q(c-r*m,i));let w=Math.exp(-m*1e3/n);c*=w,u*=w,d*=w},transform(){return{translateX:c,translateY:u,scale:Math.exp(d)}},isIdentity(l=5e-4){return Math.abs(c)<l&&Math.abs(u)<l&&Math.abs(d)<l},reset(){c=0,u=0,d=0,p.clear()}}}export{tr as ACTIVATION_COLD_BOOT_AFTER_MS,rr as ACTIVATION_DEGRADED_AFTER_MS,Te as ACTIVATION_HINT_PATH,er as ACTIVATION_STILL_AFTER_MS,Ee as ACTIVITY_DOM_EVENTS,ut as ACTIVITY_FIELD,pr as ACTIVITY_STAMP_MIN_INTERVAL_MS,$ as ActivationMonitor,Ur as App,Vt as BACKOFF_BASE_MS,Gt as BACKOFF_MAX_ATTEMPTS,Kt as BACKOFF_MAX_MS,he as CaptureController,fe as CaptureUnavailableError,O as ClientTokenError,Yr as DATA_CHANNEL_MESSAGE_CEILING,bt as DEFAULT_DOC_SYNC_TIMEOUT_MS,Tt as DEFAULT_GATEWAY_URL,Lt as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,zr as DEFAULT_REFERENCE_JPEG_QUALITY,Gr as DEFAULT_REFERENCE_MAX_SIZE,$t as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Xt as DERIVED_LEG_SEP,G as DGRAM_HEADER_BYTES,mr as FOREGROUND_COALESCE_MS,z as FrameReassembler,Vr as INPUT_PRESENCE_DEFAULT_HZ,Ct as INPUT_PRESENCE_FIELD,F as InvalidDurationError,Re as LEGACY_ACTIVATION_HINT_PATH,ke as PLATFORM_DOC_NAME,pe as PermanentLockedError,le as PinRequiresActiveTempError,Nt as ProduceAckTimeoutError,de as RecordingNotFoundError,W as RecordingsClient,C as RecordingsError,V as RecordingsUnauthorizedError,re as RequestAbortError,ye as RequestCancelledError,ve as RequestDocSyncError,te as RequestError,ge as RequestTimeoutError,ue as RetainNotTempError,ce as RuntimeArtifactNotFoundError,D as RuntimeArtifactsClient,k as RuntimeArtifactsError,ae as RuntimeArtifactsUnauthorizedError,Z as Session,be as SessionAllocationError,Ut as SessionEndError,B as SessionEndUnavailableError,Wt as SessionFailedError,we as StreamDirectionConflict,J as TransportNegotiator,jt as TransportSessionMismatchError,X as TransportSessionSignaling,lt as VISIBILITY_FIELD,Jr as WIRE_MESSAGE_BUDGET,ft as WT_CONTROL_FRAME_MAX,Q as WebRtcSession,Y as WebTransportSession,K as WtControlDecoder,at as activationHintFrom,rn as cameraCaptureAvailable,nn as captureStillFromVideo,zt as computeBackoffDelay,Ce as createActivityTracker,on as createCameraWarp,Lr as createClientToken,Kr as createInputPresencePublisher,lr as createRecordingsClient,sr as createRuntimeArtifactsClient,Nr as createStore,Zt as derivedLegName,Qt as derivedLegRole,Ft as describeSessionFailure,Ht as describeSessionPhase,Oe as encodeWtControlFrame,Ke as fitWithin,Ae as isDurationString,qr as isPendingRecording,Yt as isRetryableSessionError,Bt as isWakingPhase,xe as mediaRecorderChunkSource,en as normalizeReferenceImage,dr as normalizeRetention,Me as observeLeaveConfirm,Ie as observePageLifecycle,Pe as observePageTeardown,Ue as parseDgramHeader,Jt as prewake,tn as referenceImageErrorMessage,Se as releaseSessionBeacon,qt as sessionFailureFromMediaError,Hr as sharedCaptureController,Wr as videoStream,_e as whenLive,vr as writeDgramHeader};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, i as ChannelMessage, j as ChannelMultiplexer, k as ChannelName, m as DOC_SYNC_WIRE_CONTRACT_VERSION, n as DeferredChannelMultiplexer, o as DeferredDocConnector, q as DocConnection, r as DocConnectionState, s as DocConnector, t as DocTokenSupplier, L as LoopbackStreamData,
|
|
1
|
+
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, i as ChannelMessage, j as ChannelMultiplexer, k as ChannelName, m as DOC_SYNC_WIRE_CONTRACT_VERSION, n as DeferredChannelMultiplexer, o as DeferredDocConnector, q as DocConnection, r as DocConnectionState, s as DocConnector, t as DocTokenSupplier, L as LoopbackStreamData, Z as SessionDocumentImpl, a3 as SessionStartOptions, aa as StreamDataTransport, ab as TransportSession, ac as TransportSessionOptions, ae as allocateSession, af as createPresence, ag as createWebsocketDocConnector, ah as deriveYjsServerUrl, ao as streamDataLabel, ap as transportStreamData } from './stream-data-TWBl_kh7.mjs';
|
|
2
2
|
import 'yjs';
|
|
3
3
|
import 'y-protocols/awareness';
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, i as ChannelMessage, j as ChannelMultiplexer, k as ChannelName, m as DOC_SYNC_WIRE_CONTRACT_VERSION, n as DeferredChannelMultiplexer, o as DeferredDocConnector, q as DocConnection, r as DocConnectionState, s as DocConnector, t as DocTokenSupplier, L as LoopbackStreamData,
|
|
1
|
+
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, i as ChannelMessage, j as ChannelMultiplexer, k as ChannelName, m as DOC_SYNC_WIRE_CONTRACT_VERSION, n as DeferredChannelMultiplexer, o as DeferredDocConnector, q as DocConnection, r as DocConnectionState, s as DocConnector, t as DocTokenSupplier, L as LoopbackStreamData, Z as SessionDocumentImpl, a3 as SessionStartOptions, aa as StreamDataTransport, ab as TransportSession, ac as TransportSessionOptions, ae as allocateSession, af as createPresence, ag as createWebsocketDocConnector, ah as deriveYjsServerUrl, ao as streamDataLabel, ap as transportStreamData } from './stream-data-TWBl_kh7.js';
|
|
2
2
|
import 'yjs';
|
|
3
3
|
import 'y-protocols/awareness';
|
|
4
4
|
|