@urun-sh/core 0.1.47 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{a as ne,b as B,f as se,i as $}from"./chunk-O7ZS2RQJ.mjs";var Se="session-api.prod.cloud.urun.sh",ve=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function N(n){return n.trim().replace(/\/+$/,"")}function oe(n,e){let t=[],r=s=>{if(!s)return;let o=N(s);o&&!t.includes(o)&&t.push(o)};r(n);for(let s of e??[])r(s);for(let s of Ee(n))r(s);return t}var be=120,ke=1e3,Re=3;function Ae(n){if(!n)return null;try{let e=new URL(n),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return N(`${e.origin}${t}`)}catch{return null}}async function ie(n){let e=oe(n.baseUrl,n.fallbackUrls),t=null,r=e.length>1;for(let s of e)try{return await Ie(s,n,{pollAttempts:be,retryAfterLimitMs:r?ke:void 0})}catch(o){if(t=o instanceof Error?o:new Error(String(o)),t instanceof A)throw t}throw t??new Error("[urun] session allocation failed")}async function Ie(n,e,t){let r,s,o,i=n,c=0,f=new Set;for(let p=0;p<t.pollAttempts;p++){s=o??await Y(e),o=void 0;let l=r?await fetch(`${i}/api/session-requests/${encodeURIComponent(r)}`,{headers:W(e,s)}):await fetch(`${i}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...W(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(Te(e))});if(!r&&(l.status===307||l.status===308)){let h=Ae(l.headers.get("location"));if(h&&h!==i&&c<Re){c+=1,i=h;continue}throw new Error(`[urun] session create redirected from ${i} without a usable target`)}let a=await ce(l);if(l.ok&&(a.status==="allocated"||!a.status&&!!a.session_id)&&!!a.session_id){let h=a.session_id;if(!a.ws_url)throw new A(`[urun] gateway allocated session ${h} without ws_url`);if(!ue(a.ws_url))throw new A(`[urun] gateway allocated session ${h} with non-absolute ws_url`);return{baseUrl:i,sessionId:h,wsUrl:a.ws_url,response:a}}if(l.status===202||a.status==="pending"||a.status==="queued"||a.queued){if(r=a.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");await xe(Pe(l,a,t.retryAfterLimitMs));continue}if((l.status===401||l.status===403)&&e.getAccessToken){let h=s??"";f.add(h);let w=await Y(e,{forceRefresh:!0,reason:"unauthorized"});if(w&&!f.has(w)){o=w,r=void 0;continue}}let g=a.error_message||a.error_code||`HTTP ${l.status}`;throw new Error(`[urun] session allocation failed at ${i}: ${g}`)}throw new Error(`[urun] timed out waiting for session allocation at ${i}`)}function W(n,e){let t={"X-Tenant-Id":n.orgId,"X-Auth-Provider":n.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function Y(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function Te(n){return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey}}async function ae(n){let e=oe(n.baseUrl,n.fallbackUrls),t=null;for(let r of e)try{let s={baseUrl:r,app:"",functionName:"",orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider,idempotencyKey:""},o=await Y(s),i=await fetch(`${N(r)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,{headers:W(s,o)});if(!i.ok)throw new Error(`[urun] viewer-connect for ${n.sessionId} failed: HTTP ${i.status}`);let c=await ce(i);if(!c.ws_url||!ue(c.ws_url))throw new A(`[urun] viewer-connect returned no usable ws_url for ${n.sessionId}`);return{baseUrl:N(r),sessionId:n.sessionId,wsUrl:c.ws_url,response:c}}catch(s){if(t=s instanceof Error?s:new Error(String(s)),t instanceof A)throw t}throw t??new Error("[urun] viewer-connect failed")}async function ce(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function Pe(n,e,t){let r=Number(n.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??r),o=t??1e4;return Number.isFinite(s)&&s>0?Math.min(s*1e3,o):1e3}function xe(n){return new Promise(e=>setTimeout(e,n))}var A=class extends Error{};function ue(n){try{let e=new URL(n);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function Ee(n){try{return new URL(n).hostname!==Se?[]:ve}catch{return[]}}import*as x from"yjs";var de=Symbol("urun:doc:remote"),Oe=Symbol("urun:doc:local");function I(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}var F="$bytes";function Ce(n){return n instanceof Uint8Array||n instanceof ArrayBuffer}function Ue(n){if(!I(n))return!1;let e=Object.keys(n);return e.length===1&&e[0]===F&&typeof n[F]=="string"}function Me(n){return n instanceof ArrayBuffer?new Uint8Array(n):n}function De(n){if(typeof Buffer<"u")return Buffer.from(n).toString("base64");let e="";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return btoa(e)}function qe(n){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(n,"base64"));let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function J(n){if(Ce(n))return{[F]:De(Me(n))};if(Array.isArray(n))return n.map(J);if(I(n)){let e={};for(let[t,r]of Object.entries(n))e[t]=J(r);return e}return n}function E(n){if(Ue(n))return qe(n[F]);if(Array.isArray(n))return n.map(E);if(I(n)){let e={};for(let[t,r]of Object.entries(n))e[t]=E(r);return e}return n}function H(n,e){let t={...n};for(let r of Object.keys(e)){let s=e[r],o=t[r];I(s)&&I(o)?t[r]=H(o,s):t[r]=s}return t}var pe=Symbol("urun:doc:path-absent");function Le(n,e){let t=e.split("."),r=n;for(let s of t){if(r===null||typeof r!="object"||!(s in r))return pe;r=r[s]}return r}function le(n){return n===void 0?n:JSON.parse(JSON.stringify(n))}var K=class{_doc=new x.Doc;_root=this._doc.getMap("session");_listeners=new Set;_key;_sessionId;_transport;_transportUnsubs=[];_synced;_pendingPatches=[];_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();_updateHandler=(e,t)=>{t!==de&&this._transport?.sendDocSync(this._key,e)};constructor(e,t,r){this._key=e,this._sessionId=t,this._transport=r??null,this._synced=this._transport===null,this._root.observeDeep(this._observer),this._doc.on("update",this._updateHandler),this._transport&&(this._transportUnsubs.push(this._transport.onDocSync(this._key,s=>this.applyRemote(s)),this._transport.onDocSyncReady(()=>this.sendHello())),this._transport.isOpen&&this.sendHello())}setSessionId(e){this._sessionId=e}get synced(){return this._synced}onSynced(e){return this._synced?(e(),()=>{}):(this._syncWaiters.add(e),()=>this._syncWaiters.delete(e))}set(e){if(e=J(e),!this._synced){this._pendingPatches.push(le(e)),this.notify();return}this.applyPatch(e)}get(e,t){let r=this.snapshot();if(!e)return E(r);let s=Le(r,e);return s===pe?t:E(s)}on(e,t){return this._listeners.add(t),()=>this._listeners.delete(t)}text(e){let t=this._texts.get(e);return t||(t=new V(this._doc.getText(`text:${e}`)),this._texts.set(e,t)),t}dispose(){this._root.unobserveDeep(this._observer),this._doc.off("update",this._updateHandler);for(let e of this._transportUnsubs)e();this._transportUnsubs=[],this._transport=null,this._listeners.clear(),this._syncWaiters.clear();for(let e of this._texts.values())e.dispose();this._texts.clear(),this._doc.destroy()}sendHello(){this._transport&&this._transport.sendDocSync(this._key,x.encodeStateAsUpdate(this._doc))}applyRemote(e){if(x.applyUpdate(this._doc,e,de),!this._synced){this._synced=!0;let t=this._pendingPatches.splice(0);for(let s of t)this.applyPatch(s);let r=[...this._syncWaiters];this._syncWaiters.clear();for(let s of r)s()}}applyPatch(e){this._doc.transact(()=>{let t=this._root.toJSON();for(let[r,s]of Object.entries(e)){let o=t[r],i=I(s)&&I(o)?H(o,s):le(s);JSON.stringify(i)!==JSON.stringify(o)&&this._root.set(r,i)}},Oe)}snapshot(){let e=this._root.toJSON();for(let t of this._pendingPatches)e=H(e,t);return e}notify(){let e=E(this.snapshot());for(let t of this._listeners)t(e)}},V=class{constructor(e){this._ytext=e;this._observer=t=>{for(let r of t.delta)if(typeof r.insert=="string"&&r.insert.length>0){let s=r.insert;for(let o of this._delta)o(s)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(e){e.length!==0&&this._ytext.insert(this._ytext.length,e)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(e,t){return this._delta.add(t),()=>this._delta.delete(t)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};var y=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},O=class extends y{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},C=class extends y{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},U=class extends Error{stream;owner;attempted;constructor(e,t,r){super(`[urun] stream "${e}" is already produced by the ${t}; this (${r}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=r,Object.setPrototypeOf(this,new.target.prototype)}},k=class extends y{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},M=class extends y{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}};var je=new Set,Be="rpc",$e="llm",he=3e4,Ne="llm-resp";function Fe(n){return`${Ne}:${n}`}function z(){return se()}function Ke(n){if(n&&typeof n=="object"){let e=n.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof n=="string"?n:JSON.stringify(n)}}function Ge(n,e,t,r,s,o,i,c,f){let p=[],l=null,a=!1,d=null,g=!1,h,w,_=new Promise((u,b)=>{h=u,w=b});_.catch(()=>{});let S=o(),m=null,v=null,R=null,q=null,L=!0,Z=()=>{R&&(clearTimeout(R),R=null),q&&(q(),q=null)},j=()=>{L=!1,Z(),m?.(),m=null,v?.(),v=null,i?.removeEventListener("abort",te),S.dispose(),g&&n.set({requests:{[e]:null}})},G=()=>{if(l){if(p.length>0){let u=l;l=null,u.resolve({value:p.shift(),done:!1})}else if(d!==null){let u=l;l=null,u.reject(d)}else if(a){let u=l;l=null,u.resolve({value:void 0,done:!0})}}},we=u=>{a||(p.push(u),G())},T=u=>{a||(d=u,a=!0,w(u),j(),G())},ee=u=>{a||(a=!0,h(u),j(),G())},te=()=>T(new k(e)),_e=u=>{if(!(a||!u||typeof u!="object"))switch(u.t){case"delta":typeof u.delta=="string"&&we(u.delta);break;case"response":ee(u.body);break;case"error":{let{message:b,code:P}=Ke(u.body);T(new y(b,{requestId:e,code:u.code??P}));break}}},ye=()=>{let u=S.messages()[Symbol.asyncIterator]();m=()=>{u.return?.(void 0)};let b=()=>{L&&u.next().then(P=>{if(L){if(P.done){a||ee(void 0);return}_e(P.value),b()}},P=>{L&&T(P)})};b()},re=()=>{if(!g){if(g=!0,i){if(i.aborted){T(new k(e));return}i.addEventListener("abort",te,{once:!0})}v=c?.(u=>T(u))??null,ye(),n.set({requests:{[e]:{payload:t,consumer_id:r,stream:s}}}),f&&f>0&&!n.synced&&(R=setTimeout(()=>{R=null,!a&&!n.synced&&T(new C(f,e))},f),q=n.onSynced(()=>Z()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(re(),p.length>0)return Promise.resolve({value:p.shift(),done:!1});if(d!==null){let u=d;return d=null,Promise.reject(u)}return a?Promise.resolve({value:void 0,done:!0}):new Promise((u,b)=>{l={resolve:u,reject:b}})},return(){return a||(a=!0,h(void 0),j()),Promise.resolve({value:void 0,done:!0})},throw(u){return a||(a=!0,w(u),j()),Promise.reject(u)}}}},body:_,start:re}}function We(n,e){return[`streams/${n}/${e}`,`streams/${n}/*`]}function Ye(n,e){return`streams/${n}/${e??"*"}`}function fe(n){if(n&&typeof n=="object"){let{epoch:e,by:t}=n,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function Je(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:o,br:i}=r,c={};(s==="audio"||s==="video")&&(c.kind=s);let f=fe(o);f&&(c.rt=f);let p=fe(i);return p&&(c.br=p),c}var X=class{constructor(e,t,r,s){this._name=e;this._transport=t;this._laneDoc=r;this._controlDoc=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_laneDoc;_controlDoc;_track=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_laneUnsubs=[];_laneSeen=new Map;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,s=!1,o={push(c){if(!s)if(r){let f=r;r=null,f({value:c,done:!1})}else t.push(c)},end(){if(s=!0,r){let c=r;r=null,c({value:void 0,done:!0})}}};e._messageConsumers.add(o);let i=()=>{s=!0,e._messageConsumers.delete(o)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.resolve({value:void 0,done:!0}):new Promise(c=>{r=c})},return(){return i(),Promise.resolve({value:void 0,done:!0})}}}}}_ensureSubscribed(){if(!(this._subscribed||this._disposed)&&(this._subscribed=!0,this._transport.subscribeStream(this._name),!!this._laneDoc))for(let e of We(this._name,this._transport.consumerId)){let t=this._laneDoc(e);this._laneSeen.set(e,0);let r=s=>this._drainLane(e,s);r(t.get()),this._laneUnsubs.push(t.on("change",r))}}_drainLane(e,t){let r=t.messages;if(!Array.isArray(r))return;let s=this._laneSeen.get(e)??0;for(;s<r.length;s++){let o=r[s];this._replay.push(o);for(let i of this._messageConsumers)i.push(o)}this._laneSeen.set(e,s)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._track}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=Je(t,this._name),s=r?.br;if(s?.by==="runtime")throw new U(this._name,"runtime","browser");if(s)return;let o={br:{epoch:1}};r?.rt&&(o.rt=r.rt);let i=r?.kind??e;i&&(o.kind=i),t.set({streams:{[this._name]:o}})}async attach(e){this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._claimBrowserProducer(),!this._laneDoc)throw new Error("[urun] stream.emit requires the session doc transport (no laneDoc wired)");let r=Ye(this._name,t.to),s=this._laneDoc(r),o=s.get("messages"),i=Array.isArray(o)?[...o]:[];i.push(e),s.set({messages:i})}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)}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._subscribed&&this._transport.unsubscribeStream(this._name);for(let e of this._laneUnsubs)e();this._laneUnsubs=[];for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0});let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},D=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_activeRequests=new Set;constructor(e,t,r){this._sessionId=e,this._multiplexer=t,this._transport=r,this._wireControlDocIncarnation()}_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 ae({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,o=new B,i=new $({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),c=new n(e,o,i);return i.on("connected",()=>{i.multiplexer&&o.setTarget(i.multiplexer)}),i.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),await i.connect({role:"viewer"}),c}get id(){return this._sessionId}get phase(){return this._transport.phase}onPhase(e){return e(this._transport.phase),this._transport.on("phase",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)}stream(e){let t=this._streams.get(e);return t||(t=new X(e,this._transport,r=>this.doc(r),()=>this.doc("control")),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new K(e,this._sessionId,je.has(e)?null:this._transport),this._docs.set(e,t)),t}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=this.doc(Be),s=z();return new Promise((o,i)=>{let c=!1,f=null,p=null,l=null,a=()=>{p&&(clearTimeout(p),p=null),f&&(f(),f=null),l&&(this._activeRequests.delete(l),l=null),t.signal?.removeEventListener("abort",g),r.set({requests:{[s]:null}})},d=w=>{c||(c=!0,a(),w())},g=()=>d(()=>i(new k(s)));if(t.signal){if(t.signal.aborted){c=!0,i(new k(s));return}t.signal.addEventListener("abort",g,{once:!0})}let h=w=>{let S=w.responses?.[s];if(S==null)return;let m=S;if(m.error!==void 0&&m.error!==null){let v=typeof m.error=="string"?m.error:JSON.stringify(m.error);d(()=>i(new y(v,{requestId:s,code:m.code})))}else d(()=>o(m.result))};f=r.on("change",h),l=w=>d(()=>i(w)),this._activeRequests.add(l),typeof t.timeout=="number"&&t.timeout>=0&&(p=setTimeout(()=>d(()=>i(new O(t.timeout,s))),t.timeout)),r.set({requests:{[s]:{payload:e}}}),h(r.get())})}_consumeResponse(e,t,r,s,o){let i=this.doc($e);return Ge(i,e,t,this._transport.consumerId,r,()=>this.stream(Fe(e)),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??he)}requestStream(e,t={}){let r=z();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=z(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}disconnect(){let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new M)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};var He=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Ve(n,e){return new Proxy({},{get(t,r){if(!(He.has(r)||typeof r!="string"))return s=>{let o=s??{},i=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,c=i(),f=new B,p=new $({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c}),l=new D(c,f,p),a=async d=>{let g=await ie({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:d}),h=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return l.setSessionId(g.sessionId),{url:g.wsUrl,sessionId:g.sessionId,jwt:h,iceServers:g.response.ice_servers}};return p.setConnectionResolver(()=>a(i())),p.on("connected",()=>{p.multiplexer&&f.setTarget(p.multiplexer)}),(async()=>{let d=await a(c);p.setAuth({jwt:d.jwt,authProvider:e.authProvider,orgId:e.orgId}),p.setConnection({url:d.url,sessionId:d.sessionId,iceServers:d.iceServers}),await p.connect({app:n,functionName:r,args:o})})().catch(d=>{console.error(`[urun] Failed to connect session for ${r}:`,d)}),l}}})}var me=3e4,ge="stream:",Q=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let o=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(o.timer),s.error?o.reject(new Error(s.error)):o.resolve(s.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${ge}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${ge}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let o=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),s(new Error(`RPC request "${e}" timed out after ${me}ms`)))},me);this._pendingRpc.set(o,{resolve:r,reject:s,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function ze(n){let r=`${n.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(n.orgId)}`,s=new WebSocket(r);(n.jwt||n.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:n.orgId,jwt:n.jwt,authProvider:n.authProvider,apiKey:n.apiKey}))});let o=new ne(s);return new Q(s,o)}var Xe='video/mp4; codecs="avc1.42E01E"';function Qe(n,e){let t=e?.codec??Xe,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let s=new MediaSource,o=URL.createObjectURL(s);r.src=o,s.addEventListener("sourceopen",()=>{let d;try{d=s.addSourceBuffer(t)}catch(_){throw _ instanceof DOMException&&_.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).`):_}let g=n.getReader();function h(){return d.updating?new Promise(_=>{d.addEventListener("updateend",()=>_(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:_,value:S}=await g.read();if(_){await h(),s.readyState==="open"&&s.endOfStream();return}await h();try{d.appendBuffer(S)}catch(m){if(m instanceof DOMException&&m.name==="QuotaExceededError"){let v=d.buffered;if(v.length>0){let R=v.start(v.length-1);d.remove(0,R),await h(),d.appendBuffer(S)}else throw m}else throw m}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}w()}),r.play().catch(()=>{});let i=r,c=i.captureStream??i.mozCaptureStream;if(!c)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let f=c.call(r),p=f.getTracks(),l=0,a=p.length;if(a===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let d of p)d.addEventListener("ended",()=>{l++,l>=a&&URL.revokeObjectURL(o)});return f}export{Ve as App,he as DEFAULT_DOC_SYNC_TIMEOUT_MS,k as RequestAbortError,M as RequestCancelledError,C as RequestDocSyncError,y as RequestError,O as RequestTimeoutError,D as Session,U as StreamDirectionConflict,ze as createStore,Qe as videoStream};
1
+ import{a as ye,b as W,c as K,e as z,f as we,h as _e,j as G,k as Se,l as ve,m as ke,n as be,o as Re}from"./chunk-2TYDFOWI.mjs";var w=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)}},U=class extends w{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},J=class extends w{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Y=class extends w{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)}},V=class extends w{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)}},H=class extends w{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)}},A=class extends w{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",n=400){super(e,{status:n,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function te(r){return/^(\d+[smhdw])+$/.test(r)}function Fe(r){if(r==="pin")return{action:"pin"};if(te(r))return{action:"retain",duration:r};throw new A(`[urun] recordings: "${r}" is not a duration or "pin"`)}function We(r,e,t){let n=t||e||`HTTP ${r}`;if(r===401)return new U(n,e??"unauthorized");if(r===404)return new J(n,e??"not_found");if(r===400)return new A(n,e??"bad_request",400);if(r===409)switch(e){case"retain_not_temp":return new Y(n,e);case"pin_requires_active_temp":return new V(n,e);case"permanent_locked":return new H(n,e)}return new w(n,{status:r,code:e??`http_${r}`})}var I=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let n=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(n)?n:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!te(t))throw new A(`[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 w("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let s=this._buildUrl(t,n.params),o=await this._resolveToken(),i=await this._fetch(s,e,o,n.body);if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await this._fetch(s,e,o,n.body))}if(!i.ok){let{code:a,message:m}=await this._readError(i);throw We(i.status,a,m)}return this._readJson(i)}_buildUrl(e,t){let n=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,i])=>`${encodeURIComponent(o)}=${encodeURIComponent(i)}`).join("&");return s&&(n+=`?${s}`),n}_fetch(e,t,n,s){let o={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(o["X-Auth-Provider"]=this._options.authProvider);let i={method:t,headers:o};return s!==void 0&&(o["Content-Type"]="application/json",i.body=JSON.stringify(s)),fetch(e,i)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new U("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let n=(await e.json()).error;if(n&&typeof n=="object"){let{code:s,message:o}=n;return{code:typeof s=="string"?s:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Ke(r){return new I(r)}var ze="session-api.prod.cloud.urun.sh",Ge=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function X(r){return r.trim().replace(/\/+$/,"")}function Te(r,e){let t=[],n=s=>{if(!s)return;let o=X(s);o&&!t.includes(o)&&t.push(o)};n(r);for(let s of e??[])n(s);for(let s of tt(r))n(s);return t}var Je=120,Ye=1e3,Ve=3;function He(r){if(!r)return null;try{let e=new URL(r),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return X(`${e.origin}${t}`)}catch{return null}}async function Pe(r){let e=Te(r.baseUrl,r.fallbackUrls),t=null,n=e.length>1;for(let s of e)try{return await Xe(s,r,{pollAttempts:Je,retryAfterLimitMs:n?Ye:void 0})}catch(o){if(t=o instanceof Error?o:new Error(String(o)),t instanceof R)throw t}throw t??new Error("[urun] session allocation failed")}async function Xe(r,e,t){let n,s,o,i=r,a=0,m=new Set;for(let p=0;p<t.pollAttempts;p++){s=o??await re(e),o=void 0;let l=n?await fetch(`${i}/api/session-requests/${encodeURIComponent(n)}`,{headers:ne(e,s)}):await fetch(`${i}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...ne(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(Qe(e))});if(!n&&(l.status===307||l.status===308)){let g=He(l.headers.get("location"));if(g&&g!==i&&a<Ve){a+=1,i=g;continue}throw new Error(`[urun] session create redirected from ${i} without a usable target`)}let d=await Ae(l);if(l.ok&&(d.status==="allocated"||!d.status&&!!d.session_id)&&!!d.session_id){let g=d.session_id;if(!d.ws_url)throw new R(`[urun] gateway allocated session ${g} without ws_url`);if(!Ie(d.ws_url))throw new R(`[urun] gateway allocated session ${g} with non-absolute ws_url`);return{baseUrl:i,sessionId:g,wsUrl:d.ws_url,response:d}}if(l.status===202||d.status==="pending"||d.status==="queued"||d.queued){if(n=d.request_id||n,!n)throw new Error("[urun] gateway queued session without request_id");await et(Ze(l,d,t.retryAfterLimitMs));continue}if((l.status===401||l.status===403)&&e.getAccessToken){let g=s??"";m.add(g);let y=await re(e,{forceRefresh:!0,reason:"unauthorized"});if(y&&!m.has(y)){o=y,n=void 0;continue}}let f=d.error_message||d.error_code||`HTTP ${l.status}`;throw new Error(`[urun] session allocation failed at ${i}: ${f}`)}throw new Error(`[urun] timed out waiting for session allocation at ${i}`)}function ne(r,e){let t={"X-Tenant-Id":r.orgId,"X-Auth-Provider":r.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function re(r,e){return r.getAccessToken?await r.getAccessToken(e)??void 0:r.jwt}function Qe(r){return{app:r.app,function:r.functionName,gpus:1,idempotency_key:r.idempotencyKey}}async function xe(r){let e=Te(r.baseUrl,r.fallbackUrls),t=null;for(let n of e)try{let s={baseUrl:n,app:"",functionName:"",orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider,idempotencyKey:""},o=await re(s),i=await fetch(`${X(n)}/api/sessions/${encodeURIComponent(r.sessionId)}/viewer-connect`,{headers:ne(s,o)});if(!i.ok)throw new Error(`[urun] viewer-connect for ${r.sessionId} failed: HTTP ${i.status}`);let a=await Ae(i);if(!a.ws_url||!Ie(a.ws_url))throw new R(`[urun] viewer-connect returned no usable ws_url for ${r.sessionId}`);return{baseUrl:X(n),sessionId:r.sessionId,wsUrl:a.ws_url,response:a}}catch(s){if(t=s instanceof Error?s:new Error(String(s)),t instanceof R)throw t}throw t??new Error("[urun] viewer-connect failed")}async function Ae(r){try{let e=await r.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function Ze(r,e,t){let n=Number(r.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??n),o=t??1e4;return Number.isFinite(s)&&s>0?Math.min(s*1e3,o):1e3}function et(r){return new Promise(e=>setTimeout(e,r))}var R=class extends Error{};function Ie(r){try{let e=new URL(r);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function tt(r){try{return new URL(r).hostname!==ze?[]:Ge}catch{return[]}}import*as Ce from"yjs";function T(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Q="$bytes";function nt(r){return r instanceof Uint8Array||r instanceof ArrayBuffer}function rt(r){if(!T(r))return!1;let e=Object.keys(r);return e.length===1&&e[0]===Q&&typeof r[Q]=="string"}function st(r){return r instanceof ArrayBuffer?new Uint8Array(r):r}function ot(r){if(typeof Buffer<"u")return Buffer.from(r).toString("base64");let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)}function it(r){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function se(r){if(nt(r))return{[Q]:ot(st(r))};if(Array.isArray(r))return r.map(se);if(T(r)){let e={};for(let[t,n]of Object.entries(r))e[t]=se(n);return e}return r}function M(r){if(rt(r))return it(r[Q]);if(Array.isArray(r))return r.map(M);if(T(r)){let e={};for(let[t,n]of Object.entries(r))e[t]=M(n);return e}return r}function Oe(r,e){let t={...r};for(let n of Object.keys(e)){let s=e[n],o=t[n];T(s)&&T(o)?t[n]=Oe(o,s):t[n]=s}return t}var Ee=Symbol("urun:doc:path-absent");function at(r,e){let t=e.split("."),n=r;for(let s of t){if(n===null||typeof n!="object"||!(s in n))return Ee;n=n[s]}return n}function ct(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}var ut=Symbol("urun:doc:local"),Z=class{_doc=new Ce.Doc;_root=this._doc.getMap("session");_awareness=new Se(this._doc);_listeners=new Set;_key;_sessionId;_connection=null;_connUnsub=null;_synced;_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();constructor(e,t,n){this._key=e,this._sessionId=t,this._root.observeDeep(this._observer),n?(this._connection=n(e,this._doc,this._awareness),this._synced=this._connection.synced,this._connUnsub=this._connection.onSync(s=>{s&&this._markSynced()}),this._synced&&this._markSynced()):this._synced=!0}get awareness(){return this._awareness}setSessionId(e){this._sessionId=e}get synced(){return this._synced}onSynced(e){return this._synced?(e(),()=>{}):(this._syncWaiters.add(e),()=>this._syncWaiters.delete(e))}set(e){e=se(e),this.applyPatch(e)}get(e,t){let n=this.snapshot();if(!e)return M(n);let s=at(n,e);return s===Ee?t:M(s)}on(e,t){return this._listeners.add(t),()=>this._listeners.delete(t)}text(e){let t=this._texts.get(e);return t||(t=new oe(this._doc.getText(`text:${e}`)),this._texts.set(e,t)),t}dispose(){this._root.unobserveDeep(this._observer),this._connUnsub?.(),this._connUnsub=null,this._connection?.destroy(),this._connection=null,this._listeners.clear(),this._syncWaiters.clear();for(let e of this._texts.values())e.dispose();this._texts.clear(),this._awareness.destroy(),this._doc.destroy()}_markSynced(){let e=[...this._syncWaiters];this._synced=!0,this._syncWaiters.clear();for(let t of e)t()}applyPatch(e){this._doc.transact(()=>{let t=this._root.toJSON();for(let[n,s]of Object.entries(e)){let o=t[n],i=T(s)&&T(o)?Oe(o,s):ct(s);JSON.stringify(i)!==JSON.stringify(o)&&this._root.set(n,i)}},ut)}snapshot(){return this._root.toJSON()}notify(){let e=M(this.snapshot());for(let t of this._listeners)t(e)}},oe=class{constructor(e){this._ytext=e;this._observer=t=>{for(let n of t.delta)if(typeof n.insert=="string"&&n.insert.length>0){let s=n.insert;for(let o of this._delta)o(s)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(e){e.length!==0&&this._ytext.insert(this._ytext.length,e)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(e,t){return this._delta.add(t),()=>this._delta.delete(t)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};var _=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},D=class extends _{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},j=class extends _{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},q=class extends Error{stream;owner;attempted;constructor(e,t,n){super(`[urun] stream "${e}" is already produced by the ${t}; this (${n}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=n,Object.setPrototypeOf(this,new.target.prototype)}},C=class extends _{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},L=class extends _{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}};var Ue="video/mp4";function ie(r,e={}){let t=e.timesliceMs??1e3,n=null,s=null,o=!1,i=(a,m,p)=>{let l=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!l)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let d=e.mimeType??(typeof l.isTypeSupported=="function"&&l.isTypeSupported(Ue)?Ue:void 0),c=new MediaStream([a]),f=new l(c,d?{mimeType:d}:void 0);n=f;let g=Promise.resolve();f.ondataavailable=y=>{let h=y.data;o||!h||h.size===0||(g=g.then(async()=>{let v=new Uint8Array(await h.arrayBuffer());o||m(v)}))},f.onstop=()=>{g.then(()=>{o||p()})},f.onerror=()=>{g.then(()=>{o||p()})},f.start(t)};return{start(a,m){if(n||o)return;let p=r.track();if(p){i(p,a,m);return}s=r.onTrack(l=>{!l||n||o||(s?.(),s=null,i(l,a,m))})},stop(){if(o)return;o=!0,s?.(),s=null;let a=n;if(n=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function dt(r){let e=r;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=r.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function Me(r,e){let t=null,n=!1,s=!1,o=new ReadableStream({pull(i){n||(n=!0,t=r(e),t.start(a=>{if(!s)try{i.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{i.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return dt(o)}var lt=new Set;function ue(r){if(r.functionsUrl)return{functionsUrl:r.functionsUrl,orgId:r.orgId,apiKey:r.apiKey,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}var pt="rpc",je=3e4,mt="rpc-resp";function gt(r){return`${mt}:${r}`}function ae(){return we()}function ft(r){if(r&&typeof r=="object"){let e=r.error;if(e&&typeof e=="object"){let{message:t,code:n}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof n=="string"?n:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof r=="string"?r:JSON.stringify(r)}}function ht(r,e,t,n,s,o,i,a,m,p){let l=[],d=null,c=!1,f=null,g=!1,y,h,v=new Promise((u,S)=>{y=u,h=S});v.catch(()=>{});let k=i(),b=null,O=null,E=null,B=null,N=!0,le=()=>{E&&(clearTimeout(E),E=null),B&&(B(),B=null)},pe=!1,me=()=>{pe||!g||(pe=!0,r.set({rpc:{[e]:null}}))},F=()=>{N=!1,le(),b?.(),b=null,O?.(),O=null,a?.removeEventListener("abort",fe),k.dispose(),me()},ee=()=>{if(d){if(l.length>0){let u=d;d=null,u.resolve({value:l.shift(),done:!1})}else if(f!==null){let u=d;d=null,u.reject(f)}else if(c){let u=d;d=null,u.resolve({value:void 0,done:!0})}}},$e=u=>{c||(l.push(u),ee())},P=u=>{c||(f=u,c=!0,h(u),F(),ee())},ge=u=>{c||(c=!0,y(u),F(),ee())},fe=()=>{let u=a?.reason;P(u instanceof _?u:new C(e))},Be=u=>{if(!(c||!u||typeof u!="object"))switch(me(),u.t){case"delta":typeof u.delta=="string"&&$e(u.delta);break;case"response":ge(u.body);break;case"error":{let{message:S,code:x}=ft(u.body);P(new _(S,{requestId:e,code:u.code??x}));break}}},Ne=()=>{let u=k.messages()[Symbol.asyncIterator]();b=()=>{u.return?.(void 0)};let S=()=>{N&&u.next().then(x=>{if(N){if(x.done){c||ge(void 0);return}Be(x.value),S()}},x=>{N&&P(x)})};S()},he=()=>{if(!g){if(g=!0,a){if(a.aborted){P(new C(e));return}a.addEventListener("abort",fe,{once:!0})}O=m?.(u=>P(u))??null,Ne(),r.set({rpc:{[e]:{args:t,respond_on:n,consumer_id:s,stream:o}}}),p&&p>0&&!r.synced&&(E=setTimeout(()=>{E=null,!c&&!r.synced&&P(new j(p,e))},p),B=r.onSynced(()=>le()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(he(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(f!==null){let u=f;return f=null,Promise.reject(u)}return c?Promise.resolve({value:void 0,done:!0}):new Promise((u,S)=>{d={resolve:u,reject:S}})},return(){return c||(c=!0,y(void 0),F()),Promise.resolve({value:void 0,done:!0})},throw(u){return c||(c=!0,h(u),F()),Promise.reject(u)}}}},body:v,start:he}}function De(r){if(r&&typeof r=="object"){let{epoch:e,by:t}=r,n={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(n.by=t),n}}function yt(r,e){let n=r.get("streams")?.[e];if(!n||typeof n!="object")return null;let{kind:s,rt:o,br:i}=n,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let m=De(o);m&&(a.rt=m);let p=De(i);return p&&(a.br=p),a}var ce=class{constructor(e,t,n,s){this._name=e;this._transport=t;this._streamData=n;this._controlDoc=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_track=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],n=null,s=!1,o={push(a){if(!s)if(n){let m=n;n=null,m({value:a,done:!1})}else t.push(a)},end(){if(s=!0,n){let a=n;n=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(o);let i=()=>{s=!0,e._messageConsumers.delete(o)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{n=a})},return(){return i(),Promise.resolve({value:void 0,done:!0})}}}}}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._transport.subscribeStream(this._name),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._track}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),n=yt(t,this._name),s=n?.br;if(s?.by==="runtime")throw new q(this._name,"runtime","browser");if(s)return;let o={br:{epoch:1}};n?.rt&&(o.rt=n.rt);let i=n?.kind??e;i&&(o.kind=i),t.set({streams:{[this._name]:o}})}async attach(e){this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");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??ie;return Me(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,n)=>{t===this._name&&e(n)})}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n?.delete(t),n?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._subscribed&&this._transport.unsubscribeStream(this._name),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0});let t=this._handlers.get("track");if(t)for(let n of t)n(e)}},$=class r{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new be;_streamData;_presence=null;_activeRequests=new Set;_recordingsAuth;_recordingsAccessor=null;constructor(e,t,n,s){this._sessionId=e,this._multiplexer=t,this._transport=n,this._recordingsAuth=s,this._streamData=_e(n),this._wireControlDocIncarnation()}_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 n=await xe({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,o=new W,i=new G({url:n.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:n.response.ice_servers}),a=new r(e,o,i,ue(t));return i.on("connected",()=>{i.multiplexer&&o.setTarget(i.multiplexer)}),i.setConnection({url:n.wsUrl,sessionId:e,iceServers:n.response.ice_servers}),K()&&await z(),a.setDocTransport({wsUrl:n.wsUrl,token:s}),await i.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}onPhase(e){return e(this._transport.phase),this._transport.on("phase",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 I(e);return this._recordingsAccessor={list:n=>t.list(n??this._sessionId),get:n=>t.get(n),retain:(n,s)=>t.retain(n,s),pin:n=>t.pin(n),unpin:n=>t.unpin(n),permanent:n=>t.permanent(n),delete:n=>t.delete(n)},this._recordingsAccessor}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let n of this._docs.values())n.setSessionId(e)}stream(e){let t=this._streams.get(e);return t||(t=new ce(e,this._transport,this._streamData,()=>this.doc("control")),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new Z(e,this._sessionId,lt.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Re(this.doc("control").awareness)),this._presence}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){this.connectDocs(ke({serverUrl:ve(e.wsUrl),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 n=ae(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;o=setTimeout(()=>s.abort(new D(a,n)),a)}let i=this._consumeResponse(n,e,!1,s.signal);return i.start(),i.body.finally(()=>{o&&clearTimeout(o)})}_consumeResponse(e,t,n,s,o){let i=this.doc(pt),a=gt(e);return ht(i,e,t,a,this._streamData.consumerId,n,()=>this.stream(a),s,m=>(this._activeRequests.add(m),()=>this._activeRequests.delete(m)),o??je)}requestStream(e,t={}){let n=ae();return this._consumeResponse(n,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let n=ae(),s=this._consumeResponse(n,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}disconnect(){let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new L)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};var wt=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function _t(r,e){return new Proxy({},{get(t,n){if(!(wt.has(n)||typeof n!="string"))return s=>{let o=s??{},i=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=i(),m=new W,p=new G({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),l=new $(a,m,p,ue(e)),d=async c=>{let f=await Pe({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:r,functionName:n,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:c}),g=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return l.setSessionId(f.sessionId),{url:f.wsUrl,sessionId:f.sessionId,jwt:g,iceServers:f.response.ice_servers}};return p.setConnectionResolver(()=>d(i())),p.on("connected",()=>{p.multiplexer&&m.setTarget(p.multiplexer)}),(async()=>{let c=await d(a);p.setAuth({jwt:c.jwt,authProvider:e.authProvider,orgId:e.orgId}),p.setConnection({url:c.url,sessionId:c.sessionId,iceServers:c.iceServers}),K()&&await z(),l.setDocTransport({wsUrl:c.url,token:c.jwt}),await p.connect({app:r,functionName:n,args:o})})().catch(c=>{console.error(`[urun] Failed to connect session for ${n}:`,c)}),l}}})}var qe=3e4,Le="stream:",de=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",n=>{let s;try{s=JSON.parse(typeof n.data=="string"?n.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let o=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(o.timer),s.error?o.reject(new Error(s.error)):o.resolve(s.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let n=`${Le}${e}`;return this._multiplexer.on(n,s=>{t(s)})}emit(e,t){let n=`${Le}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(n,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((n,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let o=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),s(new Error(`RPC request "${e}" timed out after ${qe}ms`)))},qe);this._pendingRpc.set(o,{resolve:n,reject:s,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function St(r){let n=`${r.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(r.orgId)}`,s=new WebSocket(n);(r.jwt||r.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:r.orgId,jwt:r.jwt,authProvider:r.authProvider,apiKey:r.apiKey}))});let o=new ye(s);return new de(s,o)}var vt='video/mp4; codecs="avc1.42E01E"';function kt(r,e){let t=e?.codec??vt,n=document.createElement("video");n.muted=!0,n.playsInline=!0;let s=new MediaSource,o=URL.createObjectURL(s);n.src=o,s.addEventListener("sourceopen",()=>{let c;try{c=s.addSourceBuffer(t)}catch(h){throw h instanceof DOMException&&h.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).`):h}let f=r.getReader();function g(){return c.updating?new Promise(h=>{c.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function y(){try{for(;;){let{done:h,value:v}=await f.read();if(h){await g(),s.readyState==="open"&&s.endOfStream();return}await g();try{c.appendBuffer(v)}catch(k){if(k instanceof DOMException&&k.name==="QuotaExceededError"){let b=c.buffered;if(b.length>0){let O=b.start(b.length-1);c.remove(0,O),await g(),c.appendBuffer(v)}else throw k}else throw k}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}y()}),n.play().catch(()=>{});let i=n,a=i.captureStream??i.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let m=a.call(n),p=m.getTracks(),l=0,d=p.length;if(d===0)n.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let c of p)c.addEventListener("ended",()=>{l++,l>=d&&URL.revokeObjectURL(o)});return m}function bt(r){return r.status.startsWith("pending_")}export{_t as App,je as DEFAULT_DOC_SYNC_TIMEOUT_MS,A as InvalidDurationError,H as PermanentLockedError,V as PinRequiresActiveTempError,J as RecordingNotFoundError,I as RecordingsClient,w as RecordingsError,U as RecordingsUnauthorizedError,C as RequestAbortError,L as RequestCancelledError,j as RequestDocSyncError,_ as RequestError,D as RequestTimeoutError,Y as RetainNotTempError,$ as Session,q as StreamDirectionConflict,Ke as createRecordingsClient,St as createStore,te as isDurationString,bt as isPendingRecording,ie as mediaRecorderChunkSource,Fe as normalizeRetention,kt as videoStream};
@@ -0,0 +1,11 @@
1
+ export { d as ChannelMessage, e as ChannelMultiplexer, f as ChannelName, D as DeferredChannelMultiplexer, h as DeferredDocConnector, i as DocConnection, j as DocConnector, m as LoopbackStreamData, F as SessionStartOptions, N as StreamDataTransport, T as TransportSession, O as TransportSessionOptions, U as createPresence, V as createWebsocketDocConnector, W as deriveYjsServerUrl, Z as streamDataLabel, _ as transportStreamData } from './stream-data-BQHZia_W.mjs';
2
+ import 'yjs';
3
+ import 'y-protocols/awareness';
4
+
5
+ declare function isNodeRuntime(): boolean;
6
+
7
+ declare function nodeMediasoupHandlerName(): string | undefined;
8
+
9
+ declare function ensureNodeWebRTC(): Promise<void>;
10
+
11
+ export { ensureNodeWebRTC, isNodeRuntime, nodeMediasoupHandlerName };
@@ -0,0 +1,11 @@
1
+ export { d as ChannelMessage, e as ChannelMultiplexer, f as ChannelName, D as DeferredChannelMultiplexer, h as DeferredDocConnector, i as DocConnection, j as DocConnector, m as LoopbackStreamData, F as SessionStartOptions, N as StreamDataTransport, T as TransportSession, O as TransportSessionOptions, U as createPresence, V as createWebsocketDocConnector, W as deriveYjsServerUrl, Z as streamDataLabel, _ as transportStreamData } from './stream-data-BQHZia_W.js';
2
+ import 'yjs';
3
+ import 'y-protocols/awareness';
4
+
5
+ declare function isNodeRuntime(): boolean;
6
+
7
+ declare function nodeMediasoupHandlerName(): string | undefined;
8
+
9
+ declare function ensureNodeWebRTC(): Promise<void>;
10
+
11
+ export { ensureNodeWebRTC, isNodeRuntime, nodeMediasoupHandlerName };