@urun-sh/react 0.2.36 → 0.2.37
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.d.mts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/dist/index.d.mts
CHANGED
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client"
|
|
2
|
-
"use strict";var Kt=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var Hn=Object.getOwnPropertyNames;var Wn=Object.prototype.hasOwnProperty;var Bn=(e,t)=>{for(var r in t)Kt(e,r,{get:t[r],enumerable:!0})},$n=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Hn(t))!Wn.call(e,n)&&n!==r&&Kt(e,n,{get:()=>t[n],enumerable:!(o=qn(t,n))||o.enumerable});return e};var Kn=e=>$n(Kt({},"__esModule",{value:!0}),e);var bo={};Bn(bo,{Audio:()=>it,Camera:()=>lr,ComponentRenderer:()=>Br,DEFAULT_CAMERA_CONSTRAINTS:()=>cr,DEFAULT_LOG_CAP:()=>Pe,DEFAULT_VOICE_CONSTRAINTS:()=>ir,DocPatchForm:()=>ct,Image:()=>on,ImageFrame:()=>Yr,ImageFrameSchema:()=>Gr,MetricsPanel:()=>Qr,MetricsPanelSchema:()=>Zr,Mic:()=>mn,OPERATOR_CHORD_LABEL:()=>Er,OPERATOR_TOKEN_STORAGE_KEY:()=>xr,ProgressCard:()=>Kr,ProgressCardSchema:()=>$r,Session:()=>en,StatusBadge:()=>Jr,StatusBadgeSchema:()=>jr,TextStream:()=>Xr,TextStreamSchema:()=>zr,UrunActivationOverlay:()=>Ft,UrunAudio:()=>cn,UrunAuthProvider:()=>jt,UrunCamera:()=>fn,UrunControlSender:()=>Cn,UrunDocPanel:()=>bn,UrunErrorBoundary:()=>Ie,UrunEventSpine:()=>xn,UrunIdleWarning:()=>_n,UrunJwtProvider:()=>br,UrunProvider:()=>Ur,UrunSessionClock:()=>An,UrunSessionEnded:()=>Mn,UrunSessionGate:()=>Rn,UrunSessionStatus:()=>wn,UrunSessionWaking:()=>Ot,UrunStreamTail:()=>kn,UrunVoice:()=>dn,Video:()=>kt,Voice:()=>at,authMode:()=>Ge,createDocStore:()=>wt,describeSessionPhase:()=>Wt.describeSessionPhase,formatPayload:()=>Be,getUrunAudioContext:()=>ot,isWakingPhase:()=>Wt.isWakingPhase,parseJsonObject:()=>At,pushCapped:()=>ve,readOperatorToken:()=>Jt,registerComponent:()=>Hr,resumeUrunAudioContext:()=>st,urunPublicEnv:()=>ge,useActivation:()=>Dt,useApp:()=>_r,useChat:()=>Vr,useCompletion:()=>Lr,useConfirmOnLeave:()=>ht,useDocStore:()=>We,useImageFrame:()=>rr,useInputPresence:()=>Fr,useMetricsPanel:()=>nr,useOperatorOverride:()=>St,useProgressCard:()=>Qt,useRequest:()=>Nr,useSession:()=>tn,useSessionDoc:()=>yn,useSessionEndsAt:()=>dr,useSessionIdle:()=>mr,useSessionPhase:()=>ue,useSessionTrack:()=>gn,useSessionWake:()=>Lt,useStatusBadge:()=>er,useStreamMessages:()=>Mt,useTextStream:()=>tr,useUrunAudioLevel:()=>xt,useUrunAuth:()=>ft,useUrunPrewake:()=>In,usesWorkOSAuth:()=>yr});module.exports=Kn(bo);var re=require("react");var hr=require("react"),Xe=require("react/jsx-runtime"),Ie=class extends hr.Component{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||(0,Xe.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,Xe.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,Xe.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var vr=require("react"),Le=(0,vr.createContext)(null);function Ee(e){return e&&e.trim()?e.trim():void 0}function ge(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return Ee(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return Ee(typeof process<"u"?process.env?.[e]:void 0)}}function Ge(){let e=ge("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||ge("VERCEL_ENV")==="production"?"workos":ge("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function yr(){return Ge()==="workos"}var Oe=require("react"),Pr=require("react/jsx-runtime"),kr=(0,Oe.createContext)(null);function jt({getAccessToken:e,children:t}){let r=(0,Oe.useMemo)(()=>({getAccessToken:e}),[e]);return(0,Pr.jsx)(kr.Provider,{value:r,children:t})}var br=jt;function ft(){return(0,Oe.useContext)(kr)}var gt=require("react"),xr="urun.operator_token",Tr=null,Cr="op",Er="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function wr(){return typeof window<"u"}function Jt(){return Tr}function jn(){if(!wr())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(Cr);if(!r)return null;Tr=r,t.delete(Cr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Jn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function St(e){let t=(0,gt.useRef)(e);t.current=e,(0,gt.useEffect)(()=>{if(!wr())return;jn();let r=o=>{if(!Jn(o))return;let n=Jt();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var Rr=require("react");function ht(e=!0){(0,Rr.useEffect)(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}var be=require("react/jsx-runtime"),zn="/api/urun-token",Xn=1e4;function Gn(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function Ar(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function Yn(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,be.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,be.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,be.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Ur({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,confirmOnLeave:m=!1,fallback:d,errorFallback:y,children:k}){let f=n===void 0&&t===void 0;if(!f&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!f&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let p=r??o;if(f&&(typeof p!="string"||p.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);ht(m);let[C,S]=(0,re.useState)(),[A,b]=(0,re.useState)(),[x,g]=(0,re.useState)(null),_=(0,re.useRef)(void 0),H=(0,re.useRef)(null),[I,M]=(0,re.useState)(null);St(J=>M({jwt:J}));let l=ft(),E=ge("NEXT_PUBLIC_SESSION_TOKEN")??ge("NEXT_PUBLIC_URUN_JWT"),v=Ge(),T=I!==null,V=v==="workos"&&!n&&!T&&!f,G=n??(v==="jwt"?E:void 0)??C??A?.token,U=T?I.jwt:G,R=s??ge("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),B=V&&!U,$=t??A?.orgId,h=e??A?.gatewayUrl,P=f&&A===void 0,L=f&&A!==void 0&&!h?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,O=x??L,K=u??zn,j=(0,re.useCallback)(async J=>{if(!J?.forceRefresh){let ee=_.current;if(!ee)return ee;let me=Gn(ee);if(me===null||me-Date.now()>Xn)return ee}return(await(H.current??(H.current=(async()=>{try{let ee=await Ar(K);return _.current=ee.token,b(ee),ee}finally{H.current=null}})()))).token},[K]),N=(0,re.useMemo)(()=>({appId:p,baseUrl:h??"",orgId:$??"",jwt:U,getAccessToken:V?l?.getAccessToken:f&&!T?j:void 0,authProvider:R,eventsUrl:i,sessionKey:a,releaseOnLeave:c,priority:T?"preempt":void 0}),[p,l,h,R,U,i,$,a,c,V,T,f,j]);return(0,re.useEffect)(()=>{if(!f)return;let J=new AbortController;return g(null),(async()=>{try{let ne=await Ar(K,J.signal);_.current=ne.token,b(ne)}catch(ne){if(J.signal.aborted)return;g(ne instanceof Error?ne:new Error(String(ne)))}})(),()=>J.abort()},[f,K]),(0,re.useEffect)(()=>{if(!V||!l)return;let J=!1,ne=l;async function ee(){try{let dt=await ne.getAccessToken();J||S(dt??void 0)}catch{J||S(void 0)}}ee();let me=window.setInterval(()=>{ee()},6e4);return()=>{J=!0,window.clearInterval(me)}},[l,V]),(0,be.jsx)(Ie,{fallback:d,children:O?Yn(y,O):B||P?(0,be.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,be.jsx)(Le.Provider,{value:N,children:k})})}var oe=require("react"),Mr=require("@urun-sh/core");function Zn(e,t){return`${e}:${JSON.stringify(t??{})}`}function Qn(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var we=new Map;var zt=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},Xt=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},Gt=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new zt(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new Xt(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function _r(){let e=(0,oe.useContext)(Le);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,oe.useReducer)(i=>i+1,0),r=(0,oe.useRef)(new Map),o=(0,oe.useRef)(new Map),n=(0,oe.useRef)(null),s=(0,oe.useMemo)(()=>(0,Mr.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,priority:e.priority}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority]);return(0,oe.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=we.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let m=we.get(u);m===c&&(m.handle.removeNotifier(t),m.refCount=Math.max(0,m.refCount-1),a.set(u,m),m.refCount===0&&(m.disposeTimer=setTimeout(()=>{let d=we.get(u);!d||d.refCount!==0||(we.delete(u),d.handle.disconnect())},0)))}n.current=a}},[]),(0,oe.useMemo)(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let m=d=>{let y=Zn(u,d),k=r.current.get(y);if(k&&!k.disposed)return k;let f=Qn(e,u,d),p=we.get(f);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),we.delete(f),o.current.get(f)===p&&o.current.delete(f),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new Gt(s[u](d),t,e.eventsUrl),refCount:0,disposeTimer:null},we.set(f,p)),o.current.get(f)!==p&&(o.current.set(f,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(y,p.handle),p.handle};return i.set(u,m),m}})},[e,s])}var Z=require("react");function De(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function eo(e){return e instanceof Error?e:new Error(String(e))}function Nr(e,t){let r=(0,Z.useMemo)(()=>De(e),[e]),[o,n]=(0,Z.useState)(void 0),[s,i]=(0,Z.useState)(null),[a,u]=(0,Z.useState)(!1),c=(0,Z.useRef)(t);c.current=t;let m=(0,Z.useRef)(0),d=(0,Z.useRef)(null),y=(0,Z.useRef)(!0);(0,Z.useEffect)(()=>(y.current=!0,()=>{y.current=!1,d.current?.abort()}),[]);let k=(0,Z.useCallback)(async C=>{d.current?.abort();let S=new AbortController;d.current=S;let A=++m.current,b=()=>y.current&&m.current===A;b()&&(u(!0),i(null));try{let x=await r.request(C,{...c.current,signal:S.signal});return b()&&(n(x),u(!1),c.current?.onSuccess?.(x)),x}catch(x){let g=eo(x);throw b()&&(i(g),u(!1),c.current?.onError?.(g)),g}},[r]),f=(0,Z.useCallback)(C=>{k(C).catch(()=>{})},[k]),p=(0,Z.useCallback)(()=>{m.current++,d.current?.abort(),d.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:f,mutateAsync:k,data:o,error:s,isPending:a,reset:p}}var Q=require("react");function Ir(e){return e instanceof Error?e:new Error(String(e))}var to=e=>typeof e=="string"?e:String(e);function Lr(e,t){let r=(0,Q.useMemo)(()=>De(e),[e]),[o,n]=(0,Q.useState)(""),[s,i]=(0,Q.useState)(!1),[a,u]=(0,Q.useState)(null),c=(0,Q.useRef)(t);c.current=t;let m=(0,Q.useRef)(0),d=(0,Q.useRef)(null),y=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>(y.current=!0,()=>{y.current=!1,d.current?.cancel(),d.current=null}),[]);let k=(0,Q.useCallback)(()=>{m.current++,d.current?.cancel(),d.current=null,y.current&&i(!1)},[]),f=(0,Q.useCallback)(async p=>{d.current?.cancel();let C=++m.current,S=()=>y.current&&m.current===C,A=c.current,b=A?.parseChunk??to,x=A?.buildPayload??(v=>({prompt:v}));S()&&(n(""),u(null),i(!0));let{parseChunk:g,buildPayload:_,onFinish:H,onError:I,...M}=A??{},l="",E;try{E=r.requestStream(x(p),M),d.current=E}catch(v){let T=Ir(v);S()&&(u(T),i(!1),A?.onError?.(T));return}try{for await(let v of E){if(m.current!==C)break;l+=b(v),S()&&n(l)}S()&&(i(!1),A?.onFinish?.(l))}catch(v){let T=Ir(v);S()&&(u(T),i(!1),A?.onError?.(T))}finally{d.current===E&&(d.current=null)}},[r]);return{completion:o,complete:f,stop:k,isStreaming:s,error:a}}var Y=require("react");function Or(e){return e instanceof Error?e:new Error(String(e))}var ro=e=>typeof e=="string"?e:String(e),Dr=0;function Yt(e){return Dr+=1,`${e}-${Dr}`}function Vr(e,t){let r=(0,Y.useMemo)(()=>De(e),[e]),[o,n]=(0,Y.useState)(()=>(t?.initialMessages??[]).map(b=>({id:b.id??Yt("msg"),role:b.role,content:b.content}))),[s,i]=(0,Y.useState)(""),[a,u]=(0,Y.useState)(!1),[c,m]=(0,Y.useState)(null),d=(0,Y.useRef)(t);d.current=t;let y=(0,Y.useRef)(o);y.current=o;let k=(0,Y.useRef)(s);k.current=s;let f=(0,Y.useRef)(0),p=(0,Y.useRef)(null),C=(0,Y.useRef)(!0);(0,Y.useEffect)(()=>(C.current=!0,()=>{C.current=!1,p.current?.cancel(),p.current=null}),[]);let S=(0,Y.useCallback)(()=>{f.current++,p.current?.cancel(),p.current=null,C.current&&u(!1)},[]),A=(0,Y.useCallback)(async b=>{let x=b===void 0,g=(x?k.current:b)??"";if(!g.trim())return;p.current?.cancel();let H=++f.current,I=()=>C.current&&f.current===H,M=d.current,l=M?.parseChunk??ro,E={id:Yt("msg"),role:"user",content:g},v={id:Yt("msg"),role:"assistant",content:""},T=[...y.current,E].map(j=>({role:j.role,content:j.content})),V=[...y.current,E,v];y.current=V,n(V),x&&i(""),m(null),u(!0);let G=M?.buildPayload??(j=>({messages:j})),{initialMessages:U,parseChunk:R,buildPayload:B,onFinish:$,onError:h,...P}=M??{},L=j=>{n(N=>N.map(J=>J.id===v.id?{...J,content:j}:J))},O="",K;try{K=r.requestStream(G(T),P),p.current=K}catch(j){let N=Or(j);I()&&(m(N),u(!1),M?.onError?.(N));return}try{for await(let j of K){if(f.current!==H)break;O+=l(j),I()&&L(O)}I()&&(u(!1),M?.onFinish?.({...v,content:O}))}catch(j){let N=Or(j);I()&&(m(N),u(!1),M?.onError?.(N))}finally{p.current===K&&(p.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:A,stop:S,isStreaming:a,error:c}}var X=require("react"),Ve=require("@urun-sh/core"),Zt=[];function Fr(e,t={}){let{field:r=Ve.INPUT_PRESENCE_FIELD,hz:o=Ve.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,X.useMemo)(()=>s?(0,Ve.createInputPresencePublisher)({awareness:{setLocalStateField:(g,_)=>s.setField(g,_)},field:r,hz:o}):null,[s,r,o]),a=(0,X.useRef)(null);a.current=i;let[u,c]=(0,X.useState)(!1),[m,d]=(0,X.useState)(Zt),y=(0,X.useRef)(!1);(0,X.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let k=(0,X.useCallback)(()=>{let g=a.current;d(g?g.heldKeys():Zt)},[]),f=(0,X.useCallback)(()=>{a.current?.clear(),d(Zt)},[]);(0,X.useEffect)(()=>{if(!n)return;let g=()=>!!n.pointerLockElement,_=()=>{if(g()){y.current=!1,c(!0);return}y.current||(c(!1),f())},H=v=>{g()&&(a.current?.keyDown(v.key),k())},I=v=>{a.current?.keyUp(v.key),k()},M=v=>{g()&&a.current?.movePointer(v.movementX,v.movementY)},l=v=>{g()&&a.current?.setButtons(v.buttons)},E=()=>{f()};return n.addEventListener("pointerlockchange",_),n.addEventListener("keydown",H),n.addEventListener("keyup",I),n.addEventListener("mousemove",M),n.addEventListener("mousedown",l),n.addEventListener("mouseup",l),n.defaultView?.addEventListener("blur",E),()=>{n.removeEventListener("pointerlockchange",_),n.removeEventListener("keydown",H),n.removeEventListener("keyup",I),n.removeEventListener("mousemove",M),n.removeEventListener("mousedown",l),n.removeEventListener("mouseup",l),n.defaultView?.removeEventListener("blur",E)}},[n,f,k]);let p=(0,X.useCallback)(g=>{g.requestPointerLock?.()},[]),C=(0,X.useCallback)(()=>{y.current=!0,c(!0)},[]),S=(0,X.useCallback)(()=>{y.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),f()},[n,f]),A=(0,X.useCallback)(g=>{a.current?.keyDown(g),k()},[k]),b=(0,X.useCallback)(g=>{a.current?.keyUp(g),k()},[k]),x=(0,X.useCallback)((g,_)=>{a.current?.movePointer(g,_)},[]);return{engage:p,engageTouch:C,release:S,engaged:u,heldKeys:m,pressKey:A,releaseKey:b,movePointer:x}}var qr=new Map;function Hr(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);qr.set(e,{component:t,schema:r})}function Wr(e,t){let r=qr.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}var Re=require("react/jsx-runtime");function Br({name:e,props:t,fallback:r}){let o=Wr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,Re.jsx)(Re.Fragment,{children:r}):(0,Re.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,Re.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,Re.jsx)(n,{...o.validatedProps})}var Fe=require("zod"),Ae=require("react/jsx-runtime"),$r=Fe.z.object({step:Fe.z.number().min(0),total:Fe.z.number().min(1),label:Fe.z.string().optional(),variant:Fe.z.enum(["default","success","error"]).default("default")});function Qt(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function Kr(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Qt(e);return(0,Ae.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Ae.jsx)("div",{className:"urun-progress-label",children:o}),(0,Ae.jsx)("div",{className:"urun-progress-bar",children:(0,Ae.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Ae.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var vt=require("zod"),Ye=require("react/jsx-runtime"),jr=vt.z.object({state:vt.z.enum(["thinking","generating","idle","error"]),message:vt.z.string().optional()}),no={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function er(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??no[t]??t;return{state:t,message:n,isActive:o}}function Jr(e){let{state:t,message:r,isActive:o}=er(e);return(0,Ye.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,Ye.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,Ye.jsx)("span",{className:"urun-status-message",children:r})]})}var Ze=require("react"),yt=require("zod"),Qe=require("react/jsx-runtime"),zr=yt.z.object({text:yt.z.string(),streaming:yt.z.boolean().default(!1)});function tr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Xr(e){let{text:t,streaming:r}=tr(e),o=(0,Ze.useRef)(null),n=(0,Ze.useRef)(0);return(0,Ze.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,Qe.jsxs)("div",{className:"urun-text-stream",children:[(0,Qe.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,Qe.jsx)("span",{className:"urun-text-cursor"})]})}var et=require("zod"),tt=require("react/jsx-runtime"),Gr=et.z.object({src:et.z.string().url(),alt:et.z.string().optional(),caption:et.z.string().optional()});function rr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Yr(e){let{src:t,alt:r,caption:o}=rr(e);return(0,tt.jsxs)("figure",{className:"urun-image-frame",children:[(0,tt.jsx)("img",{className:"urun-image",src:t,alt:r}),o&&(0,tt.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var Se=require("zod"),qe=require("react/jsx-runtime"),Zr=Se.z.object({metrics:Se.z.array(Se.z.object({label:Se.z.string(),value:Se.z.union([Se.z.string(),Se.z.number()]),unit:Se.z.string().optional()}))});function nr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Qr(e){let{metrics:t}=nr(e);return(0,qe.jsx)("div",{className:"urun-metrics-panel",children:t.map((r,o)=>(0,qe.jsxs)("div",{className:"urun-metric-card",children:[(0,qe.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,qe.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var rt=require("react"),rn=require("react/jsx-runtime"),or=(0,rt.createContext)(null);function en({session:e,children:t}){return(0,rn.jsx)(or.Provider,{value:e,children:t})}function pe(){return(0,rt.useContext)(or)}function tn(){let e=(0,rt.useContext)(or);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}var F=require("react");var nt=require("react/jsx-runtime"),oo=1e3;function so(...e){console.debug("[video]",...e)}var kt=(0,F.forwardRef)(function(t,r){let{session:o,stream:n="video",track:s,muted:i=!0,mirror:a=!1,objectFit:u="contain",className:c,style:m,videoClassName:d,placeholder:y,poster:k,children:f,onTrack:p,onFirstFrame:C}=t,S=pe(),A=o??S,b=(0,F.useRef)(null),x=(0,F.useRef)(null),[g,_]=(0,F.useState)(!1),[H,I]=(0,F.useState)(!1),M=(0,F.useRef)(!1),l=(0,F.useRef)(p);l.current=p;let E=(0,F.useRef)(C);E.current=C;let v=(0,F.useRef)(null),T=(0,F.useRef)(null),V=(0,F.useCallback)(h=>{if(h===v.current||(v.current=h,T.current?.(),T.current=null,M.current=!1,I(!1),!h))return;let P=b.current;if(!P)return;let L=()=>{T.current?.(),T.current=null,M.current=!0,I(!0),E.current?.()};if(typeof P.requestVideoFrameCallback=="function"){let K=P.requestVideoFrameCallback(L);T.current=()=>P.cancelVideoFrameCallback?.(K);return}let O=()=>{let K=P.getVideoPlaybackQuality?.();(K?K.totalVideoFrames>0:P.readyState>=2&&P.videoWidth>0)&&L()};P.addEventListener("loadeddata",O),P.addEventListener("timeupdate",O),P.addEventListener("playing",O),T.current=()=>{P.removeEventListener("loadeddata",O),P.removeEventListener("timeupdate",O),P.removeEventListener("playing",O)},O()},[]);(0,F.useEffect)(()=>()=>{T.current?.(),T.current=null},[]);let G=(0,F.useCallback)(()=>{if(typeof MediaStream>"u")return null;x.current||(x.current=new MediaStream);let h=b.current;return h&&h.srcObject!==x.current&&(h.srcObject=x.current),x.current},[]),U=(0,F.useCallback)(h=>{let P=b.current;if(!P)return;let L=P.play();!L||typeof L.catch!="function"||L.catch(O=>so(`play() failed (${h})`,O))},[]),R=(0,F.useCallback)(h=>{let P=G();if(P){for(let L of P.getVideoTracks())L!==h&&P.removeTrack(L);if(h&&!P.getVideoTracks().includes(h)){P.addTrack(h);let L=b.current;L&&(L.srcObject=P)}h&&U("track-attach"),_(h!==null),V(h),l.current?.(h)}},[G,U,V]),B=(0,F.useCallback)(h=>{b.current=h,h&&(i&&(h.muted=!0,h.defaultMuted=!0,h.setAttribute("muted","")),h.setAttribute("playsinline",""),h.setAttribute("webkit-playsinline",""),G())},[G,i]);(0,F.useImperativeHandle)(r,()=>({get element(){return b.current},get live(){return x.current?x.current.getVideoTracks().length>0:!1},get framed(){return M.current}}),[]);let $=s!==void 0;return(0,F.useEffect)(()=>{if($){R(s??null);return}if(!A)return;let h=A.stream(n),P=()=>{let N=x.current;return N?N.getVideoTracks()[0]??null:null},L=N=>{if(N!==P()&&(R(N),N)){let J=()=>{P()===N&&R(null)};N.addEventListener("ended",J)}},O=h.track;O&&O.readyState==="live"&&L(O);let K=h.on("track",N=>{N&&N.readyState!=="live"||L(N)}),j=setInterval(()=>{let N=h.track;N&&N.readyState==="live"&&L(N)},oo);return()=>{K(),clearInterval(j)}},[A,n,$,s,R]),(0,nt.jsxs)("div",{className:c,style:{position:"relative",width:"100%",height:"100%",...m},"data-urun-video":"","data-urun-video-live":g?"true":"false","data-urun-video-framed":H?"true":"false",children:[(0,nt.jsx)("video",{ref:B,className:d,autoPlay:!0,muted:i,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...a?{transform:"scaleX(-1)"}:{}}}),g?null:y,k===void 0?null:(0,nt.jsx)("div",{"data-urun-video-poster":"","aria-hidden":H||void 0,style:{position:"absolute",inset:0,...H?{opacity:0,pointerEvents:"none"}:null},children:k}),f]})});var nn=require("react");var sn=require("react/jsx-runtime"),on=(0,nn.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,sn.jsx)(kt,{ref:r,stream:o,...n})});var W=require("react"),un=require("@urun-sh/core");var bt=null;function io(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function ot(){if(bt)return bt;let e=io();return e?(bt=new e,bt):null}function st(){let e=ot();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var ln=require("react/jsx-runtime"),ao=1e3,an=200;function sr(...e){console.debug("[audio]",...e)}var it=(0,W.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:m}=t,d=pe(),y=o??d,k=(0,W.useRef)(null),f=(0,W.useRef)(null),p=(0,W.useRef)(null),C=(0,W.useRef)(null),S=(0,W.useRef)(u);S.current=u;let A=(0,W.useRef)(c);A.current=c;let b=(0,W.useCallback)(l=>{p.current!==l&&(p.current=l,A.current?.(l))},[]),x=(0,W.useCallback)(()=>{if(typeof MediaStream>"u")return null;f.current||(f.current=new MediaStream);let l=k.current;return l&&l.srcObject!==f.current&&(l.srcObject=f.current),f.current},[]),g=(0,W.useCallback)(l=>{let E=k.current;if(!E)return;let v=E.play();!v||typeof v.then!="function"||v.then(()=>{E.muted||b(!0)}).catch(T=>{let V=T instanceof Error?T.name:String(T);if(V==="AbortError"){sr(`play() aborted (${l}); retrying in ${an}ms`),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>{C.current=null,g(`${l}:retry`)},an);return}if(V==="NotAllowedError"){sr(`play() blocked pending a user gesture (${l})`),b(!1);return}sr(`play() failed (${l})`,T)})},[b]),_=(0,W.useCallback)(l=>{let E=x();if(E){for(let v of E.getAudioTracks())v!==l&&E.removeTrack(v);l&&!E.getAudioTracks().includes(l)&&E.addTrack(l),l&&g("track-attach"),S.current?.(l)}},[x,g]),H=(0,W.useCallback)(()=>{let l=k.current;l&&(x(),l.muted=!1,g("gesture"),st(),b(!0))},[x,g,b]);(0,W.useImperativeHandle)(r,()=>({unlock:H,get unlocked(){return p.current===!0},get element(){return k.current}}),[H]);let I=(0,W.useCallback)(l=>{k.current=l,l&&(l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),x()),m?.(l)},[x,m]),M=s!==void 0;return(0,W.useEffect)(()=>{if(M){_(s??null);return}if(!y)return;let l=y.stream(n),E=()=>{let U=f.current;return U?U.getAudioTracks()[0]??null:null},v=U=>{if(U!==E()&&(_(U),U)){let R=()=>{E()===U&&_(null)};U.addEventListener("ended",R)}},T=l.track;T&&T.readyState==="live"&&v(T);let V=l.on("track",U=>{U&&U.readyState!=="live"||v(U)}),G=setInterval(()=>{let U=l.track;U&&U.readyState==="live"&&v(U)},ao);return()=>{V(),clearInterval(G)}},[y,n,M,s,_]),(0,W.useEffect)(()=>(0,un.observePageLifecycle)(()=>{st(),p.current===!0&&g("foreground")}),[g]),(0,W.useEffect)(()=>()=>{C.current&&clearTimeout(C.current)},[]),(0,ln.jsx)("audio",{ref:I,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),cn=it;var q=require("react"),He=require("@urun-sh/core");var pn=require("react/jsx-runtime"),ir={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Pt(...e){console.debug("[voice]",...e)}var at=(0,q.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=ir,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:m,onError:d,onMicStream:y,onTrack:k,onUnlockChange:f,capture:p}=t,C=pe(),S=o??C,A=(0,q.useRef)(null),b=(0,q.useRef)(null),x=(0,q.useRef)(null),g=(0,q.useRef)([]),_=(0,q.useRef)(!1),H=(0,q.useRef)(m);H.current=m;let I=(0,q.useRef)(d);I.current=d;let M=(0,q.useRef)(y);M.current=y;let l=(0,q.useCallback)(R=>{_.current!==R&&(_.current=R,H.current?.(R))},[]),E=(0,q.useCallback)(()=>{for(let R of g.current)R();g.current=[],x.current?.release(),x.current=null,b.current&&(b.current=null,M.current?.(null))},[]),v=(0,q.useCallback)(async()=>{let R=x.current;if(R){let P=await R.update(i);return b.current=R.stream,M.current?.(R.stream),P}let $=await(p??(0,He.sharedCaptureController)()).claim("audio",i);x.current=$,g.current=[$.onTrack((P,L)=>{b.current=L,M.current?.(L),_.current&&S?.stream(n).attach(P).catch(O=>Pt("mic re-attach after one-capture re-acquire failed",O))}),$.onLost(P=>{x.current=null,g.current=[],b.current=null,M.current?.(null),l(!1),I.current?.(P)})],b.current=$.stream,M.current?.($.stream);let h=$.track;if(!h)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return h},[p,i,S,n,l]),T=(0,q.useCallback)(async()=>{E(),l(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,E,l]),V=(0,q.useCallback)(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");A.current?.unlock();let R;try{R=await v()}catch(h){E();let P=(0,He.sessionFailureFromMediaError)(h,S.status);throw I.current?.(P),P}S.connect?.();let B;for(let h=1;h<=u;h++)try{await S.whenLive(a!==void 0?{timeout:a}:void 0),await S.stream(n).attach(R),l(!0);return}catch(P){B=P,Pt(`start attempt ${h}/${u} failed`,P),h<u&&await new Promise(L=>setTimeout(L,c))}E(),l(!1);let $=B instanceof Error?B:new Error(String(B??"voice start failed"));throw I.current?.($),$},[S,n,a,u,c,v,E,l]);(0,q.useImperativeHandle)(r,()=>({start:V,stop:T,unlock:()=>A.current?.unlock(),get active(){return _.current},get micStream(){return b.current},get audio(){return A.current}}),[V,T]);let G=(0,q.useRef)(!1),U=(0,q.useCallback)(async()=>{if(!S||!_.current||G.current)return;let R=b.current?.getAudioTracks()[0]??null;if(R&&R.readyState==="live"){try{await S.stream(n).attach(R)}catch(B){Pt("foreground mic re-assert failed (will retry on next pass)",B)}return}G.current=!0;try{let B=await v();await S.stream(n).attach(B)}catch(B){let $=B instanceof Error?B:new Error(String(B));Pt("foreground mic re-acquire failed",$),I.current?.($)}finally{G.current=!1}},[S,n,v]);return(0,q.useEffect)(()=>{let R=()=>{U()};return S&&typeof S.onRecovery=="function"?S.onRecovery(R):(0,He.observePageLifecycle)(R)},[S,U]),(0,q.useEffect)(()=>E,[E]),s?(0,pn.jsx)(it,{ref:A,session:S,stream:n,onTrack:k,onUnlockChange:f}):null}),dn=at;var le=require("react");var Ct=require("react");var ar={level:0,speaking:!1};function xt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,Ct.useState)(ar);return(0,Ct.useEffect)(()=>{if(!e){i(ar);return}let a=ot();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,m;try{c=a.createMediaStreamSource(u),m=a.createAnalyser(),m.fftSize=r,c.connect(m)}catch{return}let d=new Uint8Array(m.fftSize),k=setInterval(()=>{m.getByteTimeDomainData(d);let f=0;for(let C=0;C<d.length;C++){let S=(d[C]-128)/128;f+=S*S}let p=Math.sqrt(f/d.length);i(C=>{let S=p>n;return Math.abs(C.level-p)<.005&&C.speaking===S?C:{level:p,speaking:S}})},o);return()=>{clearInterval(k),c.disconnect(),i(ar)}},[e,r,o,n]),s}var he=require("react/jsx-runtime"),uo={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},co={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},mn=(0,le.forwardRef)(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:m,onMicStream:d,capture:y}=t,k=pe(),f=o??k,p=(0,le.useRef)(null),[C,S]=(0,le.useState)(null),A=(0,le.useRef)(d);A.current=d;let{level:b,speaking:x}=xt(a?C:null);return(0,le.useImperativeHandle)(r,()=>({start:()=>{let g=p.current;return g?g.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>p.current?.stop()??Promise.resolve(),get active(){return p.current?.active??!1},get micStream(){return p.current?.micStream??null}}),[]),(0,le.useEffect)(()=>{!i||!f||p.current?.start().catch(()=>{})},[i,f]),(0,he.jsxs)(he.Fragment,{children:[(0,he.jsx)(at,{ref:p,session:f,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...y!==void 0?{capture:y}:{},onActiveChange:c,onError:m,onMicStream:g=>{S(g),A.current?.(g)}}),a?(0,he.jsx)("span",{className:u,style:uo,"data-urun-mic":"","data-urun-mic-active":C?"true":"false","data-urun-mic-speaking":x?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(b*100)/100,children:(0,he.jsx)("span",{style:co,children:(0,he.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(b*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var Tt=require("@urun-sh/core"),w=require("react");var ae=require("react/jsx-runtime"),cr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function ur(...e){console.debug("[camera]",...e)}function lo(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function po(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var lr=(0,w.forwardRef)(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:m="auto",connectTimeoutMs:d,visible:y=!1,className:k,videoClassName:f,onActiveChange:p,onError:C,onStream:S,onTrack:A,children:b,capture:x,flipControl:g="auto",flipControlClassName:_,onDevices:H}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let I=i?"user":a?"environment":u??"environment",M=pe(),l=o??M,E=(0,w.useRef)(null),v=(0,w.useRef)(null),T=(0,w.useRef)(null),V=(0,w.useRef)([]),G=(0,w.useRef)(null),U=(0,w.useRef)(!1),R=(0,w.useRef)(I),[B,$]=(0,w.useState)(I),[h,P]=(0,w.useState)(!1),[L,O]=(0,w.useState)(null),[K,j]=(0,w.useState)(!1),[N]=(0,w.useState)(lo),J=(0,w.useRef)(p);J.current=p;let ne=(0,w.useRef)(C);ne.current=C;let ee=(0,w.useRef)(S);ee.current=S;let me=(0,w.useRef)(A);me.current=A;let dt=(0,w.useRef)(H);dt.current=H;let ke=(0,w.useCallback)(D=>{U.current!==D&&(U.current=D,P(D),J.current?.(D))},[]);(0,w.useEffect)(()=>{if(!h){O(null);return}let D=!1,z=()=>{po().then(ie=>{D||(O(ie),ie&&dt.current?.(ie))})};z();let te=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof te?.addEventListener=="function"?(te.addEventListener("devicechange",z),()=>{D=!0,te.removeEventListener?.("devicechange",z)}):()=>{D=!0}},[h]);let pt=(0,w.useCallback)(D=>{let z=E.current;z&&(z.muted=!0,z.defaultMuted=!0,z.setAttribute("muted",""),z.setAttribute("playsinline",""),z.setAttribute("webkit-playsinline",""),z.srcObject=D,D&&z.play()?.catch?.(te=>ur("preview play() failed",te)))},[]),fe=(0,w.useCallback)(()=>{G.current?.(),G.current=null;for(let D of V.current)D();V.current=[],T.current?.release(),T.current=null,v.current&&(v.current=null,ee.current?.(null),me.current?.(null)),pt(null)},[pt]),Bt=(0,w.useCallback)((D,z)=>{G.current?.(),v.current=z,pt(z),ee.current?.(z);let te=()=>{v.current===z&&(ur("camera track ended (device removed or permission revoked)"),fe(),ke(!1))};D.addEventListener("ended",te),G.current=()=>D.removeEventListener("ended",te)},[pt,fe,ke]),_e=(0,w.useCallback)(async D=>{if(!l)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let z={...cr,...s,facingMode:D},te;try{let ie=T.current;if(ie)te=await ie.update(z);else{let Je=await(x??(0,Tt.sharedCaptureController)()).claim("video",z);if(T.current=Je,V.current=[Je.onTrack((ze,Vn)=>{Bt(ze,Vn),U.current&&l.stream(n).attachVideo(ze).then(()=>me.current?.(ze)).catch(Fn=>ur("camera re-publish after one-capture re-acquire failed",Fn))}),Je.onLost(ze=>{T.current=null,V.current=[],fe(),ke(!1),ne.current?.(ze)})],!Je.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});te=Je.track}}catch(ie){let Ne=(0,Tt.sessionFailureFromMediaError)(ie,l.status);throw ne.current?.(Ne),Ne}R.current=D,$(D),Bt(te,T.current?.stream??new MediaStream([te]));try{l.connect?.(),await l.whenLive(d!==void 0?{timeout:d}:void 0),await l.stream(n).attachVideo(te)}catch(ie){fe(),ke(!1);let Ne=ie instanceof Error?ie:new Error(String(ie));throw ne.current?.(Ne),Ne}me.current?.(te),ke(!0)},[l,n,s,d,x,Bt,fe,ke]),fr=(0,w.useCallback)(D=>_e(D?.facingMode??R.current),[_e]),mt=(0,w.useCallback)(async D=>{U.current&&R.current===D||await _e(D)},[_e]),$t=(0,w.useCallback)(()=>_e(R.current==="environment"?"user":"environment"),[_e]),gr=(0,w.useCallback)(async()=>{fe(),ke(!1),await l?.stream(n).detachVideo().catch(()=>{})},[l,n,fe,ke]);(0,w.useImperativeHandle)(r,()=>({start:fr,stop:gr,flip:$t,setFacingMode:mt,get active(){return U.current},get facingMode(){return R.current},get stream(){return v.current},get element(){return E.current}}),[fr,gr,$t,mt]);let Sr=(0,w.useRef)(mt);if(Sr.current=mt,(0,w.useEffect)(()=>{!c||!l||Sr.current(I).catch(()=>{})},[c,l,I]),(0,w.useEffect)(()=>fe,[fe]),!y)return null;let Ln=m==="auto"?B==="user":m,On=h&&(g===!0||g==="auto"&&N&&(L?.length??0)>1),Dn=()=>{K||(j(!0),$t().catch(()=>{}).finally(()=>j(!1)))};return(0,ae.jsxs)("div",{className:k,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":B,children:[(0,ae.jsx)("video",{ref:E,className:f,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Ln?{transform:"scaleX(-1)"}:{}}}),On?(0,ae.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Dn,disabled:K,className:_,style:_?{opacity:K?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:K?.6:1},children:(0,ae.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[(0,ae.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,ae.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,ae.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,ae.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,ae.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,b]})}),fn=(0,w.forwardRef)(function({preview:t=!0,...r},o){return(0,ae.jsx)(lr,{ref:o,...r,visible:t,autoStart:!1})});var Et=require("react");function gn(e,t){let[r,o]=(0,Et.useState)(null);return(0,Et.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var vn=require("react");var Rt=require("react");var Sn=require("zustand/vanilla"),hn=require("zustand"),mo=()=>{};function wt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=(0,Sn.createStore)(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):mo,u=(c=>(0,hn.useStore)(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function We(e,t){let r=(0,Rt.useMemo)(()=>wt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,Rt.useEffect)(()=>r.bind(),[r]),r}function yn(e,t,r){let n=We(e,t)(r??(a=>a)),s=(0,vn.useCallback)(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}var Ut=require("react");var Pe=200;function ve(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Be(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function At(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Mt(e,t,r={}){let o=r.cap??200,[n,s]=(0,Ut.useState)([]);return(0,Ut.useEffect)(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>ve(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}var de=require("react/jsx-runtime");function kn({session:e,name:t,cap:r,className:o}){let n=Mt(e,t,{cap:r});return(0,de.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,de.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,de.jsx)("code",{children:t}),(0,de.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,de.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,de.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,de.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,i)=>(0,de.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,de.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Be(s.payload)]},`${s.at}-${i}`))})]})}var ut=require("react");var se=require("react/jsx-runtime");function ct({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,ut.useState)(""),[i,a]=(0,ut.useState)(null),u=(0,ut.useCallback)(()=>{let c=At(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return(0,se.jsxs)("div",{className:"urun-doc-patch",children:[(0,se.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),(0,se.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,se.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?(0,se.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function bn({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=We(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return(0,se.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,se.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,se.jsx)("code",{children:t}),(0,se.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,se.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,se.jsx)(ct,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}var _t=require("react");var ye=require("react/jsx-runtime");function Pn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Cn({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=(0,_t.useState)([]);return(0,_t.useEffect)(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>ve(u,{at:Date.now(),direction:"in",text:Pn(Be(a))},r))}):void 0),[e,t,r]),(0,ye.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,ye.jsx)(ct,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>ve(u,{at:Date.now(),direction:"out",text:Pn(a)},r))}}),(0,ye.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,ye.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>(0,ye.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,ye.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,ye.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}var Nt=require("react");var Ue=require("react/jsx-runtime");function xn({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=(0,Nt.useState)([]),a=t.join(","),u=r.join(",");return(0,Nt.useEffect)(()=>{if(i([]),!e)return;let c=(d,y)=>i(k=>ve(k,{at:Date.now(),kind:d,text:y},o)),m=[];m.push(e.onPhase(d=>c("phase",`phase \u2192 ${d.name}`)));for(let d of t){let y=e.stream(d);m.push(y.on("track",k=>c("track",`${d}: ${k?"track arrived":"track ended"}`)))}for(let d of r){let y=e.doc(d);m.push(y.on("change",()=>c("doc",`${d} changed`)))}return()=>m.forEach(d=>d())},[e,a,u,o]),(0,Ue.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,Ue.jsx)("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((c,m)=>(0,Ue.jsxs)("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[(0,Ue.jsx)("span",{className:"urun-event-spine-kind",children:c.kind})," ",(0,Ue.jsx)("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${m}`))})}var qt=require("@urun-sh/core");var It=require("react");function ue(e){let[t,r]=(0,It.useState)(e?.phase??null);return(0,It.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var En=require("@urun-sh/core");var $e=require("react"),Tn=require("@urun-sh/core");function Lt(e){let t=ue(e),r=(0,Tn.isWakingPhase)(t?.name),o=(0,$e.useRef)(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=(0,$e.useState)(s);return(0,$e.useEffect)(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}var Ce=require("react/jsx-runtime");function Ot({session:e,render:t,className:r}){let o=Lt(e);return!o.waking||!o.phase?null:(0,Ce.jsx)("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):(0,Ce.jsxs)(Ce.Fragment,{children:[(0,Ce.jsx)("span",{className:"urun-session-waking-label",children:(0,En.describeSessionPhase)(o.phase)})," ",(0,Ce.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var Vt=require("react");var xe=require("react"),fo={event:null,elapsedMs:0};function Dt(e,t){let[r,o]=(0,xe.useState)(null),n=(0,xe.useRef)(0);(0,xe.useEffect)(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=(0,xe.useState)(0);return(0,xe.useEffect)(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:fo}var Ke=require("react/jsx-runtime"),go={activating:"starting stream\u2026","still-activating":"model warming up \u2014 this can take a minute","cold-boot":"cold boot \u2014 compiling/loading the model, hang tight",degraded:"taking longer than usual \u2014 still trying"};function So(e){let[t,r]=(0,Vt.useState)(!1);return(0,Vt.useEffect)(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function Ft({session:e,stream:t,videoElement:r,render:o,className:n}){let s=Dt(e,t),i=So(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return(0,Ke.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):(0,Ke.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,Ke.jsx)("span",{className:"urun-activation-overlay-copy",children:a.hint??go[u]})," ",(0,Ke.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var ce=require("react/jsx-runtime"),ho={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function wn({session:e,className:t}){let r=ue(e),o=r?.name??"idle",n=r?.name==="queued"&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:(r?.name==="error"||r?.name==="expired")&&r.error?r.error.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return(0,ce.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,ce.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,ce.jsx)("span",{className:"urun-session-status-label",children:ho[o]}),n?(0,ce.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function Rn({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=ue(e);if(s?.name==="live")return(0,ce.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,ce.jsx)(Ft,{session:e})]});let i=r?r(s):(0,ce.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&(0,qt.isWakingPhase)(s.name)?(0,ce.jsx)(Ot,{session:e}):s&&s.name!=="idle"?(0,qt.describeSessionPhase)(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return(0,ce.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,ce.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var Ht=require("react");var Un=require("react/jsx-runtime");function dr(e){return ue(e)?.endsAt??null}function vo(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function An({session:e,urgentMs:t=6e4,className:r}){let n=dr(e)?.getTime()??null,[s,i]=(0,Ht.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,Ht.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=vo(s);return(0,Un.jsx)("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}var lt=require("react/jsx-runtime"),yo=new Set(["expired","ended","error"]);function Mn({session:e,onNewSession:t,children:r,className:o}){let n=ue(e);if(!n||!yo.has(n.name))return null;let s=r?r(n):(0,lt.jsx)("span",{className:"urun-session-ended-copy",children:n.name==="expired"?"Session ended \u2014 start a new session":n.name==="error"?`Session failed${n.error?.reason?` \u2014 ${n.error.reason}`:""}.`:"Session ended."});return(0,lt.jsxs)("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?(0,lt.jsx)("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}var Te=require("react"),Me=require("react/jsx-runtime");function pr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function mr(e){let t=(0,Te.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,Te.useState)(()=>t?pr(t.get("idle")):null);return(0,Te.useEffect)(()=>{if(!t){o(null);return}return o(pr(t.get("idle"))),t.on("change",()=>o(pr(t.get("idle"))))},[t]),r}function ko(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function _n({session:e,onStillHere:t,className:r}){let o=mr(e),n=o?.deadlineEpochS??null,[s,i]=(0,Te.useState)(null);if((0,Te.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return(0,Me.jsx)("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:(0,Me.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,Me.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,Me.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${ko(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,Me.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var je=require("react"),Nn=require("@urun-sh/core");function In(e){let t=(0,je.useContext)(Le),[r,o]=(0,je.useState)(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,m=t?.getAccessToken,d=t?.authProvider;return(0,je.useEffect)(()=>{if(!a||!u||!n||!s)return;let y=!1,k=()=>{(0,Nn.prewake)({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:m,authProvider:d}).then(p=>{y||o(p)}).catch(()=>{})};k();let f=setInterval(k,Math.max(1,i)*1e3);return()=>{y=!0,clearInterval(f)}},[n,s,i,a,u,c,m,d]),r}var Wt=require("@urun-sh/core");0&&(module.exports={Audio,Camera,ComponentRenderer,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,Image,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,Mic,OPERATOR_CHORD_LABEL,OPERATOR_TOKEN_STORAGE_KEY,ProgressCard,ProgressCardSchema,Session,StatusBadge,StatusBadgeSchema,TextStream,TextStreamSchema,UrunActivationOverlay,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunIdleWarning,UrunJwtProvider,UrunProvider,UrunSessionClock,UrunSessionEnded,UrunSessionGate,UrunSessionStatus,UrunSessionWaking,UrunStreamTail,UrunVoice,Video,Voice,authMode,createDocStore,describeSessionPhase,formatPayload,getUrunAudioContext,isWakingPhase,parseJsonObject,pushCapped,readOperatorToken,registerComponent,resumeUrunAudioContext,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useConfirmOnLeave,useDocStore,useImageFrame,useInputPresence,useMetricsPanel,useOperatorOverride,useProgressCard,useRequest,useSession,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
|
|
2
|
+
"use strict";var Kt=Object.defineProperty;var Hn=Object.getOwnPropertyDescriptor;var Wn=Object.getOwnPropertyNames;var Bn=Object.prototype.hasOwnProperty;var $n=(e,t)=>{for(var r in t)Kt(e,r,{get:t[r],enumerable:!0})},Kn=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Wn(t))!Bn.call(e,n)&&n!==r&&Kt(e,n,{get:()=>t[n],enumerable:!(o=Hn(t,n))||o.enumerable});return e};var jn=e=>Kn(Kt({},"__esModule",{value:!0}),e);var bo={};$n(bo,{Audio:()=>it,Camera:()=>lr,ComponentRenderer:()=>Br,DEFAULT_CAMERA_CONSTRAINTS:()=>cr,DEFAULT_LOG_CAP:()=>Pe,DEFAULT_VOICE_CONSTRAINTS:()=>ir,DocPatchForm:()=>ct,Image:()=>sn,ImageFrame:()=>Yr,ImageFrameSchema:()=>Gr,MetricsPanel:()=>Qr,MetricsPanelSchema:()=>Zr,Mic:()=>fn,OPERATOR_CHORD_LABEL:()=>Er,OPERATOR_TOKEN_STORAGE_KEY:()=>xr,ProgressCard:()=>Kr,ProgressCardSchema:()=>$r,Session:()=>en,StatusBadge:()=>Jr,StatusBadgeSchema:()=>jr,TextStream:()=>Xr,TextStreamSchema:()=>zr,UrunActivationOverlay:()=>Ft,UrunAudio:()=>ln,UrunAuthProvider:()=>jt,UrunCamera:()=>gn,UrunControlSender:()=>xn,UrunDocPanel:()=>Pn,UrunErrorBoundary:()=>Ie,UrunEventSpine:()=>Tn,UrunIdleWarning:()=>Nn,UrunJwtProvider:()=>br,UrunProvider:()=>Ur,UrunSessionClock:()=>Un,UrunSessionEnded:()=>_n,UrunSessionGate:()=>An,UrunSessionStatus:()=>Rn,UrunSessionWaking:()=>Ot,UrunStreamTail:()=>bn,UrunVoice:()=>pn,Video:()=>kt,Voice:()=>at,authMode:()=>Ge,createDocStore:()=>wt,describeSessionPhase:()=>Wt.describeSessionPhase,formatPayload:()=>Be,getUrunAudioContext:()=>ot,isWakingPhase:()=>Wt.isWakingPhase,parseJsonObject:()=>At,pushCapped:()=>ve,readOperatorToken:()=>Jt,registerComponent:()=>Hr,resumeUrunAudioContext:()=>st,urunPublicEnv:()=>ge,useActivation:()=>Dt,useApp:()=>_r,useChat:()=>Vr,useCompletion:()=>Lr,useConfirmOnLeave:()=>ht,useDocStore:()=>We,useImageFrame:()=>rr,useInputPresence:()=>Fr,useMetricsPanel:()=>nr,useOperatorOverride:()=>St,useProgressCard:()=>Qt,useRequest:()=>Nr,useSession:()=>tn,useSessionDoc:()=>kn,useSessionEndsAt:()=>dr,useSessionIdle:()=>mr,useSessionPhase:()=>ue,useSessionTrack:()=>Sn,useSessionWake:()=>Lt,useStatusBadge:()=>er,useStreamMessages:()=>Mt,useTextStream:()=>tr,useUrunAudioLevel:()=>xt,useUrunAuth:()=>ft,useUrunPrewake:()=>Ln,usesWorkOSAuth:()=>yr});module.exports=jn(bo);var ne=require("react");var hr=require("react"),Xe=require("react/jsx-runtime"),Ie=class extends hr.Component{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||(0,Xe.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,Xe.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,Xe.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var vr=require("react"),Le=(0,vr.createContext)(null);function Ee(e){return e&&e.trim()?e.trim():void 0}function ge(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return Ee(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return Ee(typeof process<"u"?process.env?.[e]:void 0)}}function Ge(){let e=ge("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||ge("VERCEL_ENV")==="production"?"workos":ge("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function yr(){return Ge()==="workos"}var Oe=require("react"),Pr=require("react/jsx-runtime"),kr=(0,Oe.createContext)(null);function jt({getAccessToken:e,children:t}){let r=(0,Oe.useMemo)(()=>({getAccessToken:e}),[e]);return(0,Pr.jsx)(kr.Provider,{value:r,children:t})}var br=jt;function ft(){return(0,Oe.useContext)(kr)}var gt=require("react"),xr="urun.operator_token",Tr=null,Cr="op",Er="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function wr(){return typeof window<"u"}function Jt(){return Tr}function Jn(){if(!wr())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(Cr);if(!r)return null;Tr=r,t.delete(Cr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function zn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function St(e){let t=(0,gt.useRef)(e);t.current=e,(0,gt.useEffect)(()=>{if(!wr())return;Jn();let r=o=>{if(!zn(o))return;let n=Jt();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var Rr=require("react");function ht(e=!0){(0,Rr.useEffect)(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}var be=require("react/jsx-runtime"),Xn="/api/urun-token",Gn=1e4;function Yn(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function Ar(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function Zn(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,be.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,be.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,be.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Ur({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,confirmOnLeave:f=!1,fallback:d,errorFallback:k,children:P}){let g=n===void 0&&t===void 0;if(!g&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!g&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let p=r??o;if(g&&(typeof p!="string"||p.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);ht(f);let[x,S]=(0,ne.useState)(),[N,C]=(0,ne.useState)(),[E,m]=(0,ne.useState)(null),L=(0,ne.useRef)(void 0),j=(0,ne.useRef)(null),[O,D]=(0,ne.useState)(null);St($=>D({jwt:$}));let l=ft(),T=ge("NEXT_PUBLIC_SESSION_TOKEN")??ge("NEXT_PUBLIC_URUN_JWT"),v=Ge(),_=O!==null,I=v==="workos"&&!n&&!_&&!g,Q=n??(v==="jwt"?T:void 0)??x??N?.token,A=_?O.jwt:Q,U=s??ge("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),q=I&&!A,W=t??N?.orgId,J=e??N?.gatewayUrl,B=g&&N===void 0,h=g&&N!==void 0&&!J?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,b=E??h,R=u??Xn,M=(0,ne.useCallback)(async $=>{if(!$?.forceRefresh){let Y=L.current;if(!Y)return Y;let me=Yn(Y);if(me===null||me-Date.now()>Gn)return Y}return(await(j.current??(j.current=(async()=>{try{let Y=await Ar(R);return L.current=Y.token,C(Y),Y}finally{j.current=null}})()))).token},[R]),z=(0,ne.useMemo)(()=>({appId:p,baseUrl:J??"",orgId:W??"",jwt:A,getAccessToken:I?l?.getAccessToken:g&&!_?M:void 0,authProvider:U,eventsUrl:i,sessionKey:a,releaseOnLeave:c,priority:_?"preempt":void 0}),[p,l,J,U,A,i,W,a,c,I,_,g,M]);return(0,ne.useEffect)(()=>{if(!g)return;let $=new AbortController;return m(null),(async()=>{try{let y=await Ar(R,$.signal);L.current=y.token,C(y)}catch(y){if($.signal.aborted)return;m(y instanceof Error?y:new Error(String(y)))}})(),()=>$.abort()},[g,R]),(0,ne.useEffect)(()=>{if(!I||!l)return;let $=!1,y=l;async function Y(){try{let dt=await y.getAccessToken();$||S(dt??void 0)}catch{$||S(void 0)}}Y();let me=window.setInterval(()=>{Y()},6e4);return()=>{$=!0,window.clearInterval(me)}},[l,I]),(0,be.jsx)(Ie,{fallback:d,children:b?Zn(k,b):q||B?(0,be.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,be.jsx)(Le.Provider,{value:z,children:P})})}var oe=require("react"),Mr=require("@urun-sh/core");function Qn(e,t){return`${e}:${JSON.stringify(t??{})}`}function eo(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var we=new Map;var zt=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},Xt=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},Gt=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new zt(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new Xt(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function _r(){let e=(0,oe.useContext)(Le);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,oe.useReducer)(i=>i+1,0),r=(0,oe.useRef)(new Map),o=(0,oe.useRef)(new Map),n=(0,oe.useRef)(null),s=(0,oe.useMemo)(()=>(0,Mr.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,priority:e.priority}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority]);return(0,oe.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=we.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let f=we.get(u);f===c&&(f.handle.removeNotifier(t),f.refCount=Math.max(0,f.refCount-1),a.set(u,f),f.refCount===0&&(f.disposeTimer=setTimeout(()=>{let d=we.get(u);!d||d.refCount!==0||(we.delete(u),d.handle.disconnect())},0)))}n.current=a}},[]),(0,oe.useMemo)(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let f=d=>{let k=Qn(u,d),P=r.current.get(k);if(P&&!P.disposed)return P;let g=eo(e,u,d),p=we.get(g);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),we.delete(g),o.current.get(g)===p&&o.current.delete(g),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new Gt(s[u](d),t,e.eventsUrl),refCount:0,disposeTimer:null},we.set(g,p)),o.current.get(g)!==p&&(o.current.set(g,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(k,p.handle),p.handle};return i.set(u,f),f}})},[e,s])}var ee=require("react");function De(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function to(e){return e instanceof Error?e:new Error(String(e))}function Nr(e,t){let r=(0,ee.useMemo)(()=>De(e),[e]),[o,n]=(0,ee.useState)(void 0),[s,i]=(0,ee.useState)(null),[a,u]=(0,ee.useState)(!1),c=(0,ee.useRef)(t);c.current=t;let f=(0,ee.useRef)(0),d=(0,ee.useRef)(null),k=(0,ee.useRef)(!0);(0,ee.useEffect)(()=>(k.current=!0,()=>{k.current=!1,d.current?.abort()}),[]);let P=(0,ee.useCallback)(async x=>{d.current?.abort();let S=new AbortController;d.current=S;let N=++f.current,C=()=>k.current&&f.current===N;C()&&(u(!0),i(null));try{let E=await r.request(x,{...c.current,signal:S.signal});return C()&&(n(E),u(!1),c.current?.onSuccess?.(E)),E}catch(E){let m=to(E);throw C()&&(i(m),u(!1),c.current?.onError?.(m)),m}},[r]),g=(0,ee.useCallback)(x=>{P(x).catch(()=>{})},[P]),p=(0,ee.useCallback)(()=>{f.current++,d.current?.abort(),d.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:g,mutateAsync:P,data:o,error:s,isPending:a,reset:p}}var te=require("react");function Ir(e){return e instanceof Error?e:new Error(String(e))}var ro=e=>typeof e=="string"?e:String(e);function Lr(e,t){let r=(0,te.useMemo)(()=>De(e),[e]),[o,n]=(0,te.useState)(""),[s,i]=(0,te.useState)(!1),[a,u]=(0,te.useState)(null),c=(0,te.useRef)(t);c.current=t;let f=(0,te.useRef)(0),d=(0,te.useRef)(null),k=(0,te.useRef)(!0);(0,te.useEffect)(()=>(k.current=!0,()=>{k.current=!1,d.current?.cancel(),d.current=null}),[]);let P=(0,te.useCallback)(()=>{f.current++,d.current?.cancel(),d.current=null,k.current&&i(!1)},[]),g=(0,te.useCallback)(async p=>{d.current?.cancel();let x=++f.current,S=()=>k.current&&f.current===x,N=c.current,C=N?.parseChunk??ro,E=N?.buildPayload??(v=>({prompt:v}));S()&&(n(""),u(null),i(!0));let{parseChunk:m,buildPayload:L,onFinish:j,onError:O,...D}=N??{},l="",T;try{T=r.requestStream(E(p),D),d.current=T}catch(v){let _=Ir(v);S()&&(u(_),i(!1),N?.onError?.(_));return}try{for await(let v of T){if(f.current!==x)break;l+=C(v),S()&&n(l)}S()&&(i(!1),N?.onFinish?.(l))}catch(v){let _=Ir(v);S()&&(u(_),i(!1),N?.onError?.(_))}finally{d.current===T&&(d.current=null)}},[r]);return{completion:o,complete:g,stop:P,isStreaming:s,error:a}}var Z=require("react");function Or(e){return e instanceof Error?e:new Error(String(e))}var no=e=>typeof e=="string"?e:String(e),Dr=0;function Yt(e){return Dr+=1,`${e}-${Dr}`}function Vr(e,t){let r=(0,Z.useMemo)(()=>De(e),[e]),[o,n]=(0,Z.useState)(()=>(t?.initialMessages??[]).map(C=>({id:C.id??Yt("msg"),role:C.role,content:C.content}))),[s,i]=(0,Z.useState)(""),[a,u]=(0,Z.useState)(!1),[c,f]=(0,Z.useState)(null),d=(0,Z.useRef)(t);d.current=t;let k=(0,Z.useRef)(o);k.current=o;let P=(0,Z.useRef)(s);P.current=s;let g=(0,Z.useRef)(0),p=(0,Z.useRef)(null),x=(0,Z.useRef)(!0);(0,Z.useEffect)(()=>(x.current=!0,()=>{x.current=!1,p.current?.cancel(),p.current=null}),[]);let S=(0,Z.useCallback)(()=>{g.current++,p.current?.cancel(),p.current=null,x.current&&u(!1)},[]),N=(0,Z.useCallback)(async C=>{let E=C===void 0,m=(E?P.current:C)??"";if(!m.trim())return;p.current?.cancel();let j=++g.current,O=()=>x.current&&g.current===j,D=d.current,l=D?.parseChunk??no,T={id:Yt("msg"),role:"user",content:m},v={id:Yt("msg"),role:"assistant",content:""},_=[...k.current,T].map(M=>({role:M.role,content:M.content})),I=[...k.current,T,v];k.current=I,n(I),E&&i(""),f(null),u(!0);let Q=D?.buildPayload??(M=>({messages:M})),{initialMessages:A,parseChunk:U,buildPayload:q,onFinish:W,onError:J,...B}=D??{},h=M=>{n(z=>z.map($=>$.id===v.id?{...$,content:M}:$))},b="",R;try{R=r.requestStream(Q(_),B),p.current=R}catch(M){let z=Or(M);O()&&(f(z),u(!1),D?.onError?.(z));return}try{for await(let M of R){if(g.current!==j)break;b+=l(M),O()&&h(b)}O()&&(u(!1),D?.onFinish?.({...v,content:b}))}catch(M){let z=Or(M);O()&&(f(z),u(!1),D?.onError?.(z))}finally{p.current===R&&(p.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:N,stop:S,isStreaming:a,error:c}}var G=require("react"),Ve=require("@urun-sh/core"),Zt=[];function Fr(e,t={}){let{field:r=Ve.INPUT_PRESENCE_FIELD,hz:o=Ve.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,G.useMemo)(()=>s?(0,Ve.createInputPresencePublisher)({awareness:{setLocalStateField:(m,L)=>s.setField(m,L)},field:r,hz:o}):null,[s,r,o]),a=(0,G.useRef)(null);a.current=i;let[u,c]=(0,G.useState)(!1),[f,d]=(0,G.useState)(Zt),k=(0,G.useRef)(!1);(0,G.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let P=(0,G.useCallback)(()=>{let m=a.current;d(m?m.heldKeys():Zt)},[]),g=(0,G.useCallback)(()=>{a.current?.clear(),d(Zt)},[]);(0,G.useEffect)(()=>{if(!n)return;let m=()=>!!n.pointerLockElement,L=()=>{if(m()){k.current=!1,c(!0);return}k.current||(c(!1),g())},j=v=>{m()&&(a.current?.keyDown(v.key),P())},O=v=>{a.current?.keyUp(v.key),P()},D=v=>{m()&&a.current?.movePointer(v.movementX,v.movementY)},l=v=>{m()&&a.current?.setButtons(v.buttons)},T=()=>{g()};return n.addEventListener("pointerlockchange",L),n.addEventListener("keydown",j),n.addEventListener("keyup",O),n.addEventListener("mousemove",D),n.addEventListener("mousedown",l),n.addEventListener("mouseup",l),n.defaultView?.addEventListener("blur",T),()=>{n.removeEventListener("pointerlockchange",L),n.removeEventListener("keydown",j),n.removeEventListener("keyup",O),n.removeEventListener("mousemove",D),n.removeEventListener("mousedown",l),n.removeEventListener("mouseup",l),n.defaultView?.removeEventListener("blur",T)}},[n,g,P]);let p=(0,G.useCallback)(m=>{m.requestPointerLock?.()},[]),x=(0,G.useCallback)(()=>{k.current=!0,c(!0)},[]),S=(0,G.useCallback)(()=>{k.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),g()},[n,g]),N=(0,G.useCallback)(m=>{a.current?.keyDown(m),P()},[P]),C=(0,G.useCallback)(m=>{a.current?.keyUp(m),P()},[P]),E=(0,G.useCallback)((m,L)=>{a.current?.movePointer(m,L)},[]);return{engage:p,engageTouch:x,release:S,engaged:u,heldKeys:f,pressKey:N,releaseKey:C,movePointer:E}}var qr=new Map;function Hr(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);qr.set(e,{component:t,schema:r})}function Wr(e,t){let r=qr.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}var Re=require("react/jsx-runtime");function Br({name:e,props:t,fallback:r}){let o=Wr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,Re.jsx)(Re.Fragment,{children:r}):(0,Re.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,Re.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,Re.jsx)(n,{...o.validatedProps})}var Fe=require("zod"),Ae=require("react/jsx-runtime"),$r=Fe.z.object({step:Fe.z.number().min(0),total:Fe.z.number().min(1),label:Fe.z.string().optional(),variant:Fe.z.enum(["default","success","error"]).default("default")});function Qt(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function Kr(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Qt(e);return(0,Ae.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Ae.jsx)("div",{className:"urun-progress-label",children:o}),(0,Ae.jsx)("div",{className:"urun-progress-bar",children:(0,Ae.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Ae.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var vt=require("zod"),Ye=require("react/jsx-runtime"),jr=vt.z.object({state:vt.z.enum(["thinking","generating","idle","error"]),message:vt.z.string().optional()}),oo={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function er(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??oo[t]??t;return{state:t,message:n,isActive:o}}function Jr(e){let{state:t,message:r,isActive:o}=er(e);return(0,Ye.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,Ye.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,Ye.jsx)("span",{className:"urun-status-message",children:r})]})}var Ze=require("react"),yt=require("zod"),Qe=require("react/jsx-runtime"),zr=yt.z.object({text:yt.z.string(),streaming:yt.z.boolean().default(!1)});function tr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Xr(e){let{text:t,streaming:r}=tr(e),o=(0,Ze.useRef)(null),n=(0,Ze.useRef)(0);return(0,Ze.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,Qe.jsxs)("div",{className:"urun-text-stream",children:[(0,Qe.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,Qe.jsx)("span",{className:"urun-text-cursor"})]})}var et=require("zod"),tt=require("react/jsx-runtime"),Gr=et.z.object({src:et.z.string().url(),alt:et.z.string().optional(),caption:et.z.string().optional()});function rr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Yr(e){let{src:t,alt:r,caption:o}=rr(e);return(0,tt.jsxs)("figure",{className:"urun-image-frame",children:[(0,tt.jsx)("img",{className:"urun-image",src:t,alt:r}),o&&(0,tt.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var Se=require("zod"),qe=require("react/jsx-runtime"),Zr=Se.z.object({metrics:Se.z.array(Se.z.object({label:Se.z.string(),value:Se.z.union([Se.z.string(),Se.z.number()]),unit:Se.z.string().optional()}))});function nr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Qr(e){let{metrics:t}=nr(e);return(0,qe.jsx)("div",{className:"urun-metrics-panel",children:t.map((r,o)=>(0,qe.jsxs)("div",{className:"urun-metric-card",children:[(0,qe.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,qe.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var rt=require("react"),rn=require("react/jsx-runtime"),or=(0,rt.createContext)(null);function en({session:e,children:t}){return(0,rn.jsx)(or.Provider,{value:e,children:t})}function pe(){return(0,rt.useContext)(or)}function tn(){let e=(0,rt.useContext)(or);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}var V=require("react");var nt=require("react/jsx-runtime"),nn=1e3;function so(...e){console.debug("[video]",...e)}var kt=(0,V.forwardRef)(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:u=!1,objectFit:c="contain",className:f,style:d,videoClassName:k,placeholder:P,poster:g,children:p,onTrack:x,onFirstFrame:S}=t,N=pe(),C=o??N,E=(0,V.useRef)(null),m=(0,V.useRef)(null),[L,j]=(0,V.useState)(!1),[O,D]=(0,V.useState)(!1),l=(0,V.useRef)(!1),T=(0,V.useRef)(x);T.current=x;let v=(0,V.useRef)(S);v.current=S;let _=(0,V.useRef)(null),I=(0,V.useRef)(null),Q=(0,V.useCallback)(h=>{if(h===_.current||(_.current=h,I.current?.(),I.current=null,l.current=!1,D(!1),!h))return;let b=E.current;if(!b)return;let R=()=>{I.current?.(),I.current=null,l.current=!0,D(!0),v.current?.()};if(typeof b.requestVideoFrameCallback=="function"){let z=b.requestVideoFrameCallback(R);I.current=()=>b.cancelVideoFrameCallback?.(z);return}let M=()=>{let z=b.getVideoPlaybackQuality?.();(z?z.totalVideoFrames>0:b.readyState>=2&&b.videoWidth>0)&&R()};b.addEventListener("loadeddata",M),b.addEventListener("timeupdate",M),b.addEventListener("playing",M),I.current=()=>{b.removeEventListener("loadeddata",M),b.removeEventListener("timeupdate",M),b.removeEventListener("playing",M)},M()},[]);(0,V.useEffect)(()=>()=>{I.current?.(),I.current=null},[]);let A=(0,V.useCallback)(()=>{if(typeof MediaStream>"u")return null;m.current||(m.current=new MediaStream);let h=E.current;return h&&h.srcObject!==m.current&&(h.srcObject=m.current),m.current},[]),U=(0,V.useCallback)(h=>{let b=E.current;if(!b)return;let R=b.play();!R||typeof R.catch!="function"||R.catch(M=>so(`play() failed (${h})`,M))},[]),q=(0,V.useCallback)(h=>{let b=A();if(b){for(let R of b.getVideoTracks())R!==h&&b.removeTrack(R);if(h&&!b.getVideoTracks().includes(h)){b.addTrack(h);let R=E.current;R&&(R.srcObject=b)}h&&U("track-attach"),j(h!==null),Q(h),T.current?.(h)}},[A,U,Q]),W=(0,V.useCallback)(h=>{let b=A();if(b){for(let R of b.getAudioTracks())R!==h&&b.removeTrack(R);h&&!b.getAudioTracks().includes(h)&&b.addTrack(h),h&&U("audio-attach")}},[A,U]),J=(0,V.useCallback)(h=>{E.current=h,h&&(a&&(h.muted=!0,h.defaultMuted=!0,h.setAttribute("muted","")),h.setAttribute("playsinline",""),h.setAttribute("webkit-playsinline",""),A())},[A,a]);(0,V.useImperativeHandle)(r,()=>({get element(){return E.current},get live(){return m.current?m.current.getVideoTracks().length>0:!1},get framed(){return l.current}}),[]);let B=i!==void 0;return(0,V.useEffect)(()=>{if(B){q(i??null);return}if(!C)return;let h=C.stream(n),b=()=>{let y=m.current;return y?y.getVideoTracks()[0]??null:null},R=y=>{if(y!==b()&&(q(y),y)){let Y=()=>{b()===y&&q(null)};y.addEventListener("ended",Y)}},M=h.track;M&&M.readyState==="live"&&R(M);let z=h.on("track",y=>{y&&y.readyState!=="live"||R(y)}),$=setInterval(()=>{let y=h.track;y&&y.readyState==="live"&&R(y)},nn);return()=>{z(),clearInterval($)}},[C,n,B,i,q]),(0,V.useEffect)(()=>{if(B||!C||s===!1)return;let h=C.stream(s),b=()=>{let y=m.current;return y?y.getAudioTracks()[0]??null:null},R=y=>{if(y!==b()&&(W(y),y)){let Y=()=>{b()===y&&W(null)};y.addEventListener("ended",Y)}},M=h.track;M&&M.readyState==="live"&&R(M);let z=h.on("track",y=>{y&&y.readyState!=="live"||R(y)}),$=setInterval(()=>{let y=h.track;y&&y.readyState==="live"&&R(y)},nn);return()=>{z(),clearInterval($)}},[C,s,B,W]),(0,nt.jsxs)("div",{className:f,style:{position:"relative",width:"100%",height:"100%",...d},"data-urun-video":"","data-urun-video-live":L?"true":"false","data-urun-video-framed":O?"true":"false",children:[(0,nt.jsx)("video",{ref:J,className:k,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...u?{transform:"scaleX(-1)"}:{}}}),L?null:P,g===void 0?null:(0,nt.jsx)("div",{"data-urun-video-poster":"","aria-hidden":O||void 0,style:{position:"absolute",inset:0,...O?{opacity:0,pointerEvents:"none"}:null},children:g}),p]})});var on=require("react");var an=require("react/jsx-runtime"),sn=(0,on.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,an.jsx)(kt,{ref:r,stream:o,...n})});var K=require("react"),cn=require("@urun-sh/core");var bt=null;function io(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function ot(){if(bt)return bt;let e=io();return e?(bt=new e,bt):null}function st(){let e=ot();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var dn=require("react/jsx-runtime"),ao=1e3,un=200;function sr(...e){console.debug("[audio]",...e)}var it=(0,K.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:f}=t,d=pe(),k=o??d,P=(0,K.useRef)(null),g=(0,K.useRef)(null),p=(0,K.useRef)(null),x=(0,K.useRef)(null),S=(0,K.useRef)(u);S.current=u;let N=(0,K.useRef)(c);N.current=c;let C=(0,K.useCallback)(l=>{p.current!==l&&(p.current=l,N.current?.(l))},[]),E=(0,K.useCallback)(()=>{if(typeof MediaStream>"u")return null;g.current||(g.current=new MediaStream);let l=P.current;return l&&l.srcObject!==g.current&&(l.srcObject=g.current),g.current},[]),m=(0,K.useCallback)(l=>{let T=P.current;if(!T)return;let v=T.play();!v||typeof v.then!="function"||v.then(()=>{T.muted||C(!0)}).catch(_=>{let I=_ instanceof Error?_.name:String(_);if(I==="AbortError"){sr(`play() aborted (${l}); retrying in ${un}ms`),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{x.current=null,m(`${l}:retry`)},un);return}if(I==="NotAllowedError"){sr(`play() blocked pending a user gesture (${l})`),C(!1);return}sr(`play() failed (${l})`,_)})},[C]),L=(0,K.useCallback)(l=>{let T=E();if(T){for(let v of T.getAudioTracks())v!==l&&T.removeTrack(v);l&&!T.getAudioTracks().includes(l)&&T.addTrack(l),l&&m("track-attach"),S.current?.(l)}},[E,m]),j=(0,K.useCallback)(()=>{let l=P.current;l&&(E(),l.muted=!1,m("gesture"),st(),C(!0))},[E,m,C]);(0,K.useImperativeHandle)(r,()=>({unlock:j,get unlocked(){return p.current===!0},get element(){return P.current}}),[j]);let O=(0,K.useCallback)(l=>{P.current=l,l&&(l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),E()),f?.(l)},[E,f]),D=s!==void 0;return(0,K.useEffect)(()=>{if(D){L(s??null);return}if(!k)return;let l=k.stream(n),T=()=>{let A=g.current;return A?A.getAudioTracks()[0]??null:null},v=A=>{if(A!==T()&&(L(A),A)){let U=()=>{T()===A&&L(null)};A.addEventListener("ended",U)}},_=l.track;_&&_.readyState==="live"&&v(_);let I=l.on("track",A=>{A&&A.readyState!=="live"||v(A)}),Q=setInterval(()=>{let A=l.track;A&&A.readyState==="live"&&v(A)},ao);return()=>{I(),clearInterval(Q)}},[k,n,D,s,L]),(0,K.useEffect)(()=>(0,cn.observePageLifecycle)(()=>{st(),p.current===!0&&m("foreground")}),[m]),(0,K.useEffect)(()=>()=>{x.current&&clearTimeout(x.current)},[]),(0,dn.jsx)("audio",{ref:O,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),ln=it;var H=require("react"),He=require("@urun-sh/core");var mn=require("react/jsx-runtime"),ir={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Pt(...e){console.debug("[voice]",...e)}var at=(0,H.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=ir,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:f,onError:d,onMicStream:k,onTrack:P,onUnlockChange:g,capture:p}=t,x=pe(),S=o??x,N=(0,H.useRef)(null),C=(0,H.useRef)(null),E=(0,H.useRef)(null),m=(0,H.useRef)([]),L=(0,H.useRef)(!1),j=(0,H.useRef)(f);j.current=f;let O=(0,H.useRef)(d);O.current=d;let D=(0,H.useRef)(k);D.current=k;let l=(0,H.useCallback)(U=>{L.current!==U&&(L.current=U,j.current?.(U))},[]),T=(0,H.useCallback)(()=>{for(let U of m.current)U();m.current=[],E.current?.release(),E.current=null,C.current&&(C.current=null,D.current?.(null))},[]),v=(0,H.useCallback)(async()=>{let U=E.current;if(U){let B=await U.update(i);return C.current=U.stream,D.current?.(U.stream),B}let W=await(p??(0,He.sharedCaptureController)()).claim("audio",i);E.current=W,m.current=[W.onTrack((B,h)=>{C.current=h,D.current?.(h),L.current&&S?.stream(n).attach(B).catch(b=>Pt("mic re-attach after one-capture re-acquire failed",b))}),W.onLost(B=>{E.current=null,m.current=[],C.current=null,D.current?.(null),l(!1),O.current?.(B)})],C.current=W.stream,D.current?.(W.stream);let J=W.track;if(!J)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return J},[p,i,S,n,l]),_=(0,H.useCallback)(async()=>{T(),l(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,T,l]),I=(0,H.useCallback)(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");N.current?.unlock();let U;try{U=await v()}catch(J){T();let B=(0,He.sessionFailureFromMediaError)(J,S.status);throw O.current?.(B),B}S.connect?.();let q;for(let J=1;J<=u;J++)try{await S.whenLive(a!==void 0?{timeout:a}:void 0),await S.stream(n).attach(U),l(!0);return}catch(B){q=B,Pt(`start attempt ${J}/${u} failed`,B),J<u&&await new Promise(h=>setTimeout(h,c))}T(),l(!1);let W=q instanceof Error?q:new Error(String(q??"voice start failed"));throw O.current?.(W),W},[S,n,a,u,c,v,T,l]);(0,H.useImperativeHandle)(r,()=>({start:I,stop:_,unlock:()=>N.current?.unlock(),get active(){return L.current},get micStream(){return C.current},get audio(){return N.current}}),[I,_]);let Q=(0,H.useRef)(!1),A=(0,H.useCallback)(async()=>{if(!S||!L.current||Q.current)return;let U=C.current?.getAudioTracks()[0]??null;if(U&&U.readyState==="live"){try{await S.stream(n).attach(U)}catch(q){Pt("foreground mic re-assert failed (will retry on next pass)",q)}return}Q.current=!0;try{let q=await v();await S.stream(n).attach(q)}catch(q){let W=q instanceof Error?q:new Error(String(q));Pt("foreground mic re-acquire failed",W),O.current?.(W)}finally{Q.current=!1}},[S,n,v]);return(0,H.useEffect)(()=>{let U=()=>{A()};return S&&typeof S.onRecovery=="function"?S.onRecovery(U):(0,He.observePageLifecycle)(U)},[S,A]),(0,H.useEffect)(()=>T,[T]),s?(0,mn.jsx)(it,{ref:N,session:S,stream:n,onTrack:P,onUnlockChange:g}):null}),pn=at;var le=require("react");var Ct=require("react");var ar={level:0,speaking:!1};function xt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,Ct.useState)(ar);return(0,Ct.useEffect)(()=>{if(!e){i(ar);return}let a=ot();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,f;try{c=a.createMediaStreamSource(u),f=a.createAnalyser(),f.fftSize=r,c.connect(f)}catch{return}let d=new Uint8Array(f.fftSize),P=setInterval(()=>{f.getByteTimeDomainData(d);let g=0;for(let x=0;x<d.length;x++){let S=(d[x]-128)/128;g+=S*S}let p=Math.sqrt(g/d.length);i(x=>{let S=p>n;return Math.abs(x.level-p)<.005&&x.speaking===S?x:{level:p,speaking:S}})},o);return()=>{clearInterval(P),c.disconnect(),i(ar)}},[e,r,o,n]),s}var he=require("react/jsx-runtime"),uo={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},co={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},fn=(0,le.forwardRef)(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:f,onMicStream:d,capture:k}=t,P=pe(),g=o??P,p=(0,le.useRef)(null),[x,S]=(0,le.useState)(null),N=(0,le.useRef)(d);N.current=d;let{level:C,speaking:E}=xt(a?x:null);return(0,le.useImperativeHandle)(r,()=>({start:()=>{let m=p.current;return m?m.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>p.current?.stop()??Promise.resolve(),get active(){return p.current?.active??!1},get micStream(){return p.current?.micStream??null}}),[]),(0,le.useEffect)(()=>{!i||!g||p.current?.start().catch(()=>{})},[i,g]),(0,he.jsxs)(he.Fragment,{children:[(0,he.jsx)(at,{ref:p,session:g,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...k!==void 0?{capture:k}:{},onActiveChange:c,onError:f,onMicStream:m=>{S(m),N.current?.(m)}}),a?(0,he.jsx)("span",{className:u,style:uo,"data-urun-mic":"","data-urun-mic-active":x?"true":"false","data-urun-mic-speaking":E?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(C*100)/100,children:(0,he.jsx)("span",{style:co,children:(0,he.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(C*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var Tt=require("@urun-sh/core"),w=require("react");var ae=require("react/jsx-runtime"),cr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function ur(...e){console.debug("[camera]",...e)}function lo(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function po(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var lr=(0,w.forwardRef)(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:f="auto",connectTimeoutMs:d,visible:k=!1,className:P,videoClassName:g,onActiveChange:p,onError:x,onStream:S,onTrack:N,children:C,capture:E,flipControl:m="auto",flipControlClassName:L,onDevices:j}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let O=i?"user":a?"environment":u??"environment",D=pe(),l=o??D,T=(0,w.useRef)(null),v=(0,w.useRef)(null),_=(0,w.useRef)(null),I=(0,w.useRef)([]),Q=(0,w.useRef)(null),A=(0,w.useRef)(!1),U=(0,w.useRef)(O),[q,W]=(0,w.useState)(O),[J,B]=(0,w.useState)(!1),[h,b]=(0,w.useState)(null),[R,M]=(0,w.useState)(!1),[z]=(0,w.useState)(lo),$=(0,w.useRef)(p);$.current=p;let y=(0,w.useRef)(x);y.current=x;let Y=(0,w.useRef)(S);Y.current=S;let me=(0,w.useRef)(N);me.current=N;let dt=(0,w.useRef)(j);dt.current=j;let ke=(0,w.useCallback)(F=>{A.current!==F&&(A.current=F,B(F),$.current?.(F))},[]);(0,w.useEffect)(()=>{if(!J){b(null);return}let F=!1,X=()=>{po().then(ie=>{F||(b(ie),ie&&dt.current?.(ie))})};X();let re=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof re?.addEventListener=="function"?(re.addEventListener("devicechange",X),()=>{F=!0,re.removeEventListener?.("devicechange",X)}):()=>{F=!0}},[J]);let pt=(0,w.useCallback)(F=>{let X=T.current;X&&(X.muted=!0,X.defaultMuted=!0,X.setAttribute("muted",""),X.setAttribute("playsinline",""),X.setAttribute("webkit-playsinline",""),X.srcObject=F,F&&X.play()?.catch?.(re=>ur("preview play() failed",re)))},[]),fe=(0,w.useCallback)(()=>{Q.current?.(),Q.current=null;for(let F of I.current)F();I.current=[],_.current?.release(),_.current=null,v.current&&(v.current=null,Y.current?.(null),me.current?.(null)),pt(null)},[pt]),Bt=(0,w.useCallback)((F,X)=>{Q.current?.(),v.current=X,pt(X),Y.current?.(X);let re=()=>{v.current===X&&(ur("camera track ended (device removed or permission revoked)"),fe(),ke(!1))};F.addEventListener("ended",re),Q.current=()=>F.removeEventListener("ended",re)},[pt,fe,ke]),_e=(0,w.useCallback)(async F=>{if(!l)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let X={...cr,...s,facingMode:F},re;try{let ie=_.current;if(ie)re=await ie.update(X);else{let Je=await(E??(0,Tt.sharedCaptureController)()).claim("video",X);if(_.current=Je,I.current=[Je.onTrack((ze,Fn)=>{Bt(ze,Fn),A.current&&l.stream(n).attachVideo(ze).then(()=>me.current?.(ze)).catch(qn=>ur("camera re-publish after one-capture re-acquire failed",qn))}),Je.onLost(ze=>{_.current=null,I.current=[],fe(),ke(!1),y.current?.(ze)})],!Je.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});re=Je.track}}catch(ie){let Ne=(0,Tt.sessionFailureFromMediaError)(ie,l.status);throw y.current?.(Ne),Ne}U.current=F,W(F),Bt(re,_.current?.stream??new MediaStream([re]));try{l.connect?.(),await l.whenLive(d!==void 0?{timeout:d}:void 0),await l.stream(n).attachVideo(re)}catch(ie){fe(),ke(!1);let Ne=ie instanceof Error?ie:new Error(String(ie));throw y.current?.(Ne),Ne}me.current?.(re),ke(!0)},[l,n,s,d,E,Bt,fe,ke]),fr=(0,w.useCallback)(F=>_e(F?.facingMode??U.current),[_e]),mt=(0,w.useCallback)(async F=>{A.current&&U.current===F||await _e(F)},[_e]),$t=(0,w.useCallback)(()=>_e(U.current==="environment"?"user":"environment"),[_e]),gr=(0,w.useCallback)(async()=>{fe(),ke(!1),await l?.stream(n).detachVideo().catch(()=>{})},[l,n,fe,ke]);(0,w.useImperativeHandle)(r,()=>({start:fr,stop:gr,flip:$t,setFacingMode:mt,get active(){return A.current},get facingMode(){return U.current},get stream(){return v.current},get element(){return T.current}}),[fr,gr,$t,mt]);let Sr=(0,w.useRef)(mt);if(Sr.current=mt,(0,w.useEffect)(()=>{!c||!l||Sr.current(O).catch(()=>{})},[c,l,O]),(0,w.useEffect)(()=>fe,[fe]),!k)return null;let On=f==="auto"?q==="user":f,Dn=J&&(m===!0||m==="auto"&&z&&(h?.length??0)>1),Vn=()=>{R||(M(!0),$t().catch(()=>{}).finally(()=>M(!1)))};return(0,ae.jsxs)("div",{className:P,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":q,children:[(0,ae.jsx)("video",{ref:T,className:g,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...On?{transform:"scaleX(-1)"}:{}}}),Dn?(0,ae.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Vn,disabled:R,className:L,style:L?{opacity:R?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:R?.6:1},children:(0,ae.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[(0,ae.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,ae.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,ae.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,ae.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,ae.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,C]})}),gn=(0,w.forwardRef)(function({preview:t=!0,...r},o){return(0,ae.jsx)(lr,{ref:o,...r,visible:t,autoStart:!1})});var Et=require("react");function Sn(e,t){let[r,o]=(0,Et.useState)(null);return(0,Et.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var yn=require("react");var Rt=require("react");var hn=require("zustand/vanilla"),vn=require("zustand"),mo=()=>{};function wt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=(0,hn.createStore)(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):mo,u=(c=>(0,vn.useStore)(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function We(e,t){let r=(0,Rt.useMemo)(()=>wt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,Rt.useEffect)(()=>r.bind(),[r]),r}function kn(e,t,r){let n=We(e,t)(r??(a=>a)),s=(0,yn.useCallback)(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}var Ut=require("react");var Pe=200;function ve(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Be(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function At(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Mt(e,t,r={}){let o=r.cap??200,[n,s]=(0,Ut.useState)([]);return(0,Ut.useEffect)(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>ve(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}var de=require("react/jsx-runtime");function bn({session:e,name:t,cap:r,className:o}){let n=Mt(e,t,{cap:r});return(0,de.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,de.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,de.jsx)("code",{children:t}),(0,de.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,de.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,de.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,de.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,i)=>(0,de.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,de.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Be(s.payload)]},`${s.at}-${i}`))})]})}var ut=require("react");var se=require("react/jsx-runtime");function ct({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,ut.useState)(""),[i,a]=(0,ut.useState)(null),u=(0,ut.useCallback)(()=>{let c=At(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return(0,se.jsxs)("div",{className:"urun-doc-patch",children:[(0,se.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),(0,se.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,se.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?(0,se.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function Pn({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=We(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return(0,se.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,se.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,se.jsx)("code",{children:t}),(0,se.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,se.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,se.jsx)(ct,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}var _t=require("react");var ye=require("react/jsx-runtime");function Cn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function xn({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=(0,_t.useState)([]);return(0,_t.useEffect)(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>ve(u,{at:Date.now(),direction:"in",text:Cn(Be(a))},r))}):void 0),[e,t,r]),(0,ye.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,ye.jsx)(ct,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>ve(u,{at:Date.now(),direction:"out",text:Cn(a)},r))}}),(0,ye.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,ye.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>(0,ye.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,ye.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,ye.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}var Nt=require("react");var Ue=require("react/jsx-runtime");function Tn({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=(0,Nt.useState)([]),a=t.join(","),u=r.join(",");return(0,Nt.useEffect)(()=>{if(i([]),!e)return;let c=(d,k)=>i(P=>ve(P,{at:Date.now(),kind:d,text:k},o)),f=[];f.push(e.onPhase(d=>c("phase",`phase \u2192 ${d.name}`)));for(let d of t){let k=e.stream(d);f.push(k.on("track",P=>c("track",`${d}: ${P?"track arrived":"track ended"}`)))}for(let d of r){let k=e.doc(d);f.push(k.on("change",()=>c("doc",`${d} changed`)))}return()=>f.forEach(d=>d())},[e,a,u,o]),(0,Ue.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,Ue.jsx)("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((c,f)=>(0,Ue.jsxs)("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[(0,Ue.jsx)("span",{className:"urun-event-spine-kind",children:c.kind})," ",(0,Ue.jsx)("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${f}`))})}var qt=require("@urun-sh/core");var It=require("react");function ue(e){let[t,r]=(0,It.useState)(e?.phase??null);return(0,It.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var wn=require("@urun-sh/core");var $e=require("react"),En=require("@urun-sh/core");function Lt(e){let t=ue(e),r=(0,En.isWakingPhase)(t?.name),o=(0,$e.useRef)(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=(0,$e.useState)(s);return(0,$e.useEffect)(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}var Ce=require("react/jsx-runtime");function Ot({session:e,render:t,className:r}){let o=Lt(e);return!o.waking||!o.phase?null:(0,Ce.jsx)("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):(0,Ce.jsxs)(Ce.Fragment,{children:[(0,Ce.jsx)("span",{className:"urun-session-waking-label",children:(0,wn.describeSessionPhase)(o.phase)})," ",(0,Ce.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var Vt=require("react");var xe=require("react"),fo={event:null,elapsedMs:0};function Dt(e,t){let[r,o]=(0,xe.useState)(null),n=(0,xe.useRef)(0);(0,xe.useEffect)(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=(0,xe.useState)(0);return(0,xe.useEffect)(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:fo}var Ke=require("react/jsx-runtime"),go={activating:"starting stream\u2026","still-activating":"model warming up \u2014 this can take a minute","cold-boot":"cold boot \u2014 compiling/loading the model, hang tight",degraded:"taking longer than usual \u2014 still trying"};function So(e){let[t,r]=(0,Vt.useState)(!1);return(0,Vt.useEffect)(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function Ft({session:e,stream:t,videoElement:r,render:o,className:n}){let s=Dt(e,t),i=So(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return(0,Ke.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):(0,Ke.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,Ke.jsx)("span",{className:"urun-activation-overlay-copy",children:a.hint??go[u]})," ",(0,Ke.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var ce=require("react/jsx-runtime"),ho={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function Rn({session:e,className:t}){let r=ue(e),o=r?.name??"idle",n=r?.name==="queued"&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:(r?.name==="error"||r?.name==="expired")&&r.error?r.error.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return(0,ce.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,ce.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,ce.jsx)("span",{className:"urun-session-status-label",children:ho[o]}),n?(0,ce.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function An({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=ue(e);if(s?.name==="live")return(0,ce.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,ce.jsx)(Ft,{session:e})]});let i=r?r(s):(0,ce.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&(0,qt.isWakingPhase)(s.name)?(0,ce.jsx)(Ot,{session:e}):s&&s.name!=="idle"?(0,qt.describeSessionPhase)(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return(0,ce.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,ce.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var Ht=require("react");var Mn=require("react/jsx-runtime");function dr(e){return ue(e)?.endsAt??null}function vo(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function Un({session:e,urgentMs:t=6e4,className:r}){let n=dr(e)?.getTime()??null,[s,i]=(0,Ht.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,Ht.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=vo(s);return(0,Mn.jsx)("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}var lt=require("react/jsx-runtime"),yo=new Set(["expired","ended","error"]);function _n({session:e,onNewSession:t,children:r,className:o}){let n=ue(e);if(!n||!yo.has(n.name))return null;let s=r?r(n):(0,lt.jsx)("span",{className:"urun-session-ended-copy",children:n.name==="expired"?"Session ended \u2014 start a new session":n.name==="error"?`Session failed${n.error?.reason?` \u2014 ${n.error.reason}`:""}.`:"Session ended."});return(0,lt.jsxs)("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?(0,lt.jsx)("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}var Te=require("react"),Me=require("react/jsx-runtime");function pr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function mr(e){let t=(0,Te.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,Te.useState)(()=>t?pr(t.get("idle")):null);return(0,Te.useEffect)(()=>{if(!t){o(null);return}return o(pr(t.get("idle"))),t.on("change",()=>o(pr(t.get("idle"))))},[t]),r}function ko(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Nn({session:e,onStillHere:t,className:r}){let o=mr(e),n=o?.deadlineEpochS??null,[s,i]=(0,Te.useState)(null);if((0,Te.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return(0,Me.jsx)("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:(0,Me.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,Me.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,Me.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${ko(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,Me.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var je=require("react"),In=require("@urun-sh/core");function Ln(e){let t=(0,je.useContext)(Le),[r,o]=(0,je.useState)(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,f=t?.getAccessToken,d=t?.authProvider;return(0,je.useEffect)(()=>{if(!a||!u||!n||!s)return;let k=!1,P=()=>{(0,In.prewake)({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:f,authProvider:d}).then(p=>{k||o(p)}).catch(()=>{})};P();let g=setInterval(P,Math.max(1,i)*1e3);return()=>{k=!0,clearInterval(g)}},[n,s,i,a,u,c,f,d]),r}var Wt=require("@urun-sh/core");0&&(module.exports={Audio,Camera,ComponentRenderer,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,Image,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,Mic,OPERATOR_CHORD_LABEL,OPERATOR_TOKEN_STORAGE_KEY,ProgressCard,ProgressCardSchema,Session,StatusBadge,StatusBadgeSchema,TextStream,TextStreamSchema,UrunActivationOverlay,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunIdleWarning,UrunJwtProvider,UrunProvider,UrunSessionClock,UrunSessionEnded,UrunSessionGate,UrunSessionStatus,UrunSessionWaking,UrunStreamTail,UrunVoice,Video,Voice,authMode,createDocStore,describeSessionPhase,formatPayload,getUrunAudioContext,isWakingPhase,parseJsonObject,pushCapped,readOperatorToken,registerComponent,resumeUrunAudioContext,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useConfirmOnLeave,useDocStore,useImageFrame,useInputPresence,useMetricsPanel,useOperatorOverride,useProgressCard,useRequest,useSession,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client"
|
|
2
|
-
import{a as Kr,b as Jr,c as ot}from"./chunk-WF2OBDSX.mjs";import{useCallback as sn,useEffect as jt,useMemo as an,useRef as Kt,useState as Ve}from"react";import{Component as zr}from"react";import{jsx as qt,jsxs as Xr}from"react/jsx-runtime";var we=class extends zr{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||Xr("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[qt("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),qt("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as Gr}from"react";var he=Gr(null);function ce(e){return e&&e.trim()?e.trim():void 0}function oe(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return ce(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return ce(typeof process<"u"?process.env?.[e]:void 0)}}function De(){let e=oe("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||oe("VERCEL_ENV")==="production"?"workos":oe("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Yr(){return De()==="workos"}import{useEffect as Zr,useRef as Qr}from"react";var en="urun.operator_token",Wt=null,Ht="op",tn="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function Bt(){return typeof window<"u"}function $t(){return Wt}function rn(){if(!Bt())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(Ht);if(!r)return null;Wt=r,t.delete(Ht);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function nn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function st(e){let t=Qr(e);t.current=e,Zr(()=>{if(!Bt())return;rn();let r=o=>{if(!nn(o))return;let n=$t();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as on}from"react";function it(e=!0){on(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}import{jsx as xe,jsxs as mn}from"react/jsx-runtime";var un="/api/urun-token",cn=1e4;function ln(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function Jt(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function dn(e,t){return typeof e=="function"?e(t):e!==void 0?e:mn("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[xe("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),xe("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function pn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,confirmOnLeave:m=!1,fallback:d,errorFallback:y,children:k}){let f=n===void 0&&t===void 0;if(!f&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!f&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let p=r??o;if(f&&(typeof p!="string"||p.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);it(m);let[P,S]=Ve(),[R,b]=Ve(),[E,g]=Ve(null),M=Kt(void 0),V=Kt(null),[N,U]=Ve(null);st(B=>U({jwt:B}));let l=ot(),x=oe("NEXT_PUBLIC_SESSION_TOKEN")??oe("NEXT_PUBLIC_URUN_JWT"),v=De(),w=N!==null,D=v==="workos"&&!n&&!w&&!f,j=n??(v==="jwt"?x:void 0)??P??R?.token,A=w?N.jwt:j,T=s??oe("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),F=D&&!A,q=t??R?.orgId,h=e??R?.gatewayUrl,C=f&&R===void 0,I=f&&R!==void 0&&!h?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,L=E??I,H=u??un,W=sn(async B=>{if(!B?.forceRefresh){let K=M.current;if(!K)return K;let Q=ln(K);if(Q===null||Q-Date.now()>cn)return K}return(await(V.current??(V.current=(async()=>{try{let K=await Jt(H);return M.current=K.token,b(K),K}finally{V.current=null}})()))).token},[H]),_=an(()=>({appId:p,baseUrl:h??"",orgId:q??"",jwt:A,getAccessToken:D?l?.getAccessToken:f&&!w?W:void 0,authProvider:T,eventsUrl:i,sessionKey:a,releaseOnLeave:c,priority:w?"preempt":void 0}),[p,l,h,T,A,i,q,a,c,D,w,f,W]);return jt(()=>{if(!f)return;let B=new AbortController;return g(null),(async()=>{try{let z=await Jt(H,B.signal);M.current=z.token,b(z)}catch(z){if(B.signal.aborted)return;g(z instanceof Error?z:new Error(String(z)))}})(),()=>B.abort()},[f,H]),jt(()=>{if(!D||!l)return;let B=!1,z=l;async function K(){try{let Ie=await z.getAccessToken();B||S(Ie??void 0)}catch{B||S(void 0)}}K();let Q=window.setInterval(()=>{K()},6e4);return()=>{B=!0,window.clearInterval(Q)}},[l,D]),xe(we,{fallback:d,children:L?dn(y,L):F||C?xe("div",{role:"status","aria-live":"polite",children:"Signing in..."}):xe(he.Provider,{value:_,children:k})})}import{useContext as fn,useEffect as gn,useMemo as zt,useReducer as Sn,useRef as at}from"react";import{App as hn}from"@urun-sh/core";function vn(e,t){return`${e}:${JSON.stringify(t??{})}`}function yn(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var le=new Map;var ut=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},ct=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},lt=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new ut(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new ct(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function kn(){let e=fn(he);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=Sn(i=>i+1,0),r=at(new Map),o=at(new Map),n=at(null),s=zt(()=>hn(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,priority:e.priority}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority]);return gn(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=le.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let m=le.get(u);m===c&&(m.handle.removeNotifier(t),m.refCount=Math.max(0,m.refCount-1),a.set(u,m),m.refCount===0&&(m.disposeTimer=setTimeout(()=>{let d=le.get(u);!d||d.refCount!==0||(le.delete(u),d.handle.disconnect())},0)))}n.current=a}},[]),zt(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let m=d=>{let y=vn(u,d),k=r.current.get(y);if(k&&!k.disposed)return k;let f=yn(e,u,d),p=le.get(f);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),le.delete(f),o.current.get(f)===p&&o.current.delete(f),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new lt(s[u](d),t,e.eventsUrl),refCount:0,disposeTimer:null},le.set(f,p)),o.current.get(f)!==p&&(o.current.set(f,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(y,p.handle),p.handle};return i.set(u,m),m}})},[e,s])}import{useCallback as dt,useEffect as bn,useMemo as Cn,useRef as Fe,useState as pt}from"react";function ve(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function Pn(e){return e instanceof Error?e:new Error(String(e))}function En(e,t){let r=Cn(()=>ve(e),[e]),[o,n]=pt(void 0),[s,i]=pt(null),[a,u]=pt(!1),c=Fe(t);c.current=t;let m=Fe(0),d=Fe(null),y=Fe(!0);bn(()=>(y.current=!0,()=>{y.current=!1,d.current?.abort()}),[]);let k=dt(async P=>{d.current?.abort();let S=new AbortController;d.current=S;let R=++m.current,b=()=>y.current&&m.current===R;b()&&(u(!0),i(null));try{let E=await r.request(P,{...c.current,signal:S.signal});return b()&&(n(E),u(!1),c.current?.onSuccess?.(E)),E}catch(E){let g=Pn(E);throw b()&&(i(g),u(!1),c.current?.onError?.(g)),g}},[r]),f=dt(P=>{k(P).catch(()=>{})},[k]),p=dt(()=>{m.current++,d.current?.abort(),d.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:f,mutateAsync:k,data:o,error:s,isPending:a,reset:p}}import{useCallback as Xt,useEffect as wn,useMemo as xn,useRef as qe,useState as mt}from"react";function Gt(e){return e instanceof Error?e:new Error(String(e))}var Tn=e=>typeof e=="string"?e:String(e);function Rn(e,t){let r=xn(()=>ve(e),[e]),[o,n]=mt(""),[s,i]=mt(!1),[a,u]=mt(null),c=qe(t);c.current=t;let m=qe(0),d=qe(null),y=qe(!0);wn(()=>(y.current=!0,()=>{y.current=!1,d.current?.cancel(),d.current=null}),[]);let k=Xt(()=>{m.current++,d.current?.cancel(),d.current=null,y.current&&i(!1)},[]),f=Xt(async p=>{d.current?.cancel();let P=++m.current,S=()=>y.current&&m.current===P,R=c.current,b=R?.parseChunk??Tn,E=R?.buildPayload??(v=>({prompt:v}));S()&&(n(""),u(null),i(!0));let{parseChunk:g,buildPayload:M,onFinish:V,onError:N,...U}=R??{},l="",x;try{x=r.requestStream(E(p),U),d.current=x}catch(v){let w=Gt(v);S()&&(u(w),i(!1),R?.onError?.(w));return}try{for await(let v of x){if(m.current!==P)break;l+=b(v),S()&&n(l)}S()&&(i(!1),R?.onFinish?.(l))}catch(v){let w=Gt(v);S()&&(u(w),i(!1),R?.onError?.(w))}finally{d.current===x&&(d.current=null)}},[r]);return{completion:o,complete:f,stop:k,isStreaming:s,error:a}}import{useCallback as Yt,useEffect as An,useMemo as Un,useRef as ye,useState as He}from"react";function Zt(e){return e instanceof Error?e:new Error(String(e))}var Mn=e=>typeof e=="string"?e:String(e),Qt=0;function ft(e){return Qt+=1,`${e}-${Qt}`}function _n(e,t){let r=Un(()=>ve(e),[e]),[o,n]=He(()=>(t?.initialMessages??[]).map(b=>({id:b.id??ft("msg"),role:b.role,content:b.content}))),[s,i]=He(""),[a,u]=He(!1),[c,m]=He(null),d=ye(t);d.current=t;let y=ye(o);y.current=o;let k=ye(s);k.current=s;let f=ye(0),p=ye(null),P=ye(!0);An(()=>(P.current=!0,()=>{P.current=!1,p.current?.cancel(),p.current=null}),[]);let S=Yt(()=>{f.current++,p.current?.cancel(),p.current=null,P.current&&u(!1)},[]),R=Yt(async b=>{let E=b===void 0,g=(E?k.current:b)??"";if(!g.trim())return;p.current?.cancel();let V=++f.current,N=()=>P.current&&f.current===V,U=d.current,l=U?.parseChunk??Mn,x={id:ft("msg"),role:"user",content:g},v={id:ft("msg"),role:"assistant",content:""},w=[...y.current,x].map(W=>({role:W.role,content:W.content})),D=[...y.current,x,v];y.current=D,n(D),E&&i(""),m(null),u(!0);let j=U?.buildPayload??(W=>({messages:W})),{initialMessages:A,parseChunk:T,buildPayload:F,onFinish:q,onError:h,...C}=U??{},I=W=>{n(_=>_.map(B=>B.id===v.id?{...B,content:W}:B))},L="",H;try{H=r.requestStream(j(w),C),p.current=H}catch(W){let _=Zt(W);N()&&(m(_),u(!1),U?.onError?.(_));return}try{for await(let W of H){if(f.current!==V)break;L+=l(W),N()&&I(L)}N()&&(u(!1),U?.onFinish?.({...v,content:L}))}catch(W){let _=Zt(W);N()&&(m(_),u(!1),U?.onError?.(_))}finally{p.current===H&&(p.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:R,stop:S,isStreaming:a,error:c}}import{useCallback as se,useEffect as er,useMemo as Nn,useRef as tr,useState as rr}from"react";import{createInputPresencePublisher as In,INPUT_PRESENCE_DEFAULT_HZ as Ln,INPUT_PRESENCE_FIELD as On}from"@urun-sh/core";var gt=[];function Dn(e,t={}){let{field:r=On,hz:o=Ln}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=Nn(()=>s?In({awareness:{setLocalStateField:(g,M)=>s.setField(g,M)},field:r,hz:o}):null,[s,r,o]),a=tr(null);a.current=i;let[u,c]=rr(!1),[m,d]=rr(gt),y=tr(!1);er(()=>{if(i)return()=>i.dispose()},[i]);let k=se(()=>{let g=a.current;d(g?g.heldKeys():gt)},[]),f=se(()=>{a.current?.clear(),d(gt)},[]);er(()=>{if(!n)return;let g=()=>!!n.pointerLockElement,M=()=>{if(g()){y.current=!1,c(!0);return}y.current||(c(!1),f())},V=v=>{g()&&(a.current?.keyDown(v.key),k())},N=v=>{a.current?.keyUp(v.key),k()},U=v=>{g()&&a.current?.movePointer(v.movementX,v.movementY)},l=v=>{g()&&a.current?.setButtons(v.buttons)},x=()=>{f()};return n.addEventListener("pointerlockchange",M),n.addEventListener("keydown",V),n.addEventListener("keyup",N),n.addEventListener("mousemove",U),n.addEventListener("mousedown",l),n.addEventListener("mouseup",l),n.defaultView?.addEventListener("blur",x),()=>{n.removeEventListener("pointerlockchange",M),n.removeEventListener("keydown",V),n.removeEventListener("keyup",N),n.removeEventListener("mousemove",U),n.removeEventListener("mousedown",l),n.removeEventListener("mouseup",l),n.defaultView?.removeEventListener("blur",x)}},[n,f,k]);let p=se(g=>{g.requestPointerLock?.()},[]),P=se(()=>{y.current=!0,c(!0)},[]),S=se(()=>{y.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),f()},[n,f]),R=se(g=>{a.current?.keyDown(g),k()},[k]),b=se(g=>{a.current?.keyUp(g),k()},[k]),E=se((g,M)=>{a.current?.movePointer(g,M)},[]);return{engage:p,engageTouch:P,release:S,engaged:u,heldKeys:m,pressKey:R,releaseKey:b,movePointer:E}}var nr=new Map;function Vn(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);nr.set(e,{component:t,schema:r})}function or(e,t){let r=nr.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}import{Fragment as qn,jsx as We}from"react/jsx-runtime";function Fn({name:e,props:t,fallback:r}){let o=or(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?We(qn,{children:r}):We("div",{className:"urun-component-error",role:"alert",children:We("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return We(n,{...o.validatedProps})}import{z as Te}from"zod";import{jsx as St,jsxs as sr}from"react/jsx-runtime";var Hn=Te.object({step:Te.number().min(0),total:Te.number().min(1),label:Te.string().optional(),variant:Te.enum(["default","success","error"]).default("default")});function ir(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function Wn(e){let{step:t,total:r,label:o,variant:n,percentage:s}=ir(e);return sr("div",{className:"urun-progress-card","data-variant":n,children:[o&&St("div",{className:"urun-progress-label",children:o}),St("div",{className:"urun-progress-bar",children:St("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),sr("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as ht}from"zod";import{jsx as ar,jsxs as Kn}from"react/jsx-runtime";var Bn=ht.object({state:ht.enum(["thinking","generating","idle","error"]),message:ht.string().optional()}),$n={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function ur(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??$n[t]??t;return{state:t,message:n,isActive:o}}function jn(e){let{state:t,message:r,isActive:o}=ur(e);return Kn("span",{className:"urun-status-badge","data-state":t,children:[ar("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),ar("span",{className:"urun-status-message",children:r})]})}import{useRef as cr,useEffect as Jn}from"react";import{z as vt}from"zod";import{jsx as lr,jsxs as Gn}from"react/jsx-runtime";var zn=vt.object({text:vt.string(),streaming:vt.boolean().default(!1)});function dr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Xn(e){let{text:t,streaming:r}=dr(e),o=cr(null),n=cr(0);return Jn(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),Gn("div",{className:"urun-text-stream",children:[lr("span",{ref:o,className:"urun-text-content"}),r&&lr("span",{className:"urun-text-cursor"})]})}import{z as Be}from"zod";import{jsx as pr,jsxs as Qn}from"react/jsx-runtime";var Yn=Be.object({src:Be.string().url(),alt:Be.string().optional(),caption:Be.string().optional()});function mr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Zn(e){let{src:t,alt:r,caption:o}=mr(e);return Qn("figure",{className:"urun-image-frame",children:[pr("img",{className:"urun-image",src:t,alt:r}),o&&pr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as ie}from"zod";import{jsx as yt,jsxs as ro}from"react/jsx-runtime";var eo=ie.object({metrics:ie.array(ie.object({label:ie.string(),value:ie.union([ie.string(),ie.number()]),unit:ie.string().optional()}))});function fr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function to(e){let{metrics:t}=fr(e);return yt("div",{className:"urun-metrics-panel",children:t.map((r,o)=>ro("div",{className:"urun-metric-card",children:[yt("div",{className:"urun-metric-label",children:r.label}),yt("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{createContext as no,useContext as gr}from"react";import{jsx as io}from"react/jsx-runtime";var kt=no(null);function oo({session:e,children:t}){return io(kt.Provider,{value:e,children:t})}function Z(){return gr(kt)}function so(){let e=gr(kt);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}import{forwardRef as ao,useCallback as Re,useEffect as Sr,useImperativeHandle as uo,useRef as de,useState as hr}from"react";import{jsx as vr,jsxs as po}from"react/jsx-runtime";var co=1e3;function lo(...e){console.debug("[video]",...e)}var bt=ao(function(t,r){let{session:o,stream:n="video",track:s,muted:i=!0,mirror:a=!1,objectFit:u="contain",className:c,style:m,videoClassName:d,placeholder:y,poster:k,children:f,onTrack:p,onFirstFrame:P}=t,S=Z(),R=o??S,b=de(null),E=de(null),[g,M]=hr(!1),[V,N]=hr(!1),U=de(!1),l=de(p);l.current=p;let x=de(P);x.current=P;let v=de(null),w=de(null),D=Re(h=>{if(h===v.current||(v.current=h,w.current?.(),w.current=null,U.current=!1,N(!1),!h))return;let C=b.current;if(!C)return;let I=()=>{w.current?.(),w.current=null,U.current=!0,N(!0),x.current?.()};if(typeof C.requestVideoFrameCallback=="function"){let H=C.requestVideoFrameCallback(I);w.current=()=>C.cancelVideoFrameCallback?.(H);return}let L=()=>{let H=C.getVideoPlaybackQuality?.();(H?H.totalVideoFrames>0:C.readyState>=2&&C.videoWidth>0)&&I()};C.addEventListener("loadeddata",L),C.addEventListener("timeupdate",L),C.addEventListener("playing",L),w.current=()=>{C.removeEventListener("loadeddata",L),C.removeEventListener("timeupdate",L),C.removeEventListener("playing",L)},L()},[]);Sr(()=>()=>{w.current?.(),w.current=null},[]);let j=Re(()=>{if(typeof MediaStream>"u")return null;E.current||(E.current=new MediaStream);let h=b.current;return h&&h.srcObject!==E.current&&(h.srcObject=E.current),E.current},[]),A=Re(h=>{let C=b.current;if(!C)return;let I=C.play();!I||typeof I.catch!="function"||I.catch(L=>lo(`play() failed (${h})`,L))},[]),T=Re(h=>{let C=j();if(C){for(let I of C.getVideoTracks())I!==h&&C.removeTrack(I);if(h&&!C.getVideoTracks().includes(h)){C.addTrack(h);let I=b.current;I&&(I.srcObject=C)}h&&A("track-attach"),M(h!==null),D(h),l.current?.(h)}},[j,A,D]),F=Re(h=>{b.current=h,h&&(i&&(h.muted=!0,h.defaultMuted=!0,h.setAttribute("muted","")),h.setAttribute("playsinline",""),h.setAttribute("webkit-playsinline",""),j())},[j,i]);uo(r,()=>({get element(){return b.current},get live(){return E.current?E.current.getVideoTracks().length>0:!1},get framed(){return U.current}}),[]);let q=s!==void 0;return Sr(()=>{if(q){T(s??null);return}if(!R)return;let h=R.stream(n),C=()=>{let _=E.current;return _?_.getVideoTracks()[0]??null:null},I=_=>{if(_!==C()&&(T(_),_)){let B=()=>{C()===_&&T(null)};_.addEventListener("ended",B)}},L=h.track;L&&L.readyState==="live"&&I(L);let H=h.on("track",_=>{_&&_.readyState!=="live"||I(_)}),W=setInterval(()=>{let _=h.track;_&&_.readyState==="live"&&I(_)},co);return()=>{H(),clearInterval(W)}},[R,n,q,s,T]),po("div",{className:c,style:{position:"relative",width:"100%",height:"100%",...m},"data-urun-video":"","data-urun-video-live":g?"true":"false","data-urun-video-framed":V?"true":"false",children:[vr("video",{ref:F,className:d,autoPlay:!0,muted:i,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...a?{transform:"scaleX(-1)"}:{}}}),g?null:y,k===void 0?null:vr("div",{"data-urun-video-poster":"","aria-hidden":V||void 0,style:{position:"absolute",inset:0,...V?{opacity:0,pointerEvents:"none"}:null},children:k}),f]})});import{forwardRef as mo}from"react";import{jsx as go}from"react/jsx-runtime";var fo=mo(function(t,r){let{stream:o="image",...n}=t;return go(bt,{ref:r,stream:o,...n})});import{forwardRef as ho,useCallback as ke,useEffect as Ct,useImperativeHandle as vo,useRef as be}from"react";import{observePageLifecycle as yo}from"@urun-sh/core";var $e=null;function So(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function je(){if($e)return $e;let e=So();return e?($e=new e,$e):null}function Ke(){let e=je();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{jsx as Co}from"react/jsx-runtime";var ko=1e3,yr=200;function Pt(...e){console.debug("[audio]",...e)}var Je=ho(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:m}=t,d=Z(),y=o??d,k=be(null),f=be(null),p=be(null),P=be(null),S=be(u);S.current=u;let R=be(c);R.current=c;let b=ke(l=>{p.current!==l&&(p.current=l,R.current?.(l))},[]),E=ke(()=>{if(typeof MediaStream>"u")return null;f.current||(f.current=new MediaStream);let l=k.current;return l&&l.srcObject!==f.current&&(l.srcObject=f.current),f.current},[]),g=ke(l=>{let x=k.current;if(!x)return;let v=x.play();!v||typeof v.then!="function"||v.then(()=>{x.muted||b(!0)}).catch(w=>{let D=w instanceof Error?w.name:String(w);if(D==="AbortError"){Pt(`play() aborted (${l}); retrying in ${yr}ms`),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{P.current=null,g(`${l}:retry`)},yr);return}if(D==="NotAllowedError"){Pt(`play() blocked pending a user gesture (${l})`),b(!1);return}Pt(`play() failed (${l})`,w)})},[b]),M=ke(l=>{let x=E();if(x){for(let v of x.getAudioTracks())v!==l&&x.removeTrack(v);l&&!x.getAudioTracks().includes(l)&&x.addTrack(l),l&&g("track-attach"),S.current?.(l)}},[E,g]),V=ke(()=>{let l=k.current;l&&(E(),l.muted=!1,g("gesture"),Ke(),b(!0))},[E,g,b]);vo(r,()=>({unlock:V,get unlocked(){return p.current===!0},get element(){return k.current}}),[V]);let N=ke(l=>{k.current=l,l&&(l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),E()),m?.(l)},[E,m]),U=s!==void 0;return Ct(()=>{if(U){M(s??null);return}if(!y)return;let l=y.stream(n),x=()=>{let A=f.current;return A?A.getAudioTracks()[0]??null:null},v=A=>{if(A!==x()&&(M(A),A)){let T=()=>{x()===A&&M(null)};A.addEventListener("ended",T)}},w=l.track;w&&w.readyState==="live"&&v(w);let D=l.on("track",A=>{A&&A.readyState!=="live"||v(A)}),j=setInterval(()=>{let A=l.track;A&&A.readyState==="live"&&v(A)},ko);return()=>{D(),clearInterval(j)}},[y,n,U,s,M]),Ct(()=>yo(()=>{Ke(),p.current===!0&&g("foreground")}),[g]),Ct(()=>()=>{P.current&&clearTimeout(P.current)},[]),Co("audio",{ref:N,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),bo=Je;import{forwardRef as Po,useCallback as Ce,useEffect as kr,useImperativeHandle as Eo,useRef as te}from"react";import{observePageLifecycle as wo,sessionFailureFromMediaError as xo,sharedCaptureController as To}from"@urun-sh/core";import{jsx as Ao}from"react/jsx-runtime";var br={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function ze(...e){console.debug("[voice]",...e)}var Xe=Po(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=br,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:m,onError:d,onMicStream:y,onTrack:k,onUnlockChange:f,capture:p}=t,P=Z(),S=o??P,R=te(null),b=te(null),E=te(null),g=te([]),M=te(!1),V=te(m);V.current=m;let N=te(d);N.current=d;let U=te(y);U.current=y;let l=Ce(T=>{M.current!==T&&(M.current=T,V.current?.(T))},[]),x=Ce(()=>{for(let T of g.current)T();g.current=[],E.current?.release(),E.current=null,b.current&&(b.current=null,U.current?.(null))},[]),v=Ce(async()=>{let T=E.current;if(T){let C=await T.update(i);return b.current=T.stream,U.current?.(T.stream),C}let q=await(p??To()).claim("audio",i);E.current=q,g.current=[q.onTrack((C,I)=>{b.current=I,U.current?.(I),M.current&&S?.stream(n).attach(C).catch(L=>ze("mic re-attach after one-capture re-acquire failed",L))}),q.onLost(C=>{E.current=null,g.current=[],b.current=null,U.current?.(null),l(!1),N.current?.(C)})],b.current=q.stream,U.current?.(q.stream);let h=q.track;if(!h)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return h},[p,i,S,n,l]),w=Ce(async()=>{x(),l(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,x,l]),D=Ce(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");R.current?.unlock();let T;try{T=await v()}catch(h){x();let C=xo(h,S.status);throw N.current?.(C),C}S.connect?.();let F;for(let h=1;h<=u;h++)try{await S.whenLive(a!==void 0?{timeout:a}:void 0),await S.stream(n).attach(T),l(!0);return}catch(C){F=C,ze(`start attempt ${h}/${u} failed`,C),h<u&&await new Promise(I=>setTimeout(I,c))}x(),l(!1);let q=F instanceof Error?F:new Error(String(F??"voice start failed"));throw N.current?.(q),q},[S,n,a,u,c,v,x,l]);Eo(r,()=>({start:D,stop:w,unlock:()=>R.current?.unlock(),get active(){return M.current},get micStream(){return b.current},get audio(){return R.current}}),[D,w]);let j=te(!1),A=Ce(async()=>{if(!S||!M.current||j.current)return;let T=b.current?.getAudioTracks()[0]??null;if(T&&T.readyState==="live"){try{await S.stream(n).attach(T)}catch(F){ze("foreground mic re-assert failed (will retry on next pass)",F)}return}j.current=!0;try{let F=await v();await S.stream(n).attach(F)}catch(F){let q=F instanceof Error?F:new Error(String(F));ze("foreground mic re-acquire failed",q),N.current?.(q)}finally{j.current=!1}},[S,n,v]);return kr(()=>{let T=()=>{A()};return S&&typeof S.onRecovery=="function"?S.onRecovery(T):wo(T)},[S,A]),kr(()=>x,[x]),s?Ao(Je,{ref:R,session:S,stream:n,onTrack:k,onUnlockChange:f}):null}),Ro=Xe;import{forwardRef as _o,useEffect as No,useImperativeHandle as Io,useRef as Cr,useState as Lo}from"react";import{useEffect as Uo,useState as Mo}from"react";var Et={level:0,speaking:!1};function wt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=Mo(Et);return Uo(()=>{if(!e){i(Et);return}let a=je();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,m;try{c=a.createMediaStreamSource(u),m=a.createAnalyser(),m.fftSize=r,c.connect(m)}catch{return}let d=new Uint8Array(m.fftSize),k=setInterval(()=>{m.getByteTimeDomainData(d);let f=0;for(let P=0;P<d.length;P++){let S=(d[P]-128)/128;f+=S*S}let p=Math.sqrt(f/d.length);i(P=>{let S=p>n;return Math.abs(P.level-p)<.005&&P.speaking===S?P:{level:p,speaking:S}})},o);return()=>{clearInterval(k),c.disconnect(),i(Et)}},[e,r,o,n]),s}import{Fragment as Fo,jsx as Ge,jsxs as qo}from"react/jsx-runtime";var Oo={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Do={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Vo=_o(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:m,onMicStream:d,capture:y}=t,k=Z(),f=o??k,p=Cr(null),[P,S]=Lo(null),R=Cr(d);R.current=d;let{level:b,speaking:E}=wt(a?P:null);return Io(r,()=>({start:()=>{let g=p.current;return g?g.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>p.current?.stop()??Promise.resolve(),get active(){return p.current?.active??!1},get micStream(){return p.current?.micStream??null}}),[]),No(()=>{!i||!f||p.current?.start().catch(()=>{})},[i,f]),qo(Fo,{children:[Ge(Xe,{ref:p,session:f,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...y!==void 0?{capture:y}:{},onActiveChange:c,onError:m,onMicStream:g=>{S(g),R.current?.(g)}}),a?Ge("span",{className:u,style:Oo,"data-urun-mic":"","data-urun-mic-active":P?"true":"false","data-urun-mic-speaking":E?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(b*100)/100,children:Ge("span",{style:Do,children:Ge("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(b*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{sessionFailureFromMediaError as Ho,sharedCaptureController as Wo}from"@urun-sh/core";import{forwardRef as Er,useCallback as re,useEffect as xt,useImperativeHandle as Bo,useRef as X,useState as Ae}from"react";import{jsx as ae,jsxs as Pr}from"react/jsx-runtime";var wr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Tt(...e){console.debug("[camera]",...e)}function $o(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function jo(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var xr=Er(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:m="auto",connectTimeoutMs:d,visible:y=!1,className:k,videoClassName:f,onActiveChange:p,onError:P,onStream:S,onTrack:R,children:b,capture:E,flipControl:g="auto",flipControlClassName:M,onDevices:V}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let N=i?"user":a?"environment":u??"environment",U=Z(),l=o??U,x=X(null),v=X(null),w=X(null),D=X([]),j=X(null),A=X(!1),T=X(N),[F,q]=Ae(N),[h,C]=Ae(!1),[I,L]=Ae(null),[H,W]=Ae(!1),[_]=Ae($o),B=X(p);B.current=p;let z=X(P);z.current=P;let K=X(S);K.current=S;let Q=X(R);Q.current=R;let Ie=X(V);Ie.current=V;let ne=re(O=>{A.current!==O&&(A.current=O,C(O),B.current?.(O))},[]);xt(()=>{if(!h){L(null);return}let O=!1,$=()=>{jo().then(G=>{O||(L(G),G&&Ie.current?.(G))})};$();let J=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof J?.addEventListener=="function"?(J.addEventListener("devicechange",$),()=>{O=!0,J.removeEventListener?.("devicechange",$)}):()=>{O=!0}},[h]);let Le=re(O=>{let $=x.current;$&&($.muted=!0,$.defaultMuted=!0,$.setAttribute("muted",""),$.setAttribute("playsinline",""),$.setAttribute("webkit-playsinline",""),$.srcObject=O,O&&$.play()?.catch?.(J=>Tt("preview play() failed",J)))},[]),ee=re(()=>{j.current?.(),j.current=null;for(let O of D.current)O();D.current=[],w.current?.release(),w.current=null,v.current&&(v.current=null,K.current?.(null),Q.current?.(null)),Le(null)},[Le]),rt=re((O,$)=>{j.current?.(),v.current=$,Le($),K.current?.($);let J=()=>{v.current===$&&(Tt("camera track ended (device removed or permission revoked)"),ee(),ne(!1))};O.addEventListener("ended",J),j.current=()=>O.removeEventListener("ended",J)},[Le,ee,ne]),ge=re(async O=>{if(!l)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let $={...wr,...s,facingMode:O},J;try{let G=w.current;if(G)J=await G.update($);else{let Pe=await(E??Wo()).claim("video",$);if(w.current=Pe,D.current=[Pe.onTrack((Ee,$r)=>{rt(Ee,$r),A.current&&l.stream(n).attachVideo(Ee).then(()=>Q.current?.(Ee)).catch(jr=>Tt("camera re-publish after one-capture re-acquire failed",jr))}),Pe.onLost(Ee=>{w.current=null,D.current=[],ee(),ne(!1),z.current?.(Ee)})],!Pe.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});J=Pe.track}}catch(G){let Se=Ho(G,l.status);throw z.current?.(Se),Se}T.current=O,q(O),rt(J,w.current?.stream??new MediaStream([J]));try{l.connect?.(),await l.whenLive(d!==void 0?{timeout:d}:void 0),await l.stream(n).attachVideo(J)}catch(G){ee(),ne(!1);let Se=G instanceof Error?G:new Error(String(G));throw z.current?.(Se),Se}Q.current?.(J),ne(!0)},[l,n,s,d,E,rt,ee,ne]),Dt=re(O=>ge(O?.facingMode??T.current),[ge]),Oe=re(async O=>{A.current&&T.current===O||await ge(O)},[ge]),nt=re(()=>ge(T.current==="environment"?"user":"environment"),[ge]),Vt=re(async()=>{ee(),ne(!1),await l?.stream(n).detachVideo().catch(()=>{})},[l,n,ee,ne]);Bo(r,()=>({start:Dt,stop:Vt,flip:nt,setFacingMode:Oe,get active(){return A.current},get facingMode(){return T.current},get stream(){return v.current},get element(){return x.current}}),[Dt,Vt,nt,Oe]);let Ft=X(Oe);if(Ft.current=Oe,xt(()=>{!c||!l||Ft.current(N).catch(()=>{})},[c,l,N]),xt(()=>ee,[ee]),!y)return null;let Hr=m==="auto"?F==="user":m,Wr=h&&(g===!0||g==="auto"&&_&&(I?.length??0)>1),Br=()=>{H||(W(!0),nt().catch(()=>{}).finally(()=>W(!1)))};return Pr("div",{className:k,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":F,children:[ae("video",{ref:x,className:f,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Hr?{transform:"scaleX(-1)"}:{}}}),Wr?ae("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Br,disabled:H,className:M,style:M?{opacity:H?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:H?.6:1},children:Pr("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[ae("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),ae("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),ae("path",{d:"M14.5 10.5v1.6h-1.6"}),ae("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),ae("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,b]})}),Ko=Er(function({preview:t=!0,...r},o){return ae(xr,{ref:o,...r,visible:t,autoStart:!1})});import{useEffect as Jo,useState as zo}from"react";function Xo(e,t){let[r,o]=zo(null);return Jo(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}import{useCallback as ts}from"react";import{useEffect as Qo,useMemo as es}from"react";import{createStore as Go}from"zustand/vanilla";import{useStore as Yo}from"zustand";var Zo=()=>{};function Rt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=Go(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):Zo,u=(c=>Yo(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function Ue(e,t){let r=es(()=>Rt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return Qo(()=>r.bind(),[r]),r}function rs(e,t,r){let n=Ue(e,t)(r??(a=>a)),s=ts(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}import{useEffect as ns,useState as os}from"react";var pe=200;function ue(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Me(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function At(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Ut(e,t,r={}){let o=r.cap??200,[n,s]=os([]);return ns(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>ue(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}import{jsx as Ye,jsxs as _e}from"react/jsx-runtime";function ss({session:e,name:t,cap:r,className:o}){let n=Ut(e,t,{cap:r});return _e("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[_e("div",{className:"urun-stream-tail-meta",children:[Ye("code",{children:t}),_e("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),Ye("div",{className:"urun-stream-tail-log",children:n.length===0?_e("span",{className:"urun-stream-tail-empty",children:["Waiting for ",Ye("code",{children:t})," messages\u2026"]}):n.map((s,i)=>_e("div",{className:"urun-stream-tail-line",children:[Ye("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Me(s.payload)]},`${s.at}-${i}`))})]})}import{useCallback as is,useState as Tr}from"react";import{jsx as me,jsxs as Ze}from"react/jsx-runtime";function Qe({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=Tr(""),[i,a]=Tr(null),u=is(()=>{let c=At(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return Ze("div",{className:"urun-doc-patch",children:[me("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),Ze("div",{className:"urun-doc-patch-actions",children:[me("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?me("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function as({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Ue(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return Ze("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[Ze("div",{className:"urun-doc-panel-meta",children:[me("code",{children:t}),me("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),me("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?me(Qe,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}import{useEffect as us,useState as cs}from"react";import{jsx as Ne,jsxs as Ar}from"react/jsx-runtime";function Rr(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function ls({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=cs([]);return us(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>ue(u,{at:Date.now(),direction:"in",text:Rr(Me(a))},r))}):void 0),[e,t,r]),Ar("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[Ne(Qe,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>ue(u,{at:Date.now(),direction:"out",text:Rr(a)},r))}}),Ne("div",{className:"urun-control-sender-log",children:n.length===0?Ne("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>Ar("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[Ne("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",Ne("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}import{useEffect as ds,useState as ps}from"react";import{jsx as et,jsxs as fs}from"react/jsx-runtime";function ms({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=ps([]),a=t.join(","),u=r.join(",");return ds(()=>{if(i([]),!e)return;let c=(d,y)=>i(k=>ue(k,{at:Date.now(),kind:d,text:y},o)),m=[];m.push(e.onPhase(d=>c("phase",`phase \u2192 ${d.name}`)));for(let d of t){let y=e.stream(d);m.push(y.on("track",k=>c("track",`${d}: ${k?"track arrived":"track ended"}`)))}for(let d of r){let y=e.doc(d);m.push(y.on("change",()=>c("doc",`${d} changed`)))}return()=>m.forEach(d=>d())},[e,a,u,o]),et("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?et("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((c,m)=>fs("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[et("span",{className:"urun-event-spine-kind",children:c.kind})," ",et("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${m}`))})}import{describeSessionPhase as As,isWakingPhase as Us}from"@urun-sh/core";import{useEffect as gs,useState as Ss}from"react";function Y(e){let[t,r]=Ss(e?.phase??null);return gs(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as bs}from"@urun-sh/core";import{useEffect as hs,useRef as vs,useState as ys}from"react";import{isWakingPhase as ks}from"@urun-sh/core";function Mt(e){let t=Y(e),r=ks(t?.name),o=vs(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=ys(s);return hs(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}import{Fragment as Cs,jsx as Ur,jsxs as Mr}from"react/jsx-runtime";function _t({session:e,render:t,className:r}){let o=Mt(e);return!o.waking||!o.phase?null:Ur("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):Mr(Cs,{children:[Ur("span",{className:"urun-session-waking-label",children:bs(o.phase)})," ",Mr("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as ws,useState as xs}from"react";import{useEffect as _r,useRef as Ps,useState as Nr}from"react";var Es={event:null,elapsedMs:0};function Nt(e,t){let[r,o]=Nr(null),n=Ps(0);_r(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=Nr(0);return _r(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:Es}import{jsx as Ir,jsxs as Lr}from"react/jsx-runtime";var Ts={activating:"starting stream\u2026","still-activating":"model warming up \u2014 this can take a minute","cold-boot":"cold boot \u2014 compiling/loading the model, hang tight",degraded:"taking longer than usual \u2014 still trying"};function Rs(e){let[t,r]=xs(!1);return ws(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function It({session:e,stream:t,videoElement:r,render:o,className:n}){let s=Nt(e,t),i=Rs(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return Ir("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):Lr("div",{className:"urun-activation-overlay-card",children:[Ir("span",{className:"urun-activation-overlay-copy",children:a.hint??Ts[u]})," ",Lr("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as fe,jsxs as Lt}from"react/jsx-runtime";var Ms={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function _s({session:e,className:t}){let r=Y(e),o=r?.name??"idle",n=r?.name==="queued"&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:(r?.name==="error"||r?.name==="expired")&&r.error?r.error.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return Lt("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[fe("span",{className:"urun-session-status-dot","data-phase":o}),fe("span",{className:"urun-session-status-label",children:Ms[o]}),n?fe("span",{className:"urun-session-status-detail",children:n}):null]})}function Ns({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=Y(e);if(s?.name==="live")return Lt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,fe(It,{session:e})]});let i=r?r(s):fe("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&Us(s.name)?fe(_t,{session:e}):s&&s.name!=="idle"?As(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return Lt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?fe("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as Is,useState as Ls}from"react";import{jsx as Vs}from"react/jsx-runtime";function Or(e){return Y(e)?.endsAt??null}function Os(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function Ds({session:e,urgentMs:t=6e4,className:r}){let n=Or(e)?.getTime()??null,[s,i]=Ls(()=>n===null?null:Math.max(0,n-Date.now()));if(Is(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=Os(s);return Vs("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}import{jsx as Dr,jsxs as Hs}from"react/jsx-runtime";var Fs=new Set(["expired","ended","error"]);function qs({session:e,onNewSession:t,children:r,className:o}){let n=Y(e);if(!n||!Fs.has(n.name))return null;let s=r?r(n):Dr("span",{className:"urun-session-ended-copy",children:n.name==="expired"?"Session ended \u2014 start a new session":n.name==="error"?`Session failed${n.error?.reason?` \u2014 ${n.error.reason}`:""}.`:"Session ended."});return Hs("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?Dr("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}import{useEffect as Vr,useMemo as Ws,useState as Fr}from"react";import{jsx as tt,jsxs as js}from"react/jsx-runtime";function Ot(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function qr(e){let t=Ws(()=>e?e.doc("control"):null,[e]),[r,o]=Fr(()=>t?Ot(t.get("idle")):null);return Vr(()=>{if(!t){o(null);return}return o(Ot(t.get("idle"))),t.on("change",()=>o(Ot(t.get("idle"))))},[t]),r}function Bs(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function $s({session:e,onStillHere:t,className:r}){let o=qr(e),n=o?.deadlineEpochS??null,[s,i]=Fr(null);if(Vr(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return tt("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:js("div",{className:"urun-idle-warning-card",children:[tt("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),tt("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Bs(s)} due to inactivity.`:"This session will end soon due to inactivity."}),tt("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useContext as Ks,useEffect as Js,useState as zs}from"react";import{prewake as Xs}from"@urun-sh/core";function Gs(e){let t=Ks(he),[r,o]=zs(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,m=t?.getAccessToken,d=t?.authProvider;return Js(()=>{if(!a||!u||!n||!s)return;let y=!1,k=()=>{Xs({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:m,authProvider:d}).then(p=>{y||o(p)}).catch(()=>{})};k();let f=setInterval(k,Math.max(1,i)*1e3);return()=>{y=!0,clearInterval(f)}},[n,s,i,a,u,c,m,d]),r}import{describeSessionPhase as Gc,isWakingPhase as Yc}from"@urun-sh/core";export{Je as Audio,xr as Camera,Fn as ComponentRenderer,wr as DEFAULT_CAMERA_CONSTRAINTS,pe as DEFAULT_LOG_CAP,br as DEFAULT_VOICE_CONSTRAINTS,Qe as DocPatchForm,fo as Image,Zn as ImageFrame,Yn as ImageFrameSchema,to as MetricsPanel,eo as MetricsPanelSchema,Vo as Mic,tn as OPERATOR_CHORD_LABEL,en as OPERATOR_TOKEN_STORAGE_KEY,Wn as ProgressCard,Hn as ProgressCardSchema,oo as Session,jn as StatusBadge,Bn as StatusBadgeSchema,Xn as TextStream,zn as TextStreamSchema,It as UrunActivationOverlay,bo as UrunAudio,Kr as UrunAuthProvider,Ko as UrunCamera,ls as UrunControlSender,as as UrunDocPanel,we as UrunErrorBoundary,ms as UrunEventSpine,$s as UrunIdleWarning,Jr as UrunJwtProvider,pn as UrunProvider,Ds as UrunSessionClock,qs as UrunSessionEnded,Ns as UrunSessionGate,_s as UrunSessionStatus,_t as UrunSessionWaking,ss as UrunStreamTail,Ro as UrunVoice,bt as Video,Xe as Voice,De as authMode,Rt as createDocStore,Gc as describeSessionPhase,Me as formatPayload,je as getUrunAudioContext,Yc as isWakingPhase,At as parseJsonObject,ue as pushCapped,$t as readOperatorToken,Vn as registerComponent,Ke as resumeUrunAudioContext,oe as urunPublicEnv,Nt as useActivation,kn as useApp,_n as useChat,Rn as useCompletion,it as useConfirmOnLeave,Ue as useDocStore,mr as useImageFrame,Dn as useInputPresence,fr as useMetricsPanel,st as useOperatorOverride,ir as useProgressCard,En as useRequest,so as useSession,rs as useSessionDoc,Or as useSessionEndsAt,qr as useSessionIdle,Y as useSessionPhase,Xo as useSessionTrack,Mt as useSessionWake,ur as useStatusBadge,Ut as useStreamMessages,dr as useTextStream,wt as useUrunAudioLevel,ot as useUrunAuth,Gs as useUrunPrewake,Yr as usesWorkOSAuth};
|
|
2
|
+
import{a as Jr,b as zr,c as ot}from"./chunk-WF2OBDSX.mjs";import{useCallback as an,useEffect as Kt,useMemo as un,useRef as Jt,useState as Ve}from"react";import{Component as Xr}from"react";import{jsx as Ht,jsxs as Gr}from"react/jsx-runtime";var xe=class extends Xr{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||Gr("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[Ht("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),Ht("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as Yr}from"react";var he=Yr(null);function ce(e){return e&&e.trim()?e.trim():void 0}function oe(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return ce(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return ce(typeof process<"u"?process.env?.[e]:void 0)}}function De(){let e=oe("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||oe("VERCEL_ENV")==="production"?"workos":oe("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Zr(){return De()==="workos"}import{useEffect as Qr,useRef as en}from"react";var tn="urun.operator_token",Bt=null,Wt="op",rn="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function $t(){return typeof window<"u"}function jt(){return Bt}function nn(){if(!$t())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(Wt);if(!r)return null;Bt=r,t.delete(Wt);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function on(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function st(e){let t=en(e);t.current=e,Qr(()=>{if(!$t())return;nn();let r=o=>{if(!on(o))return;let n=jt();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as sn}from"react";function it(e=!0){sn(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}import{jsx as we,jsxs as fn}from"react/jsx-runtime";var cn="/api/urun-token",ln=1e4;function dn(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function zt(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function pn(e,t){return typeof e=="function"?e(t):e!==void 0?e:fn("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[we("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),we("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function mn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,confirmOnLeave:f=!1,fallback:d,errorFallback:k,children:C}){let g=n===void 0&&t===void 0;if(!g&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!g&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let p=r??o;if(g&&(typeof p!="string"||p.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);it(f);let[E,S]=Ve(),[_,P]=Ve(),[x,m]=Ve(null),I=Jt(void 0),W=Jt(null),[L,O]=Ve(null);st(H=>O({jwt:H}));let l=ot(),T=oe("NEXT_PUBLIC_SESSION_TOKEN")??oe("NEXT_PUBLIC_URUN_JWT"),v=De(),M=L!==null,N=v==="workos"&&!n&&!M&&!g,J=n??(v==="jwt"?T:void 0)??E??_?.token,R=M?L.jwt:J,A=s??oe("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),V=N&&!R,F=t??_?.orgId,B=e??_?.gatewayUrl,q=g&&_===void 0,h=g&&_!==void 0&&!B?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,b=x??h,w=u??cn,U=an(async H=>{if(!H?.forceRefresh){let K=I.current;if(!K)return K;let Q=dn(K);if(Q===null||Q-Date.now()>ln)return K}return(await(W.current??(W.current=(async()=>{try{let K=await zt(w);return I.current=K.token,P(K),K}finally{W.current=null}})()))).token},[w]),$=un(()=>({appId:p,baseUrl:B??"",orgId:F??"",jwt:R,getAccessToken:N?l?.getAccessToken:g&&!M?U:void 0,authProvider:A,eventsUrl:i,sessionKey:a,releaseOnLeave:c,priority:M?"preempt":void 0}),[p,l,B,A,R,i,F,a,c,N,M,g,U]);return Kt(()=>{if(!g)return;let H=new AbortController;return m(null),(async()=>{try{let y=await zt(w,H.signal);I.current=y.token,P(y)}catch(y){if(H.signal.aborted)return;m(y instanceof Error?y:new Error(String(y)))}})(),()=>H.abort()},[g,w]),Kt(()=>{if(!N||!l)return;let H=!1,y=l;async function K(){try{let Ie=await y.getAccessToken();H||S(Ie??void 0)}catch{H||S(void 0)}}K();let Q=window.setInterval(()=>{K()},6e4);return()=>{H=!0,window.clearInterval(Q)}},[l,N]),we(xe,{fallback:d,children:b?pn(k,b):V||q?we("div",{role:"status","aria-live":"polite",children:"Signing in..."}):we(he.Provider,{value:$,children:C})})}import{useContext as gn,useEffect as Sn,useMemo as Xt,useReducer as hn,useRef as at}from"react";import{App as vn}from"@urun-sh/core";function yn(e,t){return`${e}:${JSON.stringify(t??{})}`}function kn(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var le=new Map;var ut=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},ct=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},lt=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new ut(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new ct(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function bn(){let e=gn(he);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=hn(i=>i+1,0),r=at(new Map),o=at(new Map),n=at(null),s=Xt(()=>vn(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,priority:e.priority}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority]);return Sn(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=le.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let f=le.get(u);f===c&&(f.handle.removeNotifier(t),f.refCount=Math.max(0,f.refCount-1),a.set(u,f),f.refCount===0&&(f.disposeTimer=setTimeout(()=>{let d=le.get(u);!d||d.refCount!==0||(le.delete(u),d.handle.disconnect())},0)))}n.current=a}},[]),Xt(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let f=d=>{let k=yn(u,d),C=r.current.get(k);if(C&&!C.disposed)return C;let g=kn(e,u,d),p=le.get(g);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),le.delete(g),o.current.get(g)===p&&o.current.delete(g),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new lt(s[u](d),t,e.eventsUrl),refCount:0,disposeTimer:null},le.set(g,p)),o.current.get(g)!==p&&(o.current.set(g,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(k,p.handle),p.handle};return i.set(u,f),f}})},[e,s])}import{useCallback as dt,useEffect as Cn,useMemo as Pn,useRef as Fe,useState as pt}from"react";function ve(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function En(e){return e instanceof Error?e:new Error(String(e))}function Tn(e,t){let r=Pn(()=>ve(e),[e]),[o,n]=pt(void 0),[s,i]=pt(null),[a,u]=pt(!1),c=Fe(t);c.current=t;let f=Fe(0),d=Fe(null),k=Fe(!0);Cn(()=>(k.current=!0,()=>{k.current=!1,d.current?.abort()}),[]);let C=dt(async E=>{d.current?.abort();let S=new AbortController;d.current=S;let _=++f.current,P=()=>k.current&&f.current===_;P()&&(u(!0),i(null));try{let x=await r.request(E,{...c.current,signal:S.signal});return P()&&(n(x),u(!1),c.current?.onSuccess?.(x)),x}catch(x){let m=En(x);throw P()&&(i(m),u(!1),c.current?.onError?.(m)),m}},[r]),g=dt(E=>{C(E).catch(()=>{})},[C]),p=dt(()=>{f.current++,d.current?.abort(),d.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:g,mutateAsync:C,data:o,error:s,isPending:a,reset:p}}import{useCallback as Gt,useEffect as xn,useMemo as wn,useRef as qe,useState as mt}from"react";function Yt(e){return e instanceof Error?e:new Error(String(e))}var Rn=e=>typeof e=="string"?e:String(e);function An(e,t){let r=wn(()=>ve(e),[e]),[o,n]=mt(""),[s,i]=mt(!1),[a,u]=mt(null),c=qe(t);c.current=t;let f=qe(0),d=qe(null),k=qe(!0);xn(()=>(k.current=!0,()=>{k.current=!1,d.current?.cancel(),d.current=null}),[]);let C=Gt(()=>{f.current++,d.current?.cancel(),d.current=null,k.current&&i(!1)},[]),g=Gt(async p=>{d.current?.cancel();let E=++f.current,S=()=>k.current&&f.current===E,_=c.current,P=_?.parseChunk??Rn,x=_?.buildPayload??(v=>({prompt:v}));S()&&(n(""),u(null),i(!0));let{parseChunk:m,buildPayload:I,onFinish:W,onError:L,...O}=_??{},l="",T;try{T=r.requestStream(x(p),O),d.current=T}catch(v){let M=Yt(v);S()&&(u(M),i(!1),_?.onError?.(M));return}try{for await(let v of T){if(f.current!==E)break;l+=P(v),S()&&n(l)}S()&&(i(!1),_?.onFinish?.(l))}catch(v){let M=Yt(v);S()&&(u(M),i(!1),_?.onError?.(M))}finally{d.current===T&&(d.current=null)}},[r]);return{completion:o,complete:g,stop:C,isStreaming:s,error:a}}import{useCallback as Zt,useEffect as Un,useMemo as Mn,useRef as ye,useState as He}from"react";function Qt(e){return e instanceof Error?e:new Error(String(e))}var _n=e=>typeof e=="string"?e:String(e),er=0;function ft(e){return er+=1,`${e}-${er}`}function Nn(e,t){let r=Mn(()=>ve(e),[e]),[o,n]=He(()=>(t?.initialMessages??[]).map(P=>({id:P.id??ft("msg"),role:P.role,content:P.content}))),[s,i]=He(""),[a,u]=He(!1),[c,f]=He(null),d=ye(t);d.current=t;let k=ye(o);k.current=o;let C=ye(s);C.current=s;let g=ye(0),p=ye(null),E=ye(!0);Un(()=>(E.current=!0,()=>{E.current=!1,p.current?.cancel(),p.current=null}),[]);let S=Zt(()=>{g.current++,p.current?.cancel(),p.current=null,E.current&&u(!1)},[]),_=Zt(async P=>{let x=P===void 0,m=(x?C.current:P)??"";if(!m.trim())return;p.current?.cancel();let W=++g.current,L=()=>E.current&&g.current===W,O=d.current,l=O?.parseChunk??_n,T={id:ft("msg"),role:"user",content:m},v={id:ft("msg"),role:"assistant",content:""},M=[...k.current,T].map(U=>({role:U.role,content:U.content})),N=[...k.current,T,v];k.current=N,n(N),x&&i(""),f(null),u(!0);let J=O?.buildPayload??(U=>({messages:U})),{initialMessages:R,parseChunk:A,buildPayload:V,onFinish:F,onError:B,...q}=O??{},h=U=>{n($=>$.map(H=>H.id===v.id?{...H,content:U}:H))},b="",w;try{w=r.requestStream(J(M),q),p.current=w}catch(U){let $=Qt(U);L()&&(f($),u(!1),O?.onError?.($));return}try{for await(let U of w){if(g.current!==W)break;b+=l(U),L()&&h(b)}L()&&(u(!1),O?.onFinish?.({...v,content:b}))}catch(U){let $=Qt(U);L()&&(f($),u(!1),O?.onError?.($))}finally{p.current===w&&(p.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:_,stop:S,isStreaming:a,error:c}}import{useCallback as se,useEffect as tr,useMemo as In,useRef as rr,useState as nr}from"react";import{createInputPresencePublisher as Ln,INPUT_PRESENCE_DEFAULT_HZ as On,INPUT_PRESENCE_FIELD as Dn}from"@urun-sh/core";var gt=[];function Vn(e,t={}){let{field:r=Dn,hz:o=On}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=In(()=>s?Ln({awareness:{setLocalStateField:(m,I)=>s.setField(m,I)},field:r,hz:o}):null,[s,r,o]),a=rr(null);a.current=i;let[u,c]=nr(!1),[f,d]=nr(gt),k=rr(!1);tr(()=>{if(i)return()=>i.dispose()},[i]);let C=se(()=>{let m=a.current;d(m?m.heldKeys():gt)},[]),g=se(()=>{a.current?.clear(),d(gt)},[]);tr(()=>{if(!n)return;let m=()=>!!n.pointerLockElement,I=()=>{if(m()){k.current=!1,c(!0);return}k.current||(c(!1),g())},W=v=>{m()&&(a.current?.keyDown(v.key),C())},L=v=>{a.current?.keyUp(v.key),C()},O=v=>{m()&&a.current?.movePointer(v.movementX,v.movementY)},l=v=>{m()&&a.current?.setButtons(v.buttons)},T=()=>{g()};return n.addEventListener("pointerlockchange",I),n.addEventListener("keydown",W),n.addEventListener("keyup",L),n.addEventListener("mousemove",O),n.addEventListener("mousedown",l),n.addEventListener("mouseup",l),n.defaultView?.addEventListener("blur",T),()=>{n.removeEventListener("pointerlockchange",I),n.removeEventListener("keydown",W),n.removeEventListener("keyup",L),n.removeEventListener("mousemove",O),n.removeEventListener("mousedown",l),n.removeEventListener("mouseup",l),n.defaultView?.removeEventListener("blur",T)}},[n,g,C]);let p=se(m=>{m.requestPointerLock?.()},[]),E=se(()=>{k.current=!0,c(!0)},[]),S=se(()=>{k.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),g()},[n,g]),_=se(m=>{a.current?.keyDown(m),C()},[C]),P=se(m=>{a.current?.keyUp(m),C()},[C]),x=se((m,I)=>{a.current?.movePointer(m,I)},[]);return{engage:p,engageTouch:E,release:S,engaged:u,heldKeys:f,pressKey:_,releaseKey:P,movePointer:x}}var or=new Map;function Fn(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);or.set(e,{component:t,schema:r})}function sr(e,t){let r=or.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}import{Fragment as Hn,jsx as We}from"react/jsx-runtime";function qn({name:e,props:t,fallback:r}){let o=sr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?We(Hn,{children:r}):We("div",{className:"urun-component-error",role:"alert",children:We("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return We(n,{...o.validatedProps})}import{z as Re}from"zod";import{jsx as St,jsxs as ir}from"react/jsx-runtime";var Wn=Re.object({step:Re.number().min(0),total:Re.number().min(1),label:Re.string().optional(),variant:Re.enum(["default","success","error"]).default("default")});function ar(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function Bn(e){let{step:t,total:r,label:o,variant:n,percentage:s}=ar(e);return ir("div",{className:"urun-progress-card","data-variant":n,children:[o&&St("div",{className:"urun-progress-label",children:o}),St("div",{className:"urun-progress-bar",children:St("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),ir("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as ht}from"zod";import{jsx as ur,jsxs as Jn}from"react/jsx-runtime";var $n=ht.object({state:ht.enum(["thinking","generating","idle","error"]),message:ht.string().optional()}),jn={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function cr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??jn[t]??t;return{state:t,message:n,isActive:o}}function Kn(e){let{state:t,message:r,isActive:o}=cr(e);return Jn("span",{className:"urun-status-badge","data-state":t,children:[ur("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),ur("span",{className:"urun-status-message",children:r})]})}import{useRef as lr,useEffect as zn}from"react";import{z as vt}from"zod";import{jsx as dr,jsxs as Yn}from"react/jsx-runtime";var Xn=vt.object({text:vt.string(),streaming:vt.boolean().default(!1)});function pr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Gn(e){let{text:t,streaming:r}=pr(e),o=lr(null),n=lr(0);return zn(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),Yn("div",{className:"urun-text-stream",children:[dr("span",{ref:o,className:"urun-text-content"}),r&&dr("span",{className:"urun-text-cursor"})]})}import{z as Be}from"zod";import{jsx as mr,jsxs as eo}from"react/jsx-runtime";var Zn=Be.object({src:Be.string().url(),alt:Be.string().optional(),caption:Be.string().optional()});function fr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Qn(e){let{src:t,alt:r,caption:o}=fr(e);return eo("figure",{className:"urun-image-frame",children:[mr("img",{className:"urun-image",src:t,alt:r}),o&&mr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as ie}from"zod";import{jsx as yt,jsxs as no}from"react/jsx-runtime";var to=ie.object({metrics:ie.array(ie.object({label:ie.string(),value:ie.union([ie.string(),ie.number()]),unit:ie.string().optional()}))});function gr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function ro(e){let{metrics:t}=gr(e);return yt("div",{className:"urun-metrics-panel",children:t.map((r,o)=>no("div",{className:"urun-metric-card",children:[yt("div",{className:"urun-metric-label",children:r.label}),yt("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{createContext as oo,useContext as Sr}from"react";import{jsx as ao}from"react/jsx-runtime";var kt=oo(null);function so({session:e,children:t}){return ao(kt.Provider,{value:e,children:t})}function Z(){return Sr(kt)}function io(){let e=Sr(kt);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}import{forwardRef as uo,useCallback as ke,useEffect as bt,useImperativeHandle as co,useRef as de,useState as hr}from"react";import{jsx as yr,jsxs as po}from"react/jsx-runtime";var vr=1e3;function lo(...e){console.debug("[video]",...e)}var Ct=uo(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:u=!1,objectFit:c="contain",className:f,style:d,videoClassName:k,placeholder:C,poster:g,children:p,onTrack:E,onFirstFrame:S}=t,_=Z(),P=o??_,x=de(null),m=de(null),[I,W]=hr(!1),[L,O]=hr(!1),l=de(!1),T=de(E);T.current=E;let v=de(S);v.current=S;let M=de(null),N=de(null),J=ke(h=>{if(h===M.current||(M.current=h,N.current?.(),N.current=null,l.current=!1,O(!1),!h))return;let b=x.current;if(!b)return;let w=()=>{N.current?.(),N.current=null,l.current=!0,O(!0),v.current?.()};if(typeof b.requestVideoFrameCallback=="function"){let $=b.requestVideoFrameCallback(w);N.current=()=>b.cancelVideoFrameCallback?.($);return}let U=()=>{let $=b.getVideoPlaybackQuality?.();($?$.totalVideoFrames>0:b.readyState>=2&&b.videoWidth>0)&&w()};b.addEventListener("loadeddata",U),b.addEventListener("timeupdate",U),b.addEventListener("playing",U),N.current=()=>{b.removeEventListener("loadeddata",U),b.removeEventListener("timeupdate",U),b.removeEventListener("playing",U)},U()},[]);bt(()=>()=>{N.current?.(),N.current=null},[]);let R=ke(()=>{if(typeof MediaStream>"u")return null;m.current||(m.current=new MediaStream);let h=x.current;return h&&h.srcObject!==m.current&&(h.srcObject=m.current),m.current},[]),A=ke(h=>{let b=x.current;if(!b)return;let w=b.play();!w||typeof w.catch!="function"||w.catch(U=>lo(`play() failed (${h})`,U))},[]),V=ke(h=>{let b=R();if(b){for(let w of b.getVideoTracks())w!==h&&b.removeTrack(w);if(h&&!b.getVideoTracks().includes(h)){b.addTrack(h);let w=x.current;w&&(w.srcObject=b)}h&&A("track-attach"),W(h!==null),J(h),T.current?.(h)}},[R,A,J]),F=ke(h=>{let b=R();if(b){for(let w of b.getAudioTracks())w!==h&&b.removeTrack(w);h&&!b.getAudioTracks().includes(h)&&b.addTrack(h),h&&A("audio-attach")}},[R,A]),B=ke(h=>{x.current=h,h&&(a&&(h.muted=!0,h.defaultMuted=!0,h.setAttribute("muted","")),h.setAttribute("playsinline",""),h.setAttribute("webkit-playsinline",""),R())},[R,a]);co(r,()=>({get element(){return x.current},get live(){return m.current?m.current.getVideoTracks().length>0:!1},get framed(){return l.current}}),[]);let q=i!==void 0;return bt(()=>{if(q){V(i??null);return}if(!P)return;let h=P.stream(n),b=()=>{let y=m.current;return y?y.getVideoTracks()[0]??null:null},w=y=>{if(y!==b()&&(V(y),y)){let K=()=>{b()===y&&V(null)};y.addEventListener("ended",K)}},U=h.track;U&&U.readyState==="live"&&w(U);let $=h.on("track",y=>{y&&y.readyState!=="live"||w(y)}),H=setInterval(()=>{let y=h.track;y&&y.readyState==="live"&&w(y)},vr);return()=>{$(),clearInterval(H)}},[P,n,q,i,V]),bt(()=>{if(q||!P||s===!1)return;let h=P.stream(s),b=()=>{let y=m.current;return y?y.getAudioTracks()[0]??null:null},w=y=>{if(y!==b()&&(F(y),y)){let K=()=>{b()===y&&F(null)};y.addEventListener("ended",K)}},U=h.track;U&&U.readyState==="live"&&w(U);let $=h.on("track",y=>{y&&y.readyState!=="live"||w(y)}),H=setInterval(()=>{let y=h.track;y&&y.readyState==="live"&&w(y)},vr);return()=>{$(),clearInterval(H)}},[P,s,q,F]),po("div",{className:f,style:{position:"relative",width:"100%",height:"100%",...d},"data-urun-video":"","data-urun-video-live":I?"true":"false","data-urun-video-framed":L?"true":"false",children:[yr("video",{ref:B,className:k,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...u?{transform:"scaleX(-1)"}:{}}}),I?null:C,g===void 0?null:yr("div",{"data-urun-video-poster":"","aria-hidden":L||void 0,style:{position:"absolute",inset:0,...L?{opacity:0,pointerEvents:"none"}:null},children:g}),p]})});import{forwardRef as mo}from"react";import{jsx as go}from"react/jsx-runtime";var fo=mo(function(t,r){let{stream:o="image",...n}=t;return go(Ct,{ref:r,stream:o,...n})});import{forwardRef as ho,useCallback as be,useEffect as Pt,useImperativeHandle as vo,useRef as Ce}from"react";import{observePageLifecycle as yo}from"@urun-sh/core";var $e=null;function So(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function je(){if($e)return $e;let e=So();return e?($e=new e,$e):null}function Ke(){let e=je();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{jsx as Co}from"react/jsx-runtime";var ko=1e3,kr=200;function Et(...e){console.debug("[audio]",...e)}var Je=ho(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:f}=t,d=Z(),k=o??d,C=Ce(null),g=Ce(null),p=Ce(null),E=Ce(null),S=Ce(u);S.current=u;let _=Ce(c);_.current=c;let P=be(l=>{p.current!==l&&(p.current=l,_.current?.(l))},[]),x=be(()=>{if(typeof MediaStream>"u")return null;g.current||(g.current=new MediaStream);let l=C.current;return l&&l.srcObject!==g.current&&(l.srcObject=g.current),g.current},[]),m=be(l=>{let T=C.current;if(!T)return;let v=T.play();!v||typeof v.then!="function"||v.then(()=>{T.muted||P(!0)}).catch(M=>{let N=M instanceof Error?M.name:String(M);if(N==="AbortError"){Et(`play() aborted (${l}); retrying in ${kr}ms`),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{E.current=null,m(`${l}:retry`)},kr);return}if(N==="NotAllowedError"){Et(`play() blocked pending a user gesture (${l})`),P(!1);return}Et(`play() failed (${l})`,M)})},[P]),I=be(l=>{let T=x();if(T){for(let v of T.getAudioTracks())v!==l&&T.removeTrack(v);l&&!T.getAudioTracks().includes(l)&&T.addTrack(l),l&&m("track-attach"),S.current?.(l)}},[x,m]),W=be(()=>{let l=C.current;l&&(x(),l.muted=!1,m("gesture"),Ke(),P(!0))},[x,m,P]);vo(r,()=>({unlock:W,get unlocked(){return p.current===!0},get element(){return C.current}}),[W]);let L=be(l=>{C.current=l,l&&(l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),x()),f?.(l)},[x,f]),O=s!==void 0;return Pt(()=>{if(O){I(s??null);return}if(!k)return;let l=k.stream(n),T=()=>{let R=g.current;return R?R.getAudioTracks()[0]??null:null},v=R=>{if(R!==T()&&(I(R),R)){let A=()=>{T()===R&&I(null)};R.addEventListener("ended",A)}},M=l.track;M&&M.readyState==="live"&&v(M);let N=l.on("track",R=>{R&&R.readyState!=="live"||v(R)}),J=setInterval(()=>{let R=l.track;R&&R.readyState==="live"&&v(R)},ko);return()=>{N(),clearInterval(J)}},[k,n,O,s,I]),Pt(()=>yo(()=>{Ke(),p.current===!0&&m("foreground")}),[m]),Pt(()=>()=>{E.current&&clearTimeout(E.current)},[]),Co("audio",{ref:L,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),bo=Je;import{forwardRef as Po,useCallback as Pe,useEffect as br,useImperativeHandle as Eo,useRef as te}from"react";import{observePageLifecycle as To,sessionFailureFromMediaError as xo,sharedCaptureController as wo}from"@urun-sh/core";import{jsx as Ao}from"react/jsx-runtime";var Cr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function ze(...e){console.debug("[voice]",...e)}var Xe=Po(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=Cr,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:f,onError:d,onMicStream:k,onTrack:C,onUnlockChange:g,capture:p}=t,E=Z(),S=o??E,_=te(null),P=te(null),x=te(null),m=te([]),I=te(!1),W=te(f);W.current=f;let L=te(d);L.current=d;let O=te(k);O.current=k;let l=Pe(A=>{I.current!==A&&(I.current=A,W.current?.(A))},[]),T=Pe(()=>{for(let A of m.current)A();m.current=[],x.current?.release(),x.current=null,P.current&&(P.current=null,O.current?.(null))},[]),v=Pe(async()=>{let A=x.current;if(A){let q=await A.update(i);return P.current=A.stream,O.current?.(A.stream),q}let F=await(p??wo()).claim("audio",i);x.current=F,m.current=[F.onTrack((q,h)=>{P.current=h,O.current?.(h),I.current&&S?.stream(n).attach(q).catch(b=>ze("mic re-attach after one-capture re-acquire failed",b))}),F.onLost(q=>{x.current=null,m.current=[],P.current=null,O.current?.(null),l(!1),L.current?.(q)})],P.current=F.stream,O.current?.(F.stream);let B=F.track;if(!B)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return B},[p,i,S,n,l]),M=Pe(async()=>{T(),l(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,T,l]),N=Pe(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");_.current?.unlock();let A;try{A=await v()}catch(B){T();let q=xo(B,S.status);throw L.current?.(q),q}S.connect?.();let V;for(let B=1;B<=u;B++)try{await S.whenLive(a!==void 0?{timeout:a}:void 0),await S.stream(n).attach(A),l(!0);return}catch(q){V=q,ze(`start attempt ${B}/${u} failed`,q),B<u&&await new Promise(h=>setTimeout(h,c))}T(),l(!1);let F=V instanceof Error?V:new Error(String(V??"voice start failed"));throw L.current?.(F),F},[S,n,a,u,c,v,T,l]);Eo(r,()=>({start:N,stop:M,unlock:()=>_.current?.unlock(),get active(){return I.current},get micStream(){return P.current},get audio(){return _.current}}),[N,M]);let J=te(!1),R=Pe(async()=>{if(!S||!I.current||J.current)return;let A=P.current?.getAudioTracks()[0]??null;if(A&&A.readyState==="live"){try{await S.stream(n).attach(A)}catch(V){ze("foreground mic re-assert failed (will retry on next pass)",V)}return}J.current=!0;try{let V=await v();await S.stream(n).attach(V)}catch(V){let F=V instanceof Error?V:new Error(String(V));ze("foreground mic re-acquire failed",F),L.current?.(F)}finally{J.current=!1}},[S,n,v]);return br(()=>{let A=()=>{R()};return S&&typeof S.onRecovery=="function"?S.onRecovery(A):To(A)},[S,R]),br(()=>T,[T]),s?Ao(Je,{ref:_,session:S,stream:n,onTrack:C,onUnlockChange:g}):null}),Ro=Xe;import{forwardRef as _o,useEffect as No,useImperativeHandle as Io,useRef as Pr,useState as Lo}from"react";import{useEffect as Uo,useState as Mo}from"react";var Tt={level:0,speaking:!1};function xt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=Mo(Tt);return Uo(()=>{if(!e){i(Tt);return}let a=je();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,f;try{c=a.createMediaStreamSource(u),f=a.createAnalyser(),f.fftSize=r,c.connect(f)}catch{return}let d=new Uint8Array(f.fftSize),C=setInterval(()=>{f.getByteTimeDomainData(d);let g=0;for(let E=0;E<d.length;E++){let S=(d[E]-128)/128;g+=S*S}let p=Math.sqrt(g/d.length);i(E=>{let S=p>n;return Math.abs(E.level-p)<.005&&E.speaking===S?E:{level:p,speaking:S}})},o);return()=>{clearInterval(C),c.disconnect(),i(Tt)}},[e,r,o,n]),s}import{Fragment as Fo,jsx as Ge,jsxs as qo}from"react/jsx-runtime";var Oo={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Do={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Vo=_o(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:f,onMicStream:d,capture:k}=t,C=Z(),g=o??C,p=Pr(null),[E,S]=Lo(null),_=Pr(d);_.current=d;let{level:P,speaking:x}=xt(a?E:null);return Io(r,()=>({start:()=>{let m=p.current;return m?m.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>p.current?.stop()??Promise.resolve(),get active(){return p.current?.active??!1},get micStream(){return p.current?.micStream??null}}),[]),No(()=>{!i||!g||p.current?.start().catch(()=>{})},[i,g]),qo(Fo,{children:[Ge(Xe,{ref:p,session:g,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...k!==void 0?{capture:k}:{},onActiveChange:c,onError:f,onMicStream:m=>{S(m),_.current?.(m)}}),a?Ge("span",{className:u,style:Oo,"data-urun-mic":"","data-urun-mic-active":E?"true":"false","data-urun-mic-speaking":x?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(P*100)/100,children:Ge("span",{style:Do,children:Ge("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(P*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{sessionFailureFromMediaError as Ho,sharedCaptureController as Wo}from"@urun-sh/core";import{forwardRef as Tr,useCallback as re,useEffect as wt,useImperativeHandle as Bo,useRef as X,useState as Ae}from"react";import{jsx as ae,jsxs as Er}from"react/jsx-runtime";var xr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Rt(...e){console.debug("[camera]",...e)}function $o(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function jo(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var wr=Tr(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:f="auto",connectTimeoutMs:d,visible:k=!1,className:C,videoClassName:g,onActiveChange:p,onError:E,onStream:S,onTrack:_,children:P,capture:x,flipControl:m="auto",flipControlClassName:I,onDevices:W}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let L=i?"user":a?"environment":u??"environment",O=Z(),l=o??O,T=X(null),v=X(null),M=X(null),N=X([]),J=X(null),R=X(!1),A=X(L),[V,F]=Ae(L),[B,q]=Ae(!1),[h,b]=Ae(null),[w,U]=Ae(!1),[$]=Ae($o),H=X(p);H.current=p;let y=X(E);y.current=E;let K=X(S);K.current=S;let Q=X(_);Q.current=_;let Ie=X(W);Ie.current=W;let ne=re(D=>{R.current!==D&&(R.current=D,q(D),H.current?.(D))},[]);wt(()=>{if(!B){b(null);return}let D=!1,j=()=>{jo().then(G=>{D||(b(G),G&&Ie.current?.(G))})};j();let z=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof z?.addEventListener=="function"?(z.addEventListener("devicechange",j),()=>{D=!0,z.removeEventListener?.("devicechange",j)}):()=>{D=!0}},[B]);let Le=re(D=>{let j=T.current;j&&(j.muted=!0,j.defaultMuted=!0,j.setAttribute("muted",""),j.setAttribute("playsinline",""),j.setAttribute("webkit-playsinline",""),j.srcObject=D,D&&j.play()?.catch?.(z=>Rt("preview play() failed",z)))},[]),ee=re(()=>{J.current?.(),J.current=null;for(let D of N.current)D();N.current=[],M.current?.release(),M.current=null,v.current&&(v.current=null,K.current?.(null),Q.current?.(null)),Le(null)},[Le]),rt=re((D,j)=>{J.current?.(),v.current=j,Le(j),K.current?.(j);let z=()=>{v.current===j&&(Rt("camera track ended (device removed or permission revoked)"),ee(),ne(!1))};D.addEventListener("ended",z),J.current=()=>D.removeEventListener("ended",z)},[Le,ee,ne]),ge=re(async D=>{if(!l)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let j={...xr,...s,facingMode:D},z;try{let G=M.current;if(G)z=await G.update(j);else{let Ee=await(x??Wo()).claim("video",j);if(M.current=Ee,N.current=[Ee.onTrack((Te,jr)=>{rt(Te,jr),R.current&&l.stream(n).attachVideo(Te).then(()=>Q.current?.(Te)).catch(Kr=>Rt("camera re-publish after one-capture re-acquire failed",Kr))}),Ee.onLost(Te=>{M.current=null,N.current=[],ee(),ne(!1),y.current?.(Te)})],!Ee.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});z=Ee.track}}catch(G){let Se=Ho(G,l.status);throw y.current?.(Se),Se}A.current=D,F(D),rt(z,M.current?.stream??new MediaStream([z]));try{l.connect?.(),await l.whenLive(d!==void 0?{timeout:d}:void 0),await l.stream(n).attachVideo(z)}catch(G){ee(),ne(!1);let Se=G instanceof Error?G:new Error(String(G));throw y.current?.(Se),Se}Q.current?.(z),ne(!0)},[l,n,s,d,x,rt,ee,ne]),Vt=re(D=>ge(D?.facingMode??A.current),[ge]),Oe=re(async D=>{R.current&&A.current===D||await ge(D)},[ge]),nt=re(()=>ge(A.current==="environment"?"user":"environment"),[ge]),Ft=re(async()=>{ee(),ne(!1),await l?.stream(n).detachVideo().catch(()=>{})},[l,n,ee,ne]);Bo(r,()=>({start:Vt,stop:Ft,flip:nt,setFacingMode:Oe,get active(){return R.current},get facingMode(){return A.current},get stream(){return v.current},get element(){return T.current}}),[Vt,Ft,nt,Oe]);let qt=X(Oe);if(qt.current=Oe,wt(()=>{!c||!l||qt.current(L).catch(()=>{})},[c,l,L]),wt(()=>ee,[ee]),!k)return null;let Wr=f==="auto"?V==="user":f,Br=B&&(m===!0||m==="auto"&&$&&(h?.length??0)>1),$r=()=>{w||(U(!0),nt().catch(()=>{}).finally(()=>U(!1)))};return Er("div",{className:C,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":V,children:[ae("video",{ref:T,className:g,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Wr?{transform:"scaleX(-1)"}:{}}}),Br?ae("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:$r,disabled:w,className:I,style:I?{opacity:w?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:w?.6:1},children:Er("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[ae("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),ae("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),ae("path",{d:"M14.5 10.5v1.6h-1.6"}),ae("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),ae("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,P]})}),Ko=Tr(function({preview:t=!0,...r},o){return ae(wr,{ref:o,...r,visible:t,autoStart:!1})});import{useEffect as Jo,useState as zo}from"react";function Xo(e,t){let[r,o]=zo(null);return Jo(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}import{useCallback as ts}from"react";import{useEffect as Qo,useMemo as es}from"react";import{createStore as Go}from"zustand/vanilla";import{useStore as Yo}from"zustand";var Zo=()=>{};function At(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=Go(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):Zo,u=(c=>Yo(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function Ue(e,t){let r=es(()=>At(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return Qo(()=>r.bind(),[r]),r}function rs(e,t,r){let n=Ue(e,t)(r??(a=>a)),s=ts(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}import{useEffect as ns,useState as os}from"react";var pe=200;function ue(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Me(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Ut(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Mt(e,t,r={}){let o=r.cap??200,[n,s]=os([]);return ns(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>ue(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}import{jsx as Ye,jsxs as _e}from"react/jsx-runtime";function ss({session:e,name:t,cap:r,className:o}){let n=Mt(e,t,{cap:r});return _e("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[_e("div",{className:"urun-stream-tail-meta",children:[Ye("code",{children:t}),_e("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),Ye("div",{className:"urun-stream-tail-log",children:n.length===0?_e("span",{className:"urun-stream-tail-empty",children:["Waiting for ",Ye("code",{children:t})," messages\u2026"]}):n.map((s,i)=>_e("div",{className:"urun-stream-tail-line",children:[Ye("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Me(s.payload)]},`${s.at}-${i}`))})]})}import{useCallback as is,useState as Rr}from"react";import{jsx as me,jsxs as Ze}from"react/jsx-runtime";function Qe({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=Rr(""),[i,a]=Rr(null),u=is(()=>{let c=Ut(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return Ze("div",{className:"urun-doc-patch",children:[me("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),Ze("div",{className:"urun-doc-patch-actions",children:[me("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?me("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function as({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Ue(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return Ze("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[Ze("div",{className:"urun-doc-panel-meta",children:[me("code",{children:t}),me("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),me("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?me(Qe,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}import{useEffect as us,useState as cs}from"react";import{jsx as Ne,jsxs as Ur}from"react/jsx-runtime";function Ar(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function ls({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=cs([]);return us(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>ue(u,{at:Date.now(),direction:"in",text:Ar(Me(a))},r))}):void 0),[e,t,r]),Ur("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[Ne(Qe,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>ue(u,{at:Date.now(),direction:"out",text:Ar(a)},r))}}),Ne("div",{className:"urun-control-sender-log",children:n.length===0?Ne("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>Ur("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[Ne("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",Ne("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}import{useEffect as ds,useState as ps}from"react";import{jsx as et,jsxs as fs}from"react/jsx-runtime";function ms({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=ps([]),a=t.join(","),u=r.join(",");return ds(()=>{if(i([]),!e)return;let c=(d,k)=>i(C=>ue(C,{at:Date.now(),kind:d,text:k},o)),f=[];f.push(e.onPhase(d=>c("phase",`phase \u2192 ${d.name}`)));for(let d of t){let k=e.stream(d);f.push(k.on("track",C=>c("track",`${d}: ${C?"track arrived":"track ended"}`)))}for(let d of r){let k=e.doc(d);f.push(k.on("change",()=>c("doc",`${d} changed`)))}return()=>f.forEach(d=>d())},[e,a,u,o]),et("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?et("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((c,f)=>fs("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[et("span",{className:"urun-event-spine-kind",children:c.kind})," ",et("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${f}`))})}import{describeSessionPhase as As,isWakingPhase as Us}from"@urun-sh/core";import{useEffect as gs,useState as Ss}from"react";function Y(e){let[t,r]=Ss(e?.phase??null);return gs(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as bs}from"@urun-sh/core";import{useEffect as hs,useRef as vs,useState as ys}from"react";import{isWakingPhase as ks}from"@urun-sh/core";function _t(e){let t=Y(e),r=ks(t?.name),o=vs(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=ys(s);return hs(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}import{Fragment as Cs,jsx as Mr,jsxs as _r}from"react/jsx-runtime";function Nt({session:e,render:t,className:r}){let o=_t(e);return!o.waking||!o.phase?null:Mr("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):_r(Cs,{children:[Mr("span",{className:"urun-session-waking-label",children:bs(o.phase)})," ",_r("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as Ts,useState as xs}from"react";import{useEffect as Nr,useRef as Ps,useState as Ir}from"react";var Es={event:null,elapsedMs:0};function It(e,t){let[r,o]=Ir(null),n=Ps(0);Nr(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=Ir(0);return Nr(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:Es}import{jsx as Lr,jsxs as Or}from"react/jsx-runtime";var ws={activating:"starting stream\u2026","still-activating":"model warming up \u2014 this can take a minute","cold-boot":"cold boot \u2014 compiling/loading the model, hang tight",degraded:"taking longer than usual \u2014 still trying"};function Rs(e){let[t,r]=xs(!1);return Ts(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function Lt({session:e,stream:t,videoElement:r,render:o,className:n}){let s=It(e,t),i=Rs(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return Lr("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):Or("div",{className:"urun-activation-overlay-card",children:[Lr("span",{className:"urun-activation-overlay-copy",children:a.hint??ws[u]})," ",Or("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as fe,jsxs as Ot}from"react/jsx-runtime";var Ms={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function _s({session:e,className:t}){let r=Y(e),o=r?.name??"idle",n=r?.name==="queued"&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:(r?.name==="error"||r?.name==="expired")&&r.error?r.error.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return Ot("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[fe("span",{className:"urun-session-status-dot","data-phase":o}),fe("span",{className:"urun-session-status-label",children:Ms[o]}),n?fe("span",{className:"urun-session-status-detail",children:n}):null]})}function Ns({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=Y(e);if(s?.name==="live")return Ot("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,fe(Lt,{session:e})]});let i=r?r(s):fe("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&Us(s.name)?fe(Nt,{session:e}):s&&s.name!=="idle"?As(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return Ot("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?fe("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as Is,useState as Ls}from"react";import{jsx as Vs}from"react/jsx-runtime";function Dr(e){return Y(e)?.endsAt??null}function Os(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function Ds({session:e,urgentMs:t=6e4,className:r}){let n=Dr(e)?.getTime()??null,[s,i]=Ls(()=>n===null?null:Math.max(0,n-Date.now()));if(Is(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=Os(s);return Vs("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}import{jsx as Vr,jsxs as Hs}from"react/jsx-runtime";var Fs=new Set(["expired","ended","error"]);function qs({session:e,onNewSession:t,children:r,className:o}){let n=Y(e);if(!n||!Fs.has(n.name))return null;let s=r?r(n):Vr("span",{className:"urun-session-ended-copy",children:n.name==="expired"?"Session ended \u2014 start a new session":n.name==="error"?`Session failed${n.error?.reason?` \u2014 ${n.error.reason}`:""}.`:"Session ended."});return Hs("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?Vr("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}import{useEffect as Fr,useMemo as Ws,useState as qr}from"react";import{jsx as tt,jsxs as js}from"react/jsx-runtime";function Dt(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function Hr(e){let t=Ws(()=>e?e.doc("control"):null,[e]),[r,o]=qr(()=>t?Dt(t.get("idle")):null);return Fr(()=>{if(!t){o(null);return}return o(Dt(t.get("idle"))),t.on("change",()=>o(Dt(t.get("idle"))))},[t]),r}function Bs(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function $s({session:e,onStillHere:t,className:r}){let o=Hr(e),n=o?.deadlineEpochS??null,[s,i]=qr(null);if(Fr(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return tt("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:js("div",{className:"urun-idle-warning-card",children:[tt("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),tt("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Bs(s)} due to inactivity.`:"This session will end soon due to inactivity."}),tt("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useContext as Ks,useEffect as Js,useState as zs}from"react";import{prewake as Xs}from"@urun-sh/core";function Gs(e){let t=Ks(he),[r,o]=zs(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,f=t?.getAccessToken,d=t?.authProvider;return Js(()=>{if(!a||!u||!n||!s)return;let k=!1,C=()=>{Xs({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:f,authProvider:d}).then(p=>{k||o(p)}).catch(()=>{})};C();let g=setInterval(C,Math.max(1,i)*1e3);return()=>{k=!0,clearInterval(g)}},[n,s,i,a,u,c,f,d]),r}import{describeSessionPhase as Gc,isWakingPhase as Yc}from"@urun-sh/core";export{Je as Audio,wr as Camera,qn as ComponentRenderer,xr as DEFAULT_CAMERA_CONSTRAINTS,pe as DEFAULT_LOG_CAP,Cr as DEFAULT_VOICE_CONSTRAINTS,Qe as DocPatchForm,fo as Image,Qn as ImageFrame,Zn as ImageFrameSchema,ro as MetricsPanel,to as MetricsPanelSchema,Vo as Mic,rn as OPERATOR_CHORD_LABEL,tn as OPERATOR_TOKEN_STORAGE_KEY,Bn as ProgressCard,Wn as ProgressCardSchema,so as Session,Kn as StatusBadge,$n as StatusBadgeSchema,Gn as TextStream,Xn as TextStreamSchema,Lt as UrunActivationOverlay,bo as UrunAudio,Jr as UrunAuthProvider,Ko as UrunCamera,ls as UrunControlSender,as as UrunDocPanel,xe as UrunErrorBoundary,ms as UrunEventSpine,$s as UrunIdleWarning,zr as UrunJwtProvider,mn as UrunProvider,Ds as UrunSessionClock,qs as UrunSessionEnded,Ns as UrunSessionGate,_s as UrunSessionStatus,Nt as UrunSessionWaking,ss as UrunStreamTail,Ro as UrunVoice,Ct as Video,Xe as Voice,De as authMode,At as createDocStore,Gc as describeSessionPhase,Me as formatPayload,je as getUrunAudioContext,Yc as isWakingPhase,Ut as parseJsonObject,ue as pushCapped,jt as readOperatorToken,Fn as registerComponent,Ke as resumeUrunAudioContext,oe as urunPublicEnv,It as useActivation,bn as useApp,Nn as useChat,An as useCompletion,it as useConfirmOnLeave,Ue as useDocStore,fr as useImageFrame,Vn as useInputPresence,gr as useMetricsPanel,st as useOperatorOverride,ar as useProgressCard,Tn as useRequest,io as useSession,rs as useSessionDoc,Dr as useSessionEndsAt,Hr as useSessionIdle,Y as useSessionPhase,Xo as useSessionTrack,_t as useSessionWake,cr as useStatusBadge,Mt as useStreamMessages,pr as useTextStream,xt as useUrunAudioLevel,ot as useUrunAuth,Gs as useUrunPrewake,Zr as usesWorkOSAuth};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urun-sh/react",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.37",
|
|
4
4
|
"description": "React bindings for the urun TypeScript SDK",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"dev": "tsup --watch"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
|
-
"@urun-sh/core": "^0.2.
|
|
56
|
+
"@urun-sh/core": "^0.2.37",
|
|
57
57
|
"@workos-inc/authkit-nextjs": "^3.0.0",
|
|
58
58
|
"@workos-inc/authkit-react": "^0.15.0 || ^0.16.0",
|
|
59
59
|
"next": "^15.0.0 || ^16.0.0",
|