@urun-sh/react 0.2.51 → 0.2.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ - **Single-element muxed playout is now the canonical way to consume an `"av"`
6
+ parent.** `<Video stream="av" muted={false} />` puts BOTH tracks into ONE
7
+ `MediaStream` on ONE element, so the browser's native A/V sync machinery owns
8
+ the alignment — the same machinery an ordinary video player relies on.
9
+ Consuming the same pair as two elements (`<Video stream="video">` +
10
+ `<Audio stream="audio">`) gives the browser two independently-buffered
11
+ playout paths with two element lifecycles and nothing aligning them; audio's
12
+ jitter buffer accumulates standing delay on every delivery gap while video
13
+ renders on arrival, and the drift is bounded only by RTCP sender reports an
14
+ SFU may re-mint per track (liveavatar measured 2.2–2.7s of audio lagging
15
+ video that way).
16
+
17
+ The track plumbing already existed. What an UNMUTED muxed element needs —
18
+ it IS the audio sink, so it is gesture-gated exactly like an `<Audio>` — is
19
+ new: `VideoHandle.unlock()` / `VideoHandle.unlocked` and
20
+ `VideoProps.onUnlockChange`, mirroring `<Audio>`'s contract. Previously an
21
+ unmuted `<Video>` swallowed a blocked `play()` (`NotAllowedError`) into a
22
+ `console.debug` and went silently mute with no affordance for the app to
23
+ render. Also clears the stale `muted` ATTRIBUTE on an unmuted element (React
24
+ sets the property but never the attribute; WebKit reads the attribute), and
25
+ drops the unlocked claim when an element is re-rendered muted.
26
+
27
+ **No breaking changes**: two-element consumers are unchanged, and
28
+ `audioStream={false}` remains the opt-out.
29
+
30
+ - `UrunProvider` gains an optional `audioPlayout` prop, forwarded to
31
+ `@urun-sh/core`'s `AppOptions.audioPlayout` — the inbound audio
32
+ jitter-buffer cap (default 300ms) that bounds how far audio playout can
33
+ drift behind video. Like `eventsUrl` and `releaseOnLeave` it is tuning, not
34
+ identity, so it is deliberately NOT part of the shared-session key: changing
35
+ it never redials a live session (first value wins per session).
36
+
3
37
  ## 0.2.29
4
38
 
5
39
  - **`useApp()` render-safety hardened to full reference stability** (owner contract
package/README.md CHANGED
@@ -99,6 +99,36 @@ autoplay unlock, and front/back switching — hand-rolled `getUserMedia` / `.tra
99
99
  - VOD/recordings playback (seek/scrub): `VideoPlayer` from `@urun-sh/react/video` — video.js is an optional peer, deliberately not in the root export.
100
100
  - The `UrunAudio` / `UrunVoice` / `UrunCamera` (root) and `UrunVideo` (`/video` subpath) aliases are deprecated and removed next minor — write the bare names.
101
101
 
102
+ #### Muxed A/V: consume an `"av"` parent through ONE element
103
+
104
+ A runtime that egresses `ctx.stream("av", video_codec="h264", audio_codec="opus")` puts two
105
+ RTP tracks on the wire. Name the **parent** and `<Video>` puts both into ONE `MediaStream` on
106
+ ONE element, so the browser's native A/V sync machinery owns the alignment:
107
+
108
+ ```tsx
109
+ const video = useRef<VideoHandle>(null)
110
+
111
+ <button onClick={() => { video.current?.unlock(); void start() }}>Start</button>
112
+ <Video ref={video} stream="av" muted={false} onUnlockChange={setSoundReady} />
113
+ ```
114
+
115
+ This is the canonical single-element muxed playout path. Consuming the same pair as two
116
+ elements (`<Video stream="video">` + `<Audio stream="audio">`) gives the browser two
117
+ independently-buffered playout paths with nothing aligning them: audio's jitter buffer
118
+ accumulates standing delay on every delivery gap while video renders on arrival, and the
119
+ drift is bounded only by RTCP sender reports that an SFU may re-mint per track. That is
120
+ still supported — pass `audioStream={false}` on the video element so it never claims the
121
+ voice leg — but one element is the shape to reach for.
122
+
123
+ Since an unmuted element *is* the audio sink, it needs the same user gesture an `<Audio>`
124
+ does: call `unlock()` synchronously from the app's start-button handler and render a
125
+ tap-to-enable affordance from `onUnlockChange(false)`.
126
+
127
+ The SDK also caps every inbound audio receiver's jitter buffer at 300 ms
128
+ (`RTCRtpReceiver.jitterBufferTarget`) so standing audio delay cannot accumulate past that
129
+ bound. Retune it per provider with
130
+ `<UrunProvider audioPlayout={{ jitterBufferTargetMs: 500 }}>`.
131
+
102
132
  ### Hooks and building blocks
103
133
 
104
134
  - Session doc/data: `useDocStore`, `useSessionDoc`, `useStreamMessages`, `useSessionTrack`.
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import * as react from 'react';
3
3
  import { ReactNode, RefObject, Component, ErrorInfo, CSSProperties, ComponentType } from 'react';
4
- import { SessionInterface, SessionDocument, SessionStream, SessionPhase, SessionStatus, SessionDiagnostic, CameraWarpOptions, CameraWarp, CaptureController, ReferenceImage, ActivationEvent, PrewakeResult, RuntimeAvailability } from '@urun-sh/core';
4
+ import { AudioPlayoutOptions, SessionInterface, SessionDocument, SessionStream, SessionPhase, SessionStatus, SessionDiagnostic, CameraWarpOptions, CameraWarp, CaptureController, ReferenceImage, ActivationEvent, PrewakeResult, RuntimeAvailability } from '@urun-sh/core';
5
5
  export { ActivationEvent, ActivationState, App as AppInterface, AppOptions, PrewakeResult, PrewakeStatus, RuntimeAvailability, SessionDocument, Session as SessionInterface, SessionPhase, SessionPhaseName, SessionStream, describeSessionPhase, isWakingPhase } from '@urun-sh/core';
6
6
  import { ZodSchema, z } from 'zod';
7
7
  import { StoreApi } from 'zustand/vanilla';
@@ -28,6 +28,8 @@ interface UrunProviderProps {
28
28
 
29
29
  releaseOnLeave?: boolean;
30
30
 
31
+ audioPlayout?: AudioPlayoutOptions;
32
+
31
33
  confirmOnLeave?: boolean;
32
34
 
33
35
  sessionId?: string;
@@ -44,7 +46,7 @@ interface UrunProviderProps {
44
46
  fallback?: ReactNode | ((error: Error) => ReactNode);
45
47
  children: ReactNode;
46
48
  }
47
- declare function UrunProvider({ baseUrl, orgId, app, appId, jwt, authProvider, eventsUrl, sessionKey, tokenEndpoint, releaseOnLeave, confirmOnLeave, fallback, errorFallback, children, }: UrunProviderProps): react_jsx_runtime.JSX.Element;
49
+ declare function UrunProvider({ baseUrl, orgId, app, appId, jwt, authProvider, eventsUrl, sessionKey, tokenEndpoint, releaseOnLeave, audioPlayout, confirmOnLeave, fallback, errorFallback, children, }: UrunProviderProps): react_jsx_runtime.JSX.Element;
48
50
 
49
51
  interface UrunErrorBoundaryProps {
50
52
  fallback?: ReactNode | ((error: Error) => ReactNode);
@@ -282,6 +284,10 @@ interface VideoHandle {
282
284
  readonly live: boolean;
283
285
 
284
286
  readonly framed: boolean;
287
+
288
+ unlock(): void;
289
+
290
+ readonly unlocked: boolean;
285
291
  }
286
292
 
287
293
  interface FrameMarker {
@@ -326,6 +332,8 @@ interface VideoProps {
326
332
  onFrameMarkerReached?: () => void;
327
333
 
328
334
  onFrameMarkerUnsupported?: () => void;
335
+
336
+ onUnlockChange?: (unlocked: boolean) => void;
329
337
  }
330
338
 
331
339
  declare const Video: react.ForwardRefExoticComponent<VideoProps & react.RefAttributes<VideoHandle>>;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import * as react from 'react';
3
3
  import { ReactNode, RefObject, Component, ErrorInfo, CSSProperties, ComponentType } from 'react';
4
- import { SessionInterface, SessionDocument, SessionStream, SessionPhase, SessionStatus, SessionDiagnostic, CameraWarpOptions, CameraWarp, CaptureController, ReferenceImage, ActivationEvent, PrewakeResult, RuntimeAvailability } from '@urun-sh/core';
4
+ import { AudioPlayoutOptions, SessionInterface, SessionDocument, SessionStream, SessionPhase, SessionStatus, SessionDiagnostic, CameraWarpOptions, CameraWarp, CaptureController, ReferenceImage, ActivationEvent, PrewakeResult, RuntimeAvailability } from '@urun-sh/core';
5
5
  export { ActivationEvent, ActivationState, App as AppInterface, AppOptions, PrewakeResult, PrewakeStatus, RuntimeAvailability, SessionDocument, Session as SessionInterface, SessionPhase, SessionPhaseName, SessionStream, describeSessionPhase, isWakingPhase } from '@urun-sh/core';
6
6
  import { ZodSchema, z } from 'zod';
7
7
  import { StoreApi } from 'zustand/vanilla';
@@ -28,6 +28,8 @@ interface UrunProviderProps {
28
28
 
29
29
  releaseOnLeave?: boolean;
30
30
 
31
+ audioPlayout?: AudioPlayoutOptions;
32
+
31
33
  confirmOnLeave?: boolean;
32
34
 
33
35
  sessionId?: string;
@@ -44,7 +46,7 @@ interface UrunProviderProps {
44
46
  fallback?: ReactNode | ((error: Error) => ReactNode);
45
47
  children: ReactNode;
46
48
  }
47
- declare function UrunProvider({ baseUrl, orgId, app, appId, jwt, authProvider, eventsUrl, sessionKey, tokenEndpoint, releaseOnLeave, confirmOnLeave, fallback, errorFallback, children, }: UrunProviderProps): react_jsx_runtime.JSX.Element;
49
+ declare function UrunProvider({ baseUrl, orgId, app, appId, jwt, authProvider, eventsUrl, sessionKey, tokenEndpoint, releaseOnLeave, audioPlayout, confirmOnLeave, fallback, errorFallback, children, }: UrunProviderProps): react_jsx_runtime.JSX.Element;
48
50
 
49
51
  interface UrunErrorBoundaryProps {
50
52
  fallback?: ReactNode | ((error: Error) => ReactNode);
@@ -282,6 +284,10 @@ interface VideoHandle {
282
284
  readonly live: boolean;
283
285
 
284
286
  readonly framed: boolean;
287
+
288
+ unlock(): void;
289
+
290
+ readonly unlocked: boolean;
285
291
  }
286
292
 
287
293
  interface FrameMarker {
@@ -326,6 +332,8 @@ interface VideoProps {
326
332
  onFrameMarkerReached?: () => void;
327
333
 
328
334
  onFrameMarkerUnsupported?: () => void;
335
+
336
+ onUnlockChange?: (unlocked: boolean) => void;
329
337
  }
330
338
 
331
339
  declare const Video: react.ForwardRefExoticComponent<VideoProps & react.RefAttributes<VideoHandle>>;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client"
2
- "use strict";var or=Object.defineProperty;var to=Object.getOwnPropertyDescriptor;var ro=Object.getOwnPropertyNames;var no=Object.prototype.hasOwnProperty;var oo=(e,t)=>{for(var r in t)or(e,r,{get:t[r],enumerable:!0})},so=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ro(t))!no.call(e,n)&&n!==r&&or(e,n,{get:()=>t[n],enumerable:!(o=to(t,n))||o.enumerable});return e};var io=e=>so(or({},"__esModule",{value:!0}),e);var Do={};oo(Do,{Audio:()=>Et,Camera:()=>Rr,ComponentRenderer:()=>ln,DEFAULT_CAMERA_CONSTRAINTS:()=>br,DEFAULT_LOG_CAP:()=>Ie,DEFAULT_VOICE_CONSTRAINTS:()=>vr,DocPatchForm:()=>wt,Image:()=>Rn,ImageFrame:()=>vn,ImageFrameSchema:()=>Sn,MetricsPanel:()=>kn,MetricsPanelSchema:()=>yn,Mic:()=>An,OPERATOR_CHORD_LABEL:()=>Or,OPERATOR_TOKEN_STORAGE_KEY:()=>Ir,ProgressCard:()=>pn,ProgressCardSchema:()=>dn,ReprojectedVideo:()=>sn,Session:()=>Yr,StatusBadge:()=>fn,StatusBadgeSchema:()=>mn,TextStream:()=>hn,TextStreamSchema:()=>gn,UrunActivationOverlay:()=>Qt,UrunAudio:()=>Tn,UrunAuthProvider:()=>mt,UrunCamera:()=>Mn,UrunControlSender:()=>Hn,UrunDocPanel:()=>Fn,UrunErrorBoundary:()=>Xe,UrunEventSpine:()=>Wn,UrunIdleWarning:()=>Gn,UrunJwtProvider:()=>Mr,UrunProvider:()=>Hr,UrunSessionClock:()=>Xn,UrunSessionEnded:()=>Jn,UrunSessionGate:()=>$n,UrunSessionStatus:()=>Kn,UrunSessionWaking:()=>Gt,UrunStreamTail:()=>Vn,UrunVoice:()=>xn,Video:()=>qe,Voice:()=>Pt,authMode:()=>pt,createDocStore:()=>Ht,describeSessionPhase:()=>rr.describeSessionPhase,formatPayload:()=>ot,getUrunAudioContext:()=>Rt,isWakingPhase:()=>rr.isWakingPhase,parseJsonObject:()=>Bt,pushCapped:()=>Me,readOperatorToken:()=>sr,registerComponent:()=>un,resumeUrunAudioContext:()=>Ct,urunPublicEnv:()=>ve,useActivation:()=>Yt,useApp:()=>Br,useChat:()=>Jr,useCompletion:()=>$r,useConfirmOnLeave:()=>Nt,useDocStore:()=>nt,useImageFrame:()=>gr,useInputPresence:()=>Gr,useMetricsPanel:()=>hr,useOperatorOverride:()=>_t,useProgressCard:()=>pr,useReferenceImage:()=>_n,useRequest:()=>jr,useSession:()=>Zr,useSessionDoc:()=>Dn,useSessionEndsAt:()=>Cr,useSessionIdle:()=>Pr,useSessionPhase:()=>me,useSessionTrack:()=>Nn,useSessionWake:()=>Jt,useStatusBadge:()=>mr,useStreamMessages:()=>Kt,useTextStream:()=>fr,useUrunAudioLevel:()=>Ft,useUrunAuth:()=>At,useUrunPrewake:()=>Zn,usesWorkOSAuth:()=>Ur});module.exports=io(Do);var ae=require("react");var wr=require("react"),dt=require("react/jsx-runtime"),Xe=class extends wr.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,dt.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,dt.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,dt.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var xr=require("react"),ze=(0,xr.createContext)(null);function we(e){return e&&e.trim()?e.trim():void 0}function ve(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return we(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return we(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return we(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return we(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return we(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return we(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return we(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return we(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return we(typeof process<"u"?process.env?.[e]:void 0)}}function pt(){let e=ve("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||ve("VERCEL_ENV")==="production"?"workos":ve("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Ur(){return pt()==="workos"}var Je=require("react"),_r=require("react/jsx-runtime"),Ar=(0,Je.createContext)(null);function mt({getAccessToken:e,children:t}){let r=(0,Je.useMemo)(()=>({getAccessToken:e}),[e]);return(0,_r.jsx)(Ar.Provider,{value:r,children:t})}var Mr=mt;function At(){return(0,Je.useContext)(Ar)}var Mt=require("react"),Ir="urun.operator_token",Lr=null,Nr="op",Or="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function Dr(){return typeof window<"u"}function sr(){return Lr}function ao(){if(!Dr())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(Nr);if(!r)return null;Lr=r,t.delete(Nr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function uo(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function _t(e){let t=(0,Mt.useRef)(e);t.current=e,(0,Mt.useEffect)(()=>{if(!Dr())return;ao();let r=o=>{if(!uo(o))return;let n=sr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var Vr=require("react");function Nt(e=!0){(0,Vr.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 xe=require("react/jsx-runtime"),co="/api/urun-token",lo=1e4;function po(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 Fr(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 qr(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function mo(e,t){return typeof e=="function"?e(t):e!==void 0?e:(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:"Sign-in failed"}),(0,xe.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Hr({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,confirmOnLeave:g=!1,fallback:l,errorFallback:v,children:C}){let h=n===void 0&&t===void 0;if(!h&&(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(!h&&(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(h&&(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">.`);Nt(g);let[m,f]=(0,ae.useState)(),[P,E]=(0,ae.useState)(null),U=(0,ae.useRef)(void 0),S=(0,ae.useRef)(null),[k,x]=(0,ae.useState)(null);_t(oe=>x({jwt:oe}));let T=At(),D=ve("NEXT_PUBLIC_SESSION_TOKEN")??ve("NEXT_PUBLIC_URUN_JWT"),d=pt(),b=k!==null,R=d==="workos"&&!n&&!b&&!h,_=n??(d==="jwt"?D:void 0)??m?.token,V=b?k.jwt:_,z=s??ve("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),L=R&&!V&&!T?.getAccessToken,N=t??m?.orgId,F=e??m?.gatewayUrl,$=h&&m===void 0,K=h&&m!==void 0&&!F?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=L?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,ee=P??K??B,ie=qr("NEXT_PUBLIC_URUN_TOKEN_URL",ve("NEXT_PUBLIC_URUN_TOKEN_URL"))??u??co,te=qr("NEXT_PUBLIC_URUN_EVENTS_URL",ve("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,W=(0,ae.useCallback)(async oe=>{if(!oe?.forceRefresh){let I=U.current;if(!I)return I;let w=po(I);if(w===null||w-Date.now()>lo)return I}return(await(S.current??(S.current=(async()=>{try{let I=await Fr(ie);return U.current=I.token,f(I),I}finally{S.current=null}})()))).token},[ie]),Y=(0,ae.useCallback)(async()=>V,[V]),ge=typeof V=="string"&&V.trim().length>0,Ve=R?T?.getAccessToken:h&&!b?W:ge?Y:void 0,ce=(0,ae.useMemo)(()=>({appId:p,baseUrl:F??"",orgId:N??"",jwt:V,getAccessToken:R?T?.getAccessToken:h&&!b?W:void 0,authProvider:z,eventsUrl:te,sessionKey:a,releaseOnLeave:c,priority:b?"preempt":void 0}),[p,T,F,z,V,te,N,a,c,R,b,h,W]);return(0,ae.useEffect)(()=>{if(!h)return;let oe=new AbortController;return E(null),(async()=>{try{let y=await Fr(ie,oe.signal);U.current=y.token,f(y)}catch(y){if(oe.signal.aborted)return;E(y instanceof Error?y:new Error(String(y)))}})(),()=>oe.abort()},[h,ie]),(0,xe.jsx)(Xe,{fallback:l,children:ee?mo(v,ee):$?(0,xe.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,xe.jsx)(ze.Provider,{value:ce,children:Ve?(0,xe.jsx)(mt,{getAccessToken:Ve,children:C}):C})})}var le=require("react"),Wr=require("@urun-sh/core");function fo(e,t){return`${e}:${JSON.stringify(t??{})}`}function go(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 Fe=new Map;var ir=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()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}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()}},ar=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()}},ur=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 ir(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new ar(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 Br(){let e=(0,le.useContext)(ze);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,le.useReducer)(i=>i+1,0),r=(0,le.useRef)(new Map),o=(0,le.useRef)(new Map),n=(0,le.useRef)(null),s=(0,le.useMemo)(()=>(0,Wr.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,le.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=Fe.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 g=Fe.get(u);g===c&&(g.handle.removeNotifier(t),g.refCount=Math.max(0,g.refCount-1),a.set(u,g),g.refCount===0&&(g.disposeTimer=setTimeout(()=>{let l=Fe.get(u);!l||l.refCount!==0||(Fe.delete(u),l.handle.disconnect())},0)))}n.current=a}},[]),(0,le.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 g=l=>{let v=fo(u,l),C=r.current.get(v);if(C&&!C.disposed)return C;let h=go(e,u,l),p=Fe.get(h);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),Fe.delete(h),o.current.get(h)===p&&o.current.delete(h),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new ur(s[u](l),t,e.eventsUrl),refCount:0,disposeTimer:null},Fe.set(h,p)),o.current.get(h)!==p&&(o.current.set(h,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(v,p.handle),p.handle};return i.set(u,g),g}})},[e,s])}var ne=require("react");function Ge(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 ho(e){return e instanceof Error?e:new Error(String(e))}function jr(e,t){let r=(0,ne.useMemo)(()=>Ge(e),[e]),[o,n]=(0,ne.useState)(void 0),[s,i]=(0,ne.useState)(null),[a,u]=(0,ne.useState)(!1),c=(0,ne.useRef)(t);c.current=t;let g=(0,ne.useRef)(0),l=(0,ne.useRef)(null),v=(0,ne.useRef)(!0);(0,ne.useEffect)(()=>(v.current=!0,()=>{v.current=!1,l.current?.abort()}),[]);let C=(0,ne.useCallback)(async m=>{l.current?.abort();let f=new AbortController;l.current=f;let P=++g.current,E=()=>v.current&&g.current===P;E()&&(u(!0),i(null));try{let U=await r.request(m,{...c.current,signal:f.signal});return E()&&(n(U),u(!1),c.current?.onSuccess?.(U)),U}catch(U){let S=ho(U);throw E()&&(i(S),u(!1),c.current?.onError?.(S)),S}},[r]),h=(0,ne.useCallback)(m=>{C(m).catch(()=>{})},[C]),p=(0,ne.useCallback)(()=>{g.current++,l.current?.abort(),l.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:h,mutateAsync:C,data:o,error:s,isPending:a,reset:p}}var se=require("react");function Kr(e){return e instanceof Error?e:new Error(String(e))}var So=e=>typeof e=="string"?e:String(e);function $r(e,t){let r=(0,se.useMemo)(()=>Ge(e),[e]),[o,n]=(0,se.useState)(""),[s,i]=(0,se.useState)(!1),[a,u]=(0,se.useState)(null),c=(0,se.useRef)(t);c.current=t;let g=(0,se.useRef)(0),l=(0,se.useRef)(null),v=(0,se.useRef)(!0);(0,se.useEffect)(()=>(v.current=!0,()=>{v.current=!1,l.current?.cancel(),l.current=null}),[]);let C=(0,se.useCallback)(()=>{g.current++,l.current?.cancel(),l.current=null,v.current&&i(!1)},[]),h=(0,se.useCallback)(async p=>{l.current?.cancel();let m=++g.current,f=()=>v.current&&g.current===m,P=c.current,E=P?.parseChunk??So,U=P?.buildPayload??(R=>({prompt:R}));f()&&(n(""),u(null),i(!0));let{parseChunk:S,buildPayload:k,onFinish:x,onError:T,...D}=P??{},d="",b;try{b=r.requestStream(U(p),D),l.current=b}catch(R){let _=Kr(R);f()&&(u(_),i(!1),P?.onError?.(_));return}try{for await(let R of b){if(g.current!==m)break;d+=E(R),f()&&n(d)}f()&&(i(!1),P?.onFinish?.(d))}catch(R){let _=Kr(R);f()&&(u(_),i(!1),P?.onError?.(_))}finally{l.current===b&&(l.current=null)}},[r]);return{completion:o,complete:h,stop:C,isStreaming:s,error:a}}var G=require("react");function Xr(e){return e instanceof Error?e:new Error(String(e))}var vo=e=>typeof e=="string"?e:String(e),zr=0;function cr(e){return zr+=1,`${e}-${zr}`}function Jr(e,t){let r=(0,G.useMemo)(()=>Ge(e),[e]),[o,n]=(0,G.useState)(()=>(t?.initialMessages??[]).map(E=>({id:E.id??cr("msg"),role:E.role,content:E.content}))),[s,i]=(0,G.useState)(""),[a,u]=(0,G.useState)(!1),[c,g]=(0,G.useState)(null),l=(0,G.useRef)(t);l.current=t;let v=(0,G.useRef)(o);v.current=o;let C=(0,G.useRef)(s);C.current=s;let h=(0,G.useRef)(0),p=(0,G.useRef)(null),m=(0,G.useRef)(!0);(0,G.useEffect)(()=>(m.current=!0,()=>{m.current=!1,p.current?.cancel(),p.current=null}),[]);let f=(0,G.useCallback)(()=>{h.current++,p.current?.cancel(),p.current=null,m.current&&u(!1)},[]),P=(0,G.useCallback)(async E=>{let U=E===void 0,S=(U?C.current:E)??"";if(!S.trim())return;p.current?.cancel();let x=++h.current,T=()=>m.current&&h.current===x,D=l.current,d=D?.parseChunk??vo,b={id:cr("msg"),role:"user",content:S},R={id:cr("msg"),role:"assistant",content:""},_=[...v.current,b].map(W=>({role:W.role,content:W.content})),V=[...v.current,b,R];v.current=V,n(V),U&&i(""),g(null),u(!0);let z=D?.buildPayload??(W=>({messages:W})),{initialMessages:L,parseChunk:N,buildPayload:F,onFinish:$,onError:K,...B}=D??{},ee=W=>{n(Y=>Y.map(ge=>ge.id===R.id?{...ge,content:W}:ge))},ie="",te;try{te=r.requestStream(z(_),B),p.current=te}catch(W){let Y=Xr(W);T()&&(g(Y),u(!1),D?.onError?.(Y));return}try{for await(let W of te){if(h.current!==x)break;ie+=d(W),T()&&ee(ie)}T()&&(u(!1),D?.onFinish?.({...R,content:ie}))}catch(W){let Y=Xr(W);T()&&(g(Y),u(!1),D?.onError?.(Y))}finally{p.current===te&&(p.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:P,stop:f,isStreaming:a,error:c}}var J=require("react"),Ye=require("@urun-sh/core"),lr=[];function Gr(e,t={}){let{field:r=Ye.INPUT_PRESENCE_FIELD,hz:o=Ye.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,J.useMemo)(()=>s?(0,Ye.createInputPresencePublisher)({awareness:{setLocalStateField:(S,k)=>s.setField(S,k)},field:r,hz:o}):null,[s,r,o]),a=(0,J.useRef)(null);a.current=i;let[u,c]=(0,J.useState)(!1),[g,l]=(0,J.useState)(lr),v=(0,J.useRef)(!1);(0,J.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let C=(0,J.useCallback)(()=>{let S=a.current;l(S?S.heldKeys():lr)},[]),h=(0,J.useCallback)(()=>{a.current?.clear(),l(lr)},[]);(0,J.useEffect)(()=>{if(!n)return;let S=()=>!!n.pointerLockElement,k=()=>{if(S()){v.current=!1,c(!0);return}v.current||(c(!1),h())},x=R=>{S()&&(a.current?.keyDown(R.key),C())},T=R=>{a.current?.keyUp(R.key),C()},D=R=>{S()&&a.current?.movePointer(R.movementX,R.movementY)},d=R=>{S()&&a.current?.setButtons(R.buttons)},b=()=>{h()};return n.addEventListener("pointerlockchange",k),n.addEventListener("keydown",x),n.addEventListener("keyup",T),n.addEventListener("mousemove",D),n.addEventListener("mousedown",d),n.addEventListener("mouseup",d),n.defaultView?.addEventListener("blur",b),()=>{n.removeEventListener("pointerlockchange",k),n.removeEventListener("keydown",x),n.removeEventListener("keyup",T),n.removeEventListener("mousemove",D),n.removeEventListener("mousedown",d),n.removeEventListener("mouseup",d),n.defaultView?.removeEventListener("blur",b)}},[n,h,C]);let p=(0,J.useCallback)(S=>{S.requestPointerLock?.()},[]),m=(0,J.useCallback)(()=>{v.current=!0,c(!0)},[]),f=(0,J.useCallback)(()=>{v.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),h()},[n,h]),P=(0,J.useCallback)(S=>{a.current?.keyDown(S),C()},[C]),E=(0,J.useCallback)(S=>{a.current?.keyUp(S),C()},[C]),U=(0,J.useCallback)((S,k)=>{a.current?.movePointer(S,k)},[]);return{engage:p,engageTouch:m,release:f,engaged:u,heldKeys:g,pressKey:P,releaseKey:E,movePointer:U}}var ue=require("react"),on=require("@urun-sh/core");var O=require("react"),nn=require("@urun-sh/core");var ft=require("react"),Qr=require("react/jsx-runtime"),dr=(0,ft.createContext)(null);function Yr({session:e,children:t}){return(0,Qr.jsx)(dr.Provider,{value:e,children:t})}function Ee(){return(0,ft.useContext)(dr)}function Zr(){let e=(0,ft.useContext)(dr);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 gt=require("react/jsx-runtime");function yo(e,t){return e-t>>>0<2147483648}var en=1e3;function ko(...e){console.debug("[video]",...e)}function tn(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(u=>u.on("track",()=>i(n())));return()=>{for(let u of a)u()}}}}function rn(e,t,r){return r?[r,t]:[e,t]}var qe=(0,O.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:g,style:l,videoClassName:v,placeholder:C,poster:h,children:p,onTrack:m,onFirstFrame:f,frameMarker:P,onFrameMarkerReached:E,onFrameMarkerUnsupported:U}=t,S=Ee(),k=o??S,x=(0,O.useRef)(null),T=(0,O.useRef)(null),[D,d]=(0,O.useState)(!1),[b,R]=(0,O.useState)(!1),_=(0,O.useRef)(!1),V=(0,O.useRef)(m);V.current=m;let z=(0,O.useRef)(f);z.current=f;let L=(0,O.useRef)(E);L.current=E;let N=(0,O.useRef)(U);N.current=U;let F=(0,O.useRef)(P??null);F.current=P??null;let $=(0,O.useRef)(null),K=(0,O.useRef)(null),B=(0,O.useCallback)((y,I=!1)=>{if(!I&&y===$.current||($.current=y,K.current?.(),K.current=null,_.current=!1,R(!1),!y))return;let w=x.current;if(!w)return;let Z=F.current,re=Z?.rtpTimestamp??null,be=!1,A=()=>{be||(be=!0,N.current?.())};Z&&re==null&&A();let Pe=Z!=null&&re!=null,Te=Re=>{K.current?.(),K.current=null,_.current=!0,R(!0),z.current?.(),Re&&L.current?.()};if(typeof w.requestVideoFrameCallback=="function"){let Re=!1,Ke=0,ut=(Tr,nr)=>{if(!Re){if(Pe){let Ut=nr?.rtpTimestamp;if(typeof Ut!="number"){A(),Te(!1);return}if(!yo(Ut,re)){Ke=w.requestVideoFrameCallback(ut);return}Te(!0);return}Te(!1)}};Ke=w.requestVideoFrameCallback(ut),K.current=()=>{Re=!0,w.cancelVideoFrameCallback?.(Ke)};return}Pe&&A();let he=()=>{let Re=w.getVideoPlaybackQuality?.();(Re?Re.totalVideoFrames>0:w.readyState>=2&&w.videoWidth>0)&&Te(!1)};w.addEventListener("loadeddata",he),w.addEventListener("timeupdate",he),w.addEventListener("playing",he),K.current=()=>{w.removeEventListener("loadeddata",he),w.removeEventListener("timeupdate",he),w.removeEventListener("playing",he)},he()},[]);(0,O.useEffect)(()=>()=>{K.current?.(),K.current=null},[]);let ee=P==null?null:`${P.rtpTimestamp??""}|${P.ptsMs??""}`,ie=(0,O.useRef)(ee);(0,O.useEffect)(()=>{if(ie.current===ee||(ie.current=ee,ee==null))return;let y=$.current;y&&B(y,!0)},[ee,B]);let te=(0,O.useCallback)(()=>{if(typeof MediaStream>"u")return null;T.current||(T.current=new MediaStream);let y=x.current;return y&&y.srcObject!==T.current&&(y.srcObject=T.current),T.current},[]),W=(0,O.useCallback)(y=>{let I=x.current;if(!I)return;let w=I.play();!w||typeof w.catch!="function"||w.catch(Z=>ko(`play() failed (${y})`,Z))},[]),Y=(0,O.useCallback)(y=>{let I=te();if(I){for(let w of I.getVideoTracks())w!==y&&I.removeTrack(w);if(y&&!I.getVideoTracks().includes(y)){I.addTrack(y);let w=x.current;w&&(w.srcObject=I)}y&&W("track-attach"),d(y!==null),B(y),V.current?.(y)}},[te,W,B]),ge=(0,O.useCallback)(y=>{let I=te();if(I){for(let w of I.getAudioTracks())w!==y&&I.removeTrack(w);y&&!I.getAudioTracks().includes(y)&&I.addTrack(y),y&&W("audio-attach")}},[te,W]),Ve=(0,O.useCallback)(y=>{x.current=y,y&&(a&&(y.muted=!0,y.defaultMuted=!0,y.setAttribute("muted","")),y.setAttribute("playsinline",""),y.setAttribute("webkit-playsinline",""),te())},[te,a]);(0,O.useImperativeHandle)(r,()=>({get element(){return x.current},get live(){return T.current?T.current.getVideoTracks().length>0:!1},get framed(){return _.current}}),[]);let ce=(0,nn.derivedLegRole)(n)!==void 0;(0,O.useEffect)(()=>{ce&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[ce,n]);let oe=i!==void 0;return(0,O.useEffect)(()=>{if(oe){Y(i??null);return}if(ce){Y(null);return}if(!k)return;let y=tn(k,rn(n,"video")),I=()=>{let A=T.current;return A?A.getVideoTracks()[0]??null:null},w=A=>{if(A!==I()&&(Y(A),A)){let Pe=()=>{I()===A&&Y(null)};A.addEventListener("ended",Pe)}},Z=y.track;Z&&Z.readyState==="live"&&w(Z);let re=y.on("track",A=>{A&&A.readyState!=="live"||w(A)}),be=setInterval(()=>{let A=y.track;A&&A.readyState==="live"&&w(A)},en);return()=>{re(),clearInterval(be)}},[k,n,ce,oe,i,Y]),(0,O.useEffect)(()=>{if(oe||!k||s===!1||ce)return;let y=tn(k,rn(n,"audio",s)),I=()=>{let A=T.current;return A?A.getAudioTracks()[0]??null:null},w=A=>{if(A!==I()&&(ge(A),A)){let Pe=()=>{I()===A&&ge(null)};A.addEventListener("ended",Pe)}},Z=y.track;Z&&Z.readyState==="live"&&w(Z);let re=y.on("track",A=>{A&&A.readyState!=="live"||w(A)}),be=setInterval(()=>{let A=y.track;A&&A.readyState==="live"&&w(A)},en);return()=>{re(),clearInterval(be)}},[k,n,ce,s,oe,ge]),(0,gt.jsxs)("div",{className:g,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":D?"true":"false","data-urun-video-framed":b?"true":"false",children:[(0,gt.jsx)("video",{ref:Ve,className:v,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...u?{transform:"scaleX(-1)"}:{}}}),D?null:C,h===void 0?null:(0,gt.jsx)("div",{"data-urun-video-poster":"","aria-hidden":b||void 0,style:{position:"absolute",inset:0,...b?{opacity:0,pointerEvents:"none"}:null},children:h}),p]})});var ht=require("react/jsx-runtime"),bo={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},sn=(0,ue.forwardRef)(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:u=!0,documentTarget:c,...g}=o??{},l=c!==void 0?c:typeof document<"u"?document:null,v=(0,ue.useRef)(null),C=(0,ue.useRef)(null),h=(0,ue.useRef)(0),p=(0,ue.useRef)(g);p.current=g;let m=(0,ue.useMemo)(()=>(0,on.createCameraWarp)(p.current),[]);return(0,ue.useImperativeHandle)(r,()=>({get video(){return v.current},get canvas(){return C.current},warp:m,get lastDrawTs(){return h.current}}),[m]),(0,ue.useEffect)(()=>{if(!i)return;let f=0,P=0,E=null,U=k=>{typeof k.requestVideoFrameCallback=="function"&&(E=k,P=k.requestVideoFrameCallback(function x(){m.frameArrived(),P=k.requestVideoFrameCallback(x)}))},S=k=>{f=requestAnimationFrame(S);let x=C.current,T=v.current?.element??null;if(!x||!T||(T!==E&&(E&&P&&E.cancelVideoFrameCallback?.(P),U(T)),T.readyState<2))return;m.tick(k);let D=typeof devicePixelRatio=="number"?devicePixelRatio:1,d=Math.max(1,Math.round(x.clientWidth*D)),b=Math.max(1,Math.round(x.clientHeight*D));(x.width!==d||x.height!==b)&&(x.width=d,x.height=b);let R=x.getContext("2d");if(!R)return;let _=m.transform(),V=T.videoWidth||d,z=T.videoHeight||b,N=Math.max(d/V,b/z)*(1+a)*_.scale;R.setTransform(N,0,0,N,d/2+_.translateX*d,b/2+_.translateY*b),R.drawImage(T,-V/2,-z/2),h.current=k};return f=requestAnimationFrame(S),()=>{cancelAnimationFrame(f),E&&P&&E.cancelVideoFrameCallback?.(P)}},[i,a,m]),(0,ue.useEffect)(()=>{if(!i||!u||!l)return;let f=()=>!!l.pointerLockElement,P=x=>{f()&&m.keyDown(x.key)},E=x=>m.keyUp(x.key),U=x=>{f()&&m.pointerDelta(x.movementX,x.movementY)},S=()=>{f()||m.clearKeys()},k=()=>m.clearKeys();return l.addEventListener("keydown",P),l.addEventListener("keyup",E),l.addEventListener("mousemove",U),l.addEventListener("pointerlockchange",S),l.defaultView?.addEventListener("blur",k),()=>{l.removeEventListener("keydown",P),l.removeEventListener("keyup",E),l.removeEventListener("mousemove",U),l.removeEventListener("pointerlockchange",S),l.defaultView?.removeEventListener("blur",k)}},[i,u,l,m]),i?(0,ht.jsxs)(qe,{ref:v,...s,videoClassName:s.videoClassName,style:{...s.style},children:[(0,ht.jsx)("canvas",{ref:C,style:bo,"data-urun-warp":""}),n]}):(0,ht.jsx)(qe,{ref:v,...s,children:n})});var an=new Map;function un(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);an.set(e,{component:t,schema:r})}function cn(e,t){let r=an.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 He=require("react/jsx-runtime");function ln({name:e,props:t,fallback:r}){let o=cn(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,He.jsx)(He.Fragment,{children:r}):(0,He.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,He.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,He.jsx)(n,{...o.validatedProps})}var Ze=require("zod"),We=require("react/jsx-runtime"),dn=Ze.z.object({step:Ze.z.number().min(0),total:Ze.z.number().min(1),label:Ze.z.string().optional(),variant:Ze.z.enum(["default","success","error"]).default("default")});function pr(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 pn(e){let{step:t,total:r,label:o,variant:n,percentage:s}=pr(e);return(0,We.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,We.jsx)("div",{className:"urun-progress-label",children:o}),(0,We.jsx)("div",{className:"urun-progress-bar",children:(0,We.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,We.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var It=require("zod"),St=require("react/jsx-runtime"),mn=It.z.object({state:It.z.enum(["thinking","generating","idle","error"]),message:It.z.string().optional()}),Ro={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function mr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??Ro[t]??t;return{state:t,message:n,isActive:o}}function fn(e){let{state:t,message:r,isActive:o}=mr(e);return(0,St.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,St.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,St.jsx)("span",{className:"urun-status-message",children:r})]})}var vt=require("react"),Lt=require("zod"),yt=require("react/jsx-runtime"),gn=Lt.z.object({text:Lt.z.string(),streaming:Lt.z.boolean().default(!1)});function fr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function hn(e){let{text:t,streaming:r}=fr(e),o=(0,vt.useRef)(null),n=(0,vt.useRef)(0);return(0,vt.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,yt.jsxs)("div",{className:"urun-text-stream",children:[(0,yt.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,yt.jsx)("span",{className:"urun-text-cursor"})]})}var kt=require("zod"),bt=require("react/jsx-runtime"),Sn=kt.z.object({src:kt.z.string().url(),alt:kt.z.string().optional(),caption:kt.z.string().optional()});function gr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function vn(e){let{src:t,alt:r,caption:o}=gr(e);return(0,bt.jsxs)("figure",{className:"urun-image-frame",children:[(0,bt.jsx)("img",{className:"urun-image",src:t,alt:r}),o&&(0,bt.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var Ue=require("zod"),Qe=require("react/jsx-runtime"),yn=Ue.z.object({metrics:Ue.z.array(Ue.z.object({label:Ue.z.string(),value:Ue.z.union([Ue.z.string(),Ue.z.number()]),unit:Ue.z.string().optional()}))});function hr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function kn(e){let{metrics:t}=hr(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 bn=require("react");var Cn=require("react/jsx-runtime"),Rn=(0,bn.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,Cn.jsx)(qe,{ref:r,stream:o,...n})});var X=require("react"),Pn=require("@urun-sh/core");var Ot=null;function Co(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function Rt(){if(Ot)return Ot;let e=Co();return e?(Ot=new e,Ot):null}function Ct(){let e=Rt();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var wn=require("react/jsx-runtime"),Eo=1e3,En=200;function Sr(...e){console.debug("[audio]",...e)}var Et=(0,X.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:g}=t,l=Ee(),v=o??l,C=(0,X.useRef)(null),h=(0,X.useRef)(null),p=(0,X.useRef)(null),m=(0,X.useRef)(null),f=(0,X.useRef)(u);f.current=u;let P=(0,X.useRef)(c);P.current=c;let E=(0,X.useCallback)(d=>{p.current!==d&&(p.current=d,P.current?.(d))},[]),U=(0,X.useCallback)(()=>{if(typeof MediaStream>"u")return null;h.current||(h.current=new MediaStream);let d=C.current;return d&&d.srcObject!==h.current&&(d.srcObject=h.current),h.current},[]),S=(0,X.useCallback)(d=>{let b=C.current;if(!b)return;let R=b.play();!R||typeof R.then!="function"||R.then(()=>{b.muted||E(!0)}).catch(_=>{let V=_ instanceof Error?_.name:String(_);if(V==="AbortError"){Sr(`play() aborted (${d}); retrying in ${En}ms`),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{m.current=null,S(`${d}:retry`)},En);return}if(V==="NotAllowedError"){Sr(`play() blocked pending a user gesture (${d})`),E(!1);return}Sr(`play() failed (${d})`,_)})},[E]),k=(0,X.useCallback)(d=>{let b=U();if(b){for(let R of b.getAudioTracks())R!==d&&b.removeTrack(R);d&&!b.getAudioTracks().includes(d)&&b.addTrack(d),d&&S("track-attach"),f.current?.(d)}},[U,S]),x=(0,X.useCallback)(()=>{let d=C.current;d&&(U(),d.muted=!1,S("gesture"),Ct(),E(!0))},[U,S,E]);(0,X.useImperativeHandle)(r,()=>({unlock:x,get unlocked(){return p.current===!0},get element(){return C.current}}),[x]);let T=(0,X.useCallback)(d=>{C.current=d,d&&(d.setAttribute("playsinline",""),d.setAttribute("webkit-playsinline",""),U()),g?.(d)},[U,g]),D=s!==void 0;return(0,X.useEffect)(()=>{if(D){k(s??null);return}if(!v)return;let d=v.stream(n),b=()=>{let L=h.current;return L?L.getAudioTracks()[0]??null:null},R=L=>{if(L!==b()&&(k(L),L)){let N=()=>{b()===L&&k(null)};L.addEventListener("ended",N)}},_=d.track;_&&_.readyState==="live"&&R(_);let V=d.on("track",L=>{L&&L.readyState!=="live"||R(L)}),z=setInterval(()=>{let L=d.track;L&&L.readyState==="live"&&R(L)},Eo);return()=>{V(),clearInterval(z)}},[v,n,D,s,k]),(0,X.useEffect)(()=>(0,Pn.observePageLifecycle)(()=>{Ct(),p.current===!0&&S("foreground")}),[S]),(0,X.useEffect)(()=>()=>{m.current&&clearTimeout(m.current)},[]),(0,wn.jsx)("audio",{ref:T,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),Tn=Et;var j=require("react"),et=require("@urun-sh/core");var Un=require("react/jsx-runtime"),vr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Dt(...e){console.debug("[voice]",...e)}var Pt=(0,j.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=vr,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:g,onError:l,onMicStream:v,onTrack:C,onUnlockChange:h,capture:p}=t,m=Ee(),f=o??m,P=(0,j.useRef)(null),E=(0,j.useRef)(null),U=(0,j.useRef)(null),S=(0,j.useRef)([]),k=(0,j.useRef)(!1),x=(0,j.useRef)(g);x.current=g;let T=(0,j.useRef)(l);T.current=l;let D=(0,j.useRef)(v);D.current=v;let d=(0,j.useCallback)(N=>{k.current!==N&&(k.current=N,x.current?.(N))},[]),b=(0,j.useCallback)(()=>{for(let N of S.current)N();S.current=[],U.current?.release(),U.current=null,E.current&&(E.current=null,D.current?.(null))},[]),R=(0,j.useCallback)(async()=>{let N=U.current;if(N){let B=await N.update(i);return E.current=N.stream,D.current?.(N.stream),B}let $=await(p??(0,et.sharedCaptureController)()).claim("audio",i);U.current=$,S.current=[$.onTrack((B,ee)=>{E.current=ee,D.current?.(ee),k.current&&f?.stream(n).attach(B).catch(ie=>Dt("mic re-attach after one-capture re-acquire failed",ie))}),$.onLost(B=>{U.current=null,S.current=[],E.current=null,D.current?.(null),d(!1),T.current?.(B)})],E.current=$.stream,D.current?.($.stream);let K=$.track;if(!K)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return K},[p,i,f,n,d]),_=(0,j.useCallback)(async()=>{b(),d(!1),await f?.stream(n).detach().catch(()=>{})},[f,n,b,d]),V=(0,j.useCallback)(async()=>{if(!f)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");P.current?.unlock();let N;try{N=await R()}catch(K){b();let B=(0,et.sessionFailureFromMediaError)(K,f.status);throw T.current?.(B),B}f.connect?.();let F;for(let K=1;K<=u;K++)try{await f.whenLive(a!==void 0?{timeout:a}:void 0),await f.stream(n).attach(N),d(!0);return}catch(B){F=B,Dt(`start attempt ${K}/${u} failed`,B),K<u&&await new Promise(ee=>setTimeout(ee,c))}b(),d(!1);let $=F instanceof Error?F:new Error(String(F??"voice start failed"));throw T.current?.($),$},[f,n,a,u,c,R,b,d]);(0,j.useImperativeHandle)(r,()=>({start:V,stop:_,unlock:()=>P.current?.unlock(),get active(){return k.current},get micStream(){return E.current},get audio(){return P.current}}),[V,_]);let z=(0,j.useRef)(!1),L=(0,j.useCallback)(async()=>{if(!f||!k.current||z.current)return;let N=E.current?.getAudioTracks()[0]??null;if(N&&N.readyState==="live"){try{await f.stream(n).attach(N)}catch(F){Dt("foreground mic re-assert failed (will retry on next pass)",F)}return}z.current=!0;try{let F=await R();await f.stream(n).attach(F)}catch(F){let $=F instanceof Error?F:new Error(String(F));Dt("foreground mic re-acquire failed",$),T.current?.($)}finally{z.current=!1}},[f,n,R]);return(0,j.useEffect)(()=>{let N=()=>{L()};return f&&typeof f.onRecovery=="function"?f.onRecovery(N):(0,et.observePageLifecycle)(N)},[f,L]),(0,j.useEffect)(()=>b,[b]),s?(0,Un.jsx)(Et,{ref:P,session:f,stream:n,onTrack:C,onUnlockChange:h}):null}),xn=Pt;var ye=require("react");var Vt=require("react");var yr={level:0,speaking:!1};function Ft(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,Vt.useState)(yr);return(0,Vt.useEffect)(()=>{if(!e){i(yr);return}let a=Rt();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,g;try{c=a.createMediaStreamSource(u),g=a.createAnalyser(),g.fftSize=r,c.connect(g)}catch{return}let l=new Uint8Array(g.fftSize),C=setInterval(()=>{g.getByteTimeDomainData(l);let h=0;for(let m=0;m<l.length;m++){let f=(l[m]-128)/128;h+=f*f}let p=Math.sqrt(h/l.length);i(m=>{let f=p>n;return Math.abs(m.level-p)<.005&&m.speaking===f?m:{level:p,speaking:f}})},o);return()=>{clearInterval(C),c.disconnect(),i(yr)}},[e,r,o,n]),s}var Ae=require("react/jsx-runtime"),Po={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},To={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},An=(0,ye.forwardRef)(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:g,onMicStream:l,capture:v}=t,C=Ee(),h=o??C,p=(0,ye.useRef)(null),[m,f]=(0,ye.useState)(null),P=(0,ye.useRef)(l);P.current=l;let{level:E,speaking:U}=Ft(a?m:null);return(0,ye.useImperativeHandle)(r,()=>({start:()=>{let S=p.current;return S?S.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,ye.useEffect)(()=>{!i||!h||p.current?.start().catch(()=>{})},[i,h]),(0,Ae.jsxs)(Ae.Fragment,{children:[(0,Ae.jsx)(Pt,{ref:p,session:h,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...v!==void 0?{capture:v}:{},onActiveChange:c,onError:g,onMicStream:S=>{f(S),P.current?.(S)}}),a?(0,Ae.jsx)("span",{className:u,style:Po,"data-urun-mic":"","data-urun-mic-active":m?"true":"false","data-urun-mic-speaking":U?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(E*100)/100,children:(0,Ae.jsx)("span",{style:To,children:(0,Ae.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(E*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var tt=require("@urun-sh/core"),M=require("react");var pe=require("react/jsx-runtime"),br={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function kr(...e){console.debug("[camera]",...e)}function wo(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function xo(){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 Rr=(0,M.forwardRef)(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:g="auto",connectTimeoutMs:l,visible:v=!1,className:C,videoClassName:h,onActiveChange:p,onError:m,onStream:f,onTrack:P,children:E,capture:U,flipControl:S="auto",flipControlClassName:k,onDevices:x}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let T=i?"user":a?"environment":u??"environment",D=Ee(),d=o??D,b=(0,M.useRef)(null),R=(0,M.useRef)(null),_=(0,M.useRef)(null),V=(0,M.useRef)([]),z=(0,M.useRef)(null),L=(0,M.useRef)(!1),N=(0,M.useRef)(!1),F=(0,M.useRef)(T),[$,K]=(0,M.useState)(T),[B,ee]=(0,M.useState)(!1),[ie,te]=(0,M.useState)(null),[W,Y]=(0,M.useState)(!1),[ge]=(0,M.useState)(wo),Ve=(0,M.useRef)(p);Ve.current=p;let ce=(0,M.useRef)(m);ce.current=m;let oe=(0,M.useRef)(f);oe.current=f;let y=(0,M.useRef)(P);y.current=P;let I=(0,M.useRef)(x);I.current=x;let w=(0,M.useCallback)(q=>{L.current!==q&&(L.current=q,ee(q),Ve.current?.(q))},[]);(0,M.useEffect)(()=>{if(!B){te(null);return}let q=!1,H=()=>{xo().then(Ce=>{q||(te(Ce),Ce&&I.current?.(Ce))})};H();let Se=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof Se?.addEventListener=="function"?(Se.addEventListener("devicechange",H),()=>{q=!0,Se.removeEventListener?.("devicechange",H)}):()=>{q=!0}},[B]);let Z=(0,M.useCallback)(q=>{let H=b.current;H&&(H.muted=!0,H.defaultMuted=!0,H.setAttribute("muted",""),H.setAttribute("playsinline",""),H.setAttribute("webkit-playsinline",""),H.srcObject=q,q&&H.play()?.catch?.(Se=>kr("preview play() failed",Se)))},[]),re=(0,M.useCallback)(()=>{N.current=!1,z.current?.(),z.current=null;for(let q of V.current)q();V.current=[],_.current?.release(),_.current=null,R.current&&(R.current=null,oe.current?.(null),y.current?.(null)),Z(null)},[Z]),be=(0,M.useCallback)((q,H)=>{z.current?.(),R.current=H,Z(H),oe.current?.(H);let Se=()=>{R.current===H&&(kr("camera track ended (device removed or permission revoked)"),re(),w(!1))};q.addEventListener("ended",Se),z.current=()=>q.removeEventListener("ended",Se)},[Z,re,w]),A=(0,M.useCallback)(async q=>{let H=n!==!1;if(H&&!d)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let Se={...br,...s,facingMode:q},Ce;try{let Ne=_.current;if(Ne)Ce=await Ne.update(Se);else{let ct=await(U??(0,tt.sharedCaptureController)()).claim("video",Se);if(_.current=ct,V.current=[ct.onTrack((lt,Qn)=>{be(lt,Qn),L.current&&(!H||!d||d.stream(n).attachVideo(lt).then(()=>y.current?.(lt)).catch(eo=>kr("camera re-publish after one-capture re-acquire failed",eo)))}),ct.onLost(lt=>{_.current=null,V.current=[],re(),w(!1),ce.current?.(lt)})],!ct.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});Ce=ct.track}}catch(Ne){let $e=(0,tt.sessionFailureFromMediaError)(Ne,d?.status);throw ce.current?.($e),$e}F.current=q,K(q),be(Ce,_.current?.stream??new MediaStream([Ce]));try{H&&d&&(d.connect?.(),await d.whenLive(l!==void 0?{timeout:l}:void 0),await d.stream(n).attachVideo(Ce)),N.current=H?n:!1}catch(Ne){re(),w(!1);let $e=Ne instanceof Error?Ne:new Error(String(Ne));throw ce.current?.($e),$e}y.current?.(Ce),w(!0)},[d,n,s,l,U,be,re,w]),Pe=(0,M.useCallback)(q=>A(q?.facingMode??F.current),[A]),Te=(0,M.useCallback)(async q=>{let H=N.current===n;L.current&&F.current===q&&H||await A(q)},[A,n]),he=(0,M.useCallback)(()=>A(F.current==="environment"?"user":"environment"),[A]),Re=(0,M.useCallback)(async()=>{re(),w(!1),n!==!1&&await d?.stream(n).detachVideo().catch(()=>{})},[d,n,re,w]),Ke=(0,M.useCallback)(async q=>{let H=b.current;if(!H)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await(0,tt.captureStillFromVideo)(H,q)},[]);(0,M.useImperativeHandle)(r,()=>({start:Pe,stop:Re,flip:he,setFacingMode:Te,capturePhoto:Ke,get active(){return L.current},get facingMode(){return F.current},get stream(){return R.current},get element(){return b.current}}),[Pe,Re,he,Te,Ke]);let ut=(0,M.useRef)(Te);if(ut.current=Te,(0,M.useEffect)(()=>{c&&(n!==!1&&!d||ut.current(T).catch(()=>{}))},[c,d,T,n]),(0,M.useEffect)(()=>re,[re]),!v)return null;let Tr=g==="auto"?$==="user":g,nr=B&&(S===!0||S==="auto"&&ge&&(ie?.length??0)>1),Ut=()=>{W||(Y(!0),he().catch(()=>{}).finally(()=>Y(!1)))};return(0,pe.jsxs)("div",{className:C,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":$,children:[(0,pe.jsx)("video",{ref:b,className:h,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Tr?{transform:"scaleX(-1)"}:{}}}),nr?(0,pe.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Ut,disabled:W,className:k,style:k?{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:(0,pe.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,pe.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,pe.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,pe.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,pe.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,pe.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,E]})}),Mn=(0,M.forwardRef)(function({preview:t=!0,...r},o){return(0,pe.jsx)(Rr,{ref:o,...r,visible:t,autoStart:!1})});var rt=require("@urun-sh/core"),Q=require("react");function _n(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=(0,Q.useState)(null),[a,u]=(0,Q.useState)(null),[c,g]=(0,Q.useState)(!1),[l,v]=(0,Q.useState)(null),[C]=(0,Q.useState)(rt.cameraCaptureAvailable),h=(0,Q.useRef)(n);h.current=n;let p=(0,Q.useRef)(null),m=(0,Q.useRef)(0),f=(0,Q.useCallback)(k=>{p.current&&URL.revokeObjectURL(p.current),p.current=k?URL.createObjectURL(new Blob([k.bytes],{type:k.type})):null,u(p.current),i(k),h.current?.(k)},[]);(0,Q.useEffect)(()=>()=>{m.current++,p.current&&URL.revokeObjectURL(p.current),p.current=null},[]);let P=(0,Q.useCallback)(async k=>{let x=++m.current;g(!0),v(null);try{let T=await k();if(m.current!==x)return;f(T)}catch(T){if(m.current!==x)return;v((0,rt.referenceImageErrorMessage)(T))}finally{m.current===x&&g(!1)}},[f]),E=(0,Q.useCallback)(k=>P(()=>(0,rt.normalizeReferenceImage)(k,{maxSize:t,type:r,quality:o,source:"file"})),[P,t,r,o]),U=(0,Q.useCallback)(k=>P(()=>k.capturePhoto({maxSize:t,type:r,quality:o})),[P,t,r,o]),S=(0,Q.useCallback)(()=>{m.current++,v(null),g(!1),f(null)},[f]);return{reference:s,previewUrl:a,pick:E,capture:U,clear:S,busy:c,error:l,cameraAvailable:C}}var qt=require("react");function Nn(e,t){let[r,o]=(0,qt.useState)(null);return(0,qt.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var On=require("react");var Wt=require("react");var In=require("zustand/vanilla"),Ln=require("zustand"),Uo=()=>{};function Ht(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=(0,In.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):Uo,u=(c=>(0,Ln.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 nt(e,t){let r=(0,Wt.useMemo)(()=>Ht(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,Wt.useEffect)(()=>r.bind(),[r]),r}function Dn(e,t,r){let n=nt(e,t)(r??(a=>a)),s=(0,On.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 jt=require("react");var Ie=200;function Me(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function ot(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Bt(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 Kt(e,t,r={}){let o=r.cap??200,[n,s]=(0,jt.useState)([]);return(0,jt.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=>Me(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}var ke=require("react/jsx-runtime");function Vn({session:e,name:t,cap:r,className:o}){let n=Kt(e,t,{cap:r});return(0,ke.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,ke.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,ke.jsx)("code",{children:t}),(0,ke.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,ke.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,ke.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,ke.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,i)=>(0,ke.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,ke.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",ot(s.payload)]},`${s.at}-${i}`))})]})}var Tt=require("react");var de=require("react/jsx-runtime");function wt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,Tt.useState)(""),[i,a]=(0,Tt.useState)(null),u=(0,Tt.useCallback)(()=>{let c=Bt(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return(0,de.jsxs)("div",{className:"urun-doc-patch",children:[(0,de.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),(0,de.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,de.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?(0,de.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function Fn({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=nt(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return(0,de.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,de.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,de.jsx)("code",{children:t}),(0,de.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,de.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,de.jsx)(wt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}var $t=require("react");var _e=require("react/jsx-runtime");function qn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Hn({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=>Me(u,{at:Date.now(),direction:"in",text:qn(ot(a))},r))}):void 0),[e,t,r]),(0,_e.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,_e.jsx)(wt,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>Me(u,{at:Date.now(),direction:"out",text:qn(a)},r))}}),(0,_e.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,_e.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>(0,_e.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,_e.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,_e.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}var Xt=require("react");var Be=require("react/jsx-runtime");function Wn({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=(0,Xt.useState)([]),a=t.join(","),u=r.join(",");return(0,Xt.useEffect)(()=>{if(i([]),!e)return;let c=(l,v)=>i(C=>Me(C,{at:Date.now(),kind:l,text:v},o)),g=[];g.push(e.onPhase(l=>c("phase",`phase \u2192 ${l.name}`)));for(let l of t){let v=e.stream(l);g.push(v.on("track",C=>c("track",`${l}: ${C?"track arrived":"track ended"}`)))}for(let l of r){let v=e.doc(l);g.push(v.on("change",()=>c("doc",`${l} changed`)))}return()=>g.forEach(l=>l())},[e,a,u,o]),(0,Be.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,Be.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,g)=>(0,Be.jsxs)("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[(0,Be.jsx)("span",{className:"urun-event-spine-kind",children:c.kind})," ",(0,Be.jsx)("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${g}`))})}var er=require("@urun-sh/core");var zt=require("react");function me(e){let[t,r]=(0,zt.useState)(e?.phase??null);return(0,zt.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var jn=require("@urun-sh/core");var st=require("react"),Bn=require("@urun-sh/core");function Jt(e){let t=me(e),r=(0,Bn.isWakingPhase)(t?.name),o=(0,st.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,st.useState)(s);return(0,st.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 Le=require("react/jsx-runtime");function Gt({session:e,render:t,className:r}){let o=Jt(e);return!o.waking||!o.phase?null:(0,Le.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,Le.jsxs)(Le.Fragment,{children:[(0,Le.jsx)("span",{className:"urun-session-waking-label",children:(0,jn.describeSessionPhase)(o.phase)})," ",(0,Le.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var Zt=require("react");var Oe=require("react"),Ao={event:null,elapsedMs:0};function Yt(e,t){let[r,o]=(0,Oe.useState)(null),n=(0,Oe.useRef)(0);(0,Oe.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,Oe.useState)(0);return(0,Oe.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}:Ao}var it=require("react/jsx-runtime"),Mo={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 _o(e){let[t,r]=(0,Zt.useState)(!1);return(0,Zt.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 Qt({session:e,stream:t,videoElement:r,render:o,className:n}){let s=Yt(e,t),i=_o(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return(0,it.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):(0,it.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,it.jsx)("span",{className:"urun-activation-overlay-copy",children:a.hint??Mo[u]})," ",(0,it.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var fe=require("react/jsx-runtime"),No={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function Kn({session:e,className:t}){let r=me(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,fe.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,fe.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,fe.jsx)("span",{className:"urun-session-status-label",children:No[o]}),n?(0,fe.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function $n({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=me(e);if(s?.name==="live")return(0,fe.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,fe.jsx)(Qt,{session:e})]});let i=r?r(s):(0,fe.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&(0,er.isWakingPhase)(s.name)?(0,fe.jsx)(Gt,{session:e}):s&&s.name!=="idle"?(0,er.describeSessionPhase)(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return(0,fe.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,fe.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var tr=require("react");var zn=require("react/jsx-runtime");function Cr(e){return me(e)?.endsAt??null}function Io(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 Xn({session:e,urgentMs:t=6e4,className:r}){let n=Cr(e)?.getTime()??null,[s,i]=(0,tr.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,tr.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=Io(s);return(0,zn.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 xt=require("react/jsx-runtime"),Lo=new Set(["expired","ended","error"]);function Jn({session:e,onNewSession:t,children:r,className:o}){let n=me(e);if(!n||!Lo.has(n.name))return null;let s=r?r(n):(0,xt.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,xt.jsxs)("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?(0,xt.jsx)("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}var De=require("react"),je=require("react/jsx-runtime");function Er(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 Pr(e){let t=(0,De.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,De.useState)(()=>t?Er(t.get("idle")):null);return(0,De.useEffect)(()=>{if(!t){o(null);return}return o(Er(t.get("idle"))),t.on("change",()=>o(Er(t.get("idle"))))},[t]),r}function Oo(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Gn({session:e,onStillHere:t,className:r}){let o=Pr(e),n=o?.deadlineEpochS??null,[s,i]=(0,De.useState)(null);if((0,De.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,je.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,je.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,je.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,je.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Oo(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,je.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var at=require("react"),Yn=require("@urun-sh/core");function Zn(e){let t=(0,at.useContext)(ze),[r,o]=(0,at.useState)(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,g=t?.getAccessToken,l=t?.authProvider;return(0,at.useEffect)(()=>{if(!a||!u||!n||!s)return;let v=!1,C=()=>{(0,Yn.prewake)({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:g,authProvider:l}).then(p=>{v||o(p)}).catch(()=>{})};C();let h=setInterval(C,Math.max(1,i)*1e3);return()=>{v=!0,clearInterval(h)}},[n,s,i,a,u,c,g,l]),r}var rr=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,ReprojectedVideo,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,useReferenceImage,useRequest,useSession,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
2
+ "use strict";var sr=Object.defineProperty;var ro=Object.getOwnPropertyDescriptor;var no=Object.getOwnPropertyNames;var oo=Object.prototype.hasOwnProperty;var so=(e,t)=>{for(var r in t)sr(e,r,{get:t[r],enumerable:!0})},io=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of no(t))!oo.call(e,n)&&n!==r&&sr(e,n,{get:()=>t[n],enumerable:!(o=ro(t,n))||o.enumerable});return e};var ao=e=>io(sr({},"__esModule",{value:!0}),e);var Do={};so(Do,{Audio:()=>wt,Camera:()=>Cr,ComponentRenderer:()=>dn,DEFAULT_CAMERA_CONSTRAINTS:()=>Rr,DEFAULT_LOG_CAP:()=>Fe,DEFAULT_VOICE_CONSTRAINTS:()=>yr,DocPatchForm:()=>At,Image:()=>Cn,ImageFrame:()=>yn,ImageFrameSchema:()=>vn,MetricsPanel:()=>bn,MetricsPanelSchema:()=>kn,Mic:()=>Mn,OPERATOR_CHORD_LABEL:()=>Or,OPERATOR_TOKEN_STORAGE_KEY:()=>Ir,ProgressCard:()=>mn,ProgressCardSchema:()=>pn,ReprojectedVideo:()=>an,Session:()=>Yr,StatusBadge:()=>gn,StatusBadgeSchema:()=>fn,TextStream:()=>Sn,TextStreamSchema:()=>hn,UrunActivationOverlay:()=>tr,UrunAudio:()=>wn,UrunAuthProvider:()=>St,UrunCamera:()=>_n,UrunControlSender:()=>Wn,UrunDocPanel:()=>qn,UrunErrorBoundary:()=>Ze,UrunEventSpine:()=>Bn,UrunIdleWarning:()=>Yn,UrunJwtProvider:()=>Mr,UrunProvider:()=>Hr,UrunSessionClock:()=>zn,UrunSessionEnded:()=>Gn,UrunSessionGate:()=>Xn,UrunSessionStatus:()=>$n,UrunSessionWaking:()=>Zt,UrunStreamTail:()=>Fn,UrunVoice:()=>Un,Video:()=>Ke,Voice:()=>xt,authMode:()=>ht,createDocStore:()=>Bt,describeSessionPhase:()=>or.describeSessionPhase,formatPayload:()=>ct,getUrunAudioContext:()=>vt,isWakingPhase:()=>or.isWakingPhase,parseJsonObject:()=>Kt,pushCapped:()=>Oe,readOperatorToken:()=>ir,registerComponent:()=>cn,resumeUrunAudioContext:()=>je,urunPublicEnv:()=>Ce,useActivation:()=>Qt,useApp:()=>Br,useChat:()=>Jr,useCompletion:()=>$r,useConfirmOnLeave:()=>Lt,useDocStore:()=>ut,useImageFrame:()=>hr,useInputPresence:()=>Gr,useMetricsPanel:()=>Sr,useOperatorOverride:()=>It,useProgressCard:()=>mr,useReferenceImage:()=>Nn,useRequest:()=>jr,useSession:()=>Zr,useSessionDoc:()=>Vn,useSessionEndsAt:()=>Pr,useSessionIdle:()=>Tr,useSessionPhase:()=>ke,useSessionTrack:()=>In,useSessionWake:()=>Yt,useStatusBadge:()=>fr,useStreamMessages:()=>Xt,useTextStream:()=>gr,useUrunAudioLevel:()=>Ht,useUrunAuth:()=>_t,useUrunPrewake:()=>Qn,usesWorkOSAuth:()=>Ur});module.exports=ao(Do);var de=require("react");var wr=require("react"),gt=require("react/jsx-runtime"),Ze=class extends wr.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,gt.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,gt.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,gt.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var xr=require("react"),Qe=(0,xr.createContext)(null);function _e(e){return e&&e.trim()?e.trim():void 0}function Ce(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return _e(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return _e(typeof process<"u"?process.env?.[e]:void 0)}}function ht(){let e=Ce("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||Ce("VERCEL_ENV")==="production"?"workos":Ce("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Ur(){return ht()==="workos"}var et=require("react"),_r=require("react/jsx-runtime"),Ar=(0,et.createContext)(null);function St({getAccessToken:e,children:t}){let r=(0,et.useMemo)(()=>({getAccessToken:e}),[e]);return(0,_r.jsx)(Ar.Provider,{value:r,children:t})}var Mr=St;function _t(){return(0,et.useContext)(Ar)}var Nt=require("react"),Ir="urun.operator_token",Lr=null,Nr="op",Or="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function Dr(){return typeof window<"u"}function ir(){return Lr}function uo(){if(!Dr())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(Nr);if(!r)return null;Lr=r,t.delete(Nr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function co(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function It(e){let t=(0,Nt.useRef)(e);t.current=e,(0,Nt.useEffect)(()=>{if(!Dr())return;uo();let r=o=>{if(!co(o))return;let n=ir();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var Vr=require("react");function Lt(e=!0){(0,Vr.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 Ne=require("react/jsx-runtime"),lo="/api/urun-token",po=1e4;function mo(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 Fr(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 qr(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function fo(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,Ne.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,Ne.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,Ne.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Hr({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,audioPlayout:f,confirmOnLeave:d=!1,fallback:y,errorFallback:b,children:k}){let l=n===void 0&&t===void 0;if(!l&&(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(!l&&(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 g=r??o;if(l&&(typeof g!="string"||g.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);Lt(d);let[m,P]=(0,de.useState)(),[R,w]=(0,de.useState)(null),h=(0,de.useRef)(void 0),C=(0,de.useRef)(null),[T,x]=(0,de.useState)(null);It(ee=>x({jwt:ee}));let U=_t(),p=Ce("NEXT_PUBLIC_SESSION_TOKEN")??Ce("NEXT_PUBLIC_URUN_JWT"),E=ht(),v=T!==null,_=E==="workos"&&!n&&!v&&!l,B=n??(E==="jwt"?p:void 0)??m?.token,q=v?T.jwt:B,O=s??Ce("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),L=_&&!q&&!U?.getAccessToken,H=t??m?.orgId,K=e??m?.gatewayUrl,re=l&&m===void 0,$=l&&m!==void 0&&!K?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,oe=L?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,ie=R??$??oe,z=qr("NEXT_PUBLIC_URUN_TOKEN_URL",Ce("NEXT_PUBLIC_URUN_TOKEN_URL"))??u??lo,W=qr("NEXT_PUBLIC_URUN_EVENTS_URL",Ce("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,G=(0,de.useCallback)(async ee=>{if(!ee?.forceRefresh){let Z=h.current;if(!Z)return Z;let ce=mo(Z);if(ce===null||ce-Date.now()>po)return Z}return(await(C.current??(C.current=(async()=>{try{let Z=await Fr(z);return h.current=Z.token,P(Z),Z}finally{C.current=null}})()))).token},[z]),Te=(0,de.useCallback)(async()=>q,[q]),me=typeof q=="string"&&q.trim().length>0,ae=_?U?.getAccessToken:l&&!v?G:me?Te:void 0,Ve=(0,de.useMemo)(()=>({appId:g,baseUrl:K??"",orgId:H??"",jwt:q,getAccessToken:_?U?.getAccessToken:l&&!v?G:void 0,authProvider:O,eventsUrl:W,sessionKey:a,releaseOnLeave:c,audioPlayout:f,priority:v?"preempt":void 0}),[g,U,K,O,q,W,H,a,c,f,_,v,l,G]);return(0,de.useEffect)(()=>{if(!l)return;let ee=new AbortController;return w(null),(async()=>{try{let ue=await Fr(z,ee.signal);h.current=ue.token,P(ue)}catch(ue){if(ee.signal.aborted)return;w(ue instanceof Error?ue:new Error(String(ue)))}})(),()=>ee.abort()},[l,z]),(0,Ne.jsx)(Ze,{fallback:y,children:ie?fo(b,ie):re?(0,Ne.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,Ne.jsx)(Qe.Provider,{value:Ve,children:ae?(0,Ne.jsx)(St,{getAccessToken:ae,children:k}):k})})}var fe=require("react"),Wr=require("@urun-sh/core");function go(e,t){return`${e}:${JSON.stringify(t??{})}`}function ho(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 Be=new Map;var ar=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()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}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()}},ur=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()}},cr=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 ar(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new ur(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 Br(){let e=(0,fe.useContext)(Qe);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,fe.useReducer)(i=>i+1,0),r=(0,fe.useRef)(new Map),o=(0,fe.useRef)(new Map),n=(0,fe.useRef)(null),s=(0,fe.useMemo)(()=>(0,Wr.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,audioPlayout:e.audioPlayout}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority,e.audioPlayout]);return(0,fe.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=Be.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=Be.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=Be.get(u);!d||d.refCount!==0||(Be.delete(u),d.handle.disconnect())},0)))}n.current=a}},[]),(0,fe.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 y=go(u,d),b=r.current.get(y);if(b&&!b.disposed)return b;let k=ho(e,u,d),l=Be.get(k);return l?.handle.disposed&&(l.disposeTimer&&clearTimeout(l.disposeTimer),Be.delete(k),o.current.get(k)===l&&o.current.delete(k),l=void 0),l?l.disposeTimer&&(clearTimeout(l.disposeTimer),l.disposeTimer=null):(l={handle:new cr(s[u](d),t,e.eventsUrl),refCount:0,disposeTimer:null},Be.set(k,l)),o.current.get(k)!==l&&(o.current.set(k,l),l.handle.addNotifier(t),l.refCount+=1),r.current.set(y,l.handle),l.handle};return i.set(u,f),f}})},[e,s])}var ne=require("react");function tt(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 So(e){return e instanceof Error?e:new Error(String(e))}function jr(e,t){let r=(0,ne.useMemo)(()=>tt(e),[e]),[o,n]=(0,ne.useState)(void 0),[s,i]=(0,ne.useState)(null),[a,u]=(0,ne.useState)(!1),c=(0,ne.useRef)(t);c.current=t;let f=(0,ne.useRef)(0),d=(0,ne.useRef)(null),y=(0,ne.useRef)(!0);(0,ne.useEffect)(()=>(y.current=!0,()=>{y.current=!1,d.current?.abort()}),[]);let b=(0,ne.useCallback)(async g=>{d.current?.abort();let m=new AbortController;d.current=m;let P=++f.current,R=()=>y.current&&f.current===P;R()&&(u(!0),i(null));try{let w=await r.request(g,{...c.current,signal:m.signal});return R()&&(n(w),u(!1),c.current?.onSuccess?.(w)),w}catch(w){let h=So(w);throw R()&&(i(h),u(!1),c.current?.onError?.(h)),h}},[r]),k=(0,ne.useCallback)(g=>{b(g).catch(()=>{})},[b]),l=(0,ne.useCallback)(()=>{f.current++,d.current?.abort(),d.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:k,mutateAsync:b,data:o,error:s,isPending:a,reset:l}}var se=require("react");function Kr(e){return e instanceof Error?e:new Error(String(e))}var vo=e=>typeof e=="string"?e:String(e);function $r(e,t){let r=(0,se.useMemo)(()=>tt(e),[e]),[o,n]=(0,se.useState)(""),[s,i]=(0,se.useState)(!1),[a,u]=(0,se.useState)(null),c=(0,se.useRef)(t);c.current=t;let f=(0,se.useRef)(0),d=(0,se.useRef)(null),y=(0,se.useRef)(!0);(0,se.useEffect)(()=>(y.current=!0,()=>{y.current=!1,d.current?.cancel(),d.current=null}),[]);let b=(0,se.useCallback)(()=>{f.current++,d.current?.cancel(),d.current=null,y.current&&i(!1)},[]),k=(0,se.useCallback)(async l=>{d.current?.cancel();let g=++f.current,m=()=>y.current&&f.current===g,P=c.current,R=P?.parseChunk??vo,w=P?.buildPayload??(v=>({prompt:v}));m()&&(n(""),u(null),i(!0));let{parseChunk:h,buildPayload:C,onFinish:T,onError:x,...U}=P??{},p="",E;try{E=r.requestStream(w(l),U),d.current=E}catch(v){let _=Kr(v);m()&&(u(_),i(!1),P?.onError?.(_));return}try{for await(let v of E){if(f.current!==g)break;p+=R(v),m()&&n(p)}m()&&(i(!1),P?.onFinish?.(p))}catch(v){let _=Kr(v);m()&&(u(_),i(!1),P?.onError?.(_))}finally{d.current===E&&(d.current=null)}},[r]);return{completion:o,complete:k,stop:b,isStreaming:s,error:a}}var Q=require("react");function Xr(e){return e instanceof Error?e:new Error(String(e))}var yo=e=>typeof e=="string"?e:String(e),zr=0;function lr(e){return zr+=1,`${e}-${zr}`}function Jr(e,t){let r=(0,Q.useMemo)(()=>tt(e),[e]),[o,n]=(0,Q.useState)(()=>(t?.initialMessages??[]).map(R=>({id:R.id??lr("msg"),role:R.role,content:R.content}))),[s,i]=(0,Q.useState)(""),[a,u]=(0,Q.useState)(!1),[c,f]=(0,Q.useState)(null),d=(0,Q.useRef)(t);d.current=t;let y=(0,Q.useRef)(o);y.current=o;let b=(0,Q.useRef)(s);b.current=s;let k=(0,Q.useRef)(0),l=(0,Q.useRef)(null),g=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let m=(0,Q.useCallback)(()=>{k.current++,l.current?.cancel(),l.current=null,g.current&&u(!1)},[]),P=(0,Q.useCallback)(async R=>{let w=R===void 0,h=(w?b.current:R)??"";if(!h.trim())return;l.current?.cancel();let T=++k.current,x=()=>g.current&&k.current===T,U=d.current,p=U?.parseChunk??yo,E={id:lr("msg"),role:"user",content:h},v={id:lr("msg"),role:"assistant",content:""},_=[...y.current,E].map(W=>({role:W.role,content:W.content})),B=[...y.current,E,v];y.current=B,n(B),w&&i(""),f(null),u(!0);let q=U?.buildPayload??(W=>({messages:W})),{initialMessages:O,parseChunk:L,buildPayload:H,onFinish:K,onError:re,...$}=U??{},oe=W=>{n(G=>G.map(Te=>Te.id===v.id?{...Te,content:W}:Te))},ie="",z;try{z=r.requestStream(q(_),$),l.current=z}catch(W){let G=Xr(W);x()&&(f(G),u(!1),U?.onError?.(G));return}try{for await(let W of z){if(k.current!==T)break;ie+=p(W),x()&&oe(ie)}x()&&(u(!1),U?.onFinish?.({...v,content:ie}))}catch(W){let G=Xr(W);x()&&(f(G),u(!1),U?.onError?.(G))}finally{l.current===z&&(l.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:P,stop:m,isStreaming:a,error:c}}var Y=require("react"),rt=require("@urun-sh/core"),dr=[];function Gr(e,t={}){let{field:r=rt.INPUT_PRESENCE_FIELD,hz:o=rt.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,Y.useMemo)(()=>s?(0,rt.createInputPresencePublisher)({awareness:{setLocalStateField:(h,C)=>s.setField(h,C)},field:r,hz:o}):null,[s,r,o]),a=(0,Y.useRef)(null);a.current=i;let[u,c]=(0,Y.useState)(!1),[f,d]=(0,Y.useState)(dr),y=(0,Y.useRef)(!1);(0,Y.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let b=(0,Y.useCallback)(()=>{let h=a.current;d(h?h.heldKeys():dr)},[]),k=(0,Y.useCallback)(()=>{a.current?.clear(),d(dr)},[]);(0,Y.useEffect)(()=>{if(!n)return;let h=()=>!!n.pointerLockElement,C=()=>{if(h()){y.current=!1,c(!0);return}y.current||(c(!1),k())},T=v=>{h()&&(a.current?.keyDown(v.key),b())},x=v=>{a.current?.keyUp(v.key),b()},U=v=>{h()&&a.current?.movePointer(v.movementX,v.movementY)},p=v=>{h()&&a.current?.setButtons(v.buttons)},E=()=>{k()};return n.addEventListener("pointerlockchange",C),n.addEventListener("keydown",T),n.addEventListener("keyup",x),n.addEventListener("mousemove",U),n.addEventListener("mousedown",p),n.addEventListener("mouseup",p),n.defaultView?.addEventListener("blur",E),()=>{n.removeEventListener("pointerlockchange",C),n.removeEventListener("keydown",T),n.removeEventListener("keyup",x),n.removeEventListener("mousemove",U),n.removeEventListener("mousedown",p),n.removeEventListener("mouseup",p),n.defaultView?.removeEventListener("blur",E)}},[n,k,b]);let l=(0,Y.useCallback)(h=>{h.requestPointerLock?.()},[]),g=(0,Y.useCallback)(()=>{y.current=!0,c(!0)},[]),m=(0,Y.useCallback)(()=>{y.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),k()},[n,k]),P=(0,Y.useCallback)(h=>{a.current?.keyDown(h),b()},[b]),R=(0,Y.useCallback)(h=>{a.current?.keyUp(h),b()},[b]),w=(0,Y.useCallback)((h,C)=>{a.current?.movePointer(h,C)},[]);return{engage:l,engageTouch:g,release:m,engaged:u,heldKeys:f,pressKey:P,releaseKey:R,movePointer:w}}var pe=require("react"),sn=require("@urun-sh/core");var I=require("react"),on=require("@urun-sh/core");var Ot=null;function ko(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function vt(){if(Ot)return Ot;let e=ko();return e?(Ot=new e,Ot):null}function je(){let e=vt();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var yt=require("react"),Qr=require("react/jsx-runtime"),pr=(0,yt.createContext)(null);function Yr({session:e,children:t}){return(0,Qr.jsx)(pr.Provider,{value:e,children:t})}function we(){return(0,yt.useContext)(pr)}function Zr(){let e=(0,yt.useContext)(pr);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 kt=require("react/jsx-runtime");function bo(e,t){return e-t>>>0<2147483648}var en=1e3;function tn(...e){console.debug("[video]",...e)}function rn(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(u=>u.on("track",()=>i(n())));return()=>{for(let u of a)u()}}}}function nn(e,t,r){return r?[r,t]:[e,t]}var Ke=(0,I.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:y,placeholder:b,poster:k,children:l,onTrack:g,onFirstFrame:m,frameMarker:P,onFrameMarkerReached:R,onFrameMarkerUnsupported:w,onUnlockChange:h}=t,C=we(),T=o??C,x=(0,I.useRef)(null),U=(0,I.useRef)(null),[p,E]=(0,I.useState)(!1),[v,_]=(0,I.useState)(!1),B=(0,I.useRef)(!1),q=(0,I.useRef)(null),O=(0,I.useRef)(g);O.current=g;let L=(0,I.useRef)(h);L.current=h;let H=(0,I.useRef)(m);H.current=m;let K=(0,I.useRef)(R);K.current=R;let re=(0,I.useRef)(w);re.current=w;let $=(0,I.useRef)(P??null);$.current=P??null;let oe=(0,I.useCallback)(S=>{q.current!==S&&(q.current=S,L.current?.(S))},[]),ie=(0,I.useRef)(null),z=(0,I.useRef)(null),W=(0,I.useCallback)((S,D=!1)=>{if(!D&&S===ie.current||(ie.current=S,z.current?.(),z.current=null,B.current=!1,_(!1),!S))return;let N=x.current;if(!N)return;let J=$.current,he=J?.rtpTimestamp??null,xe=!1,M=()=>{xe||(xe=!0,re.current?.())};J&&he==null&&M();let Ue=J!=null&&he!=null,Ge=Me=>{z.current?.(),z.current=null,B.current=!0,_(!0),H.current?.(),Me&&K.current?.()};if(typeof N.requestVideoFrameCallback=="function"){let Me=!1,V=0,F=(Se,ve)=>{if(!Me){if(Ue){let Re=ve?.rtpTimestamp;if(typeof Re!="number"){M(),Ge(!1);return}if(!bo(Re,he)){V=N.requestVideoFrameCallback(F);return}Ge(!0);return}Ge(!1)}};V=N.requestVideoFrameCallback(F),z.current=()=>{Me=!0,N.cancelVideoFrameCallback?.(V)};return}Ue&&M();let Ae=()=>{let Me=N.getVideoPlaybackQuality?.();(Me?Me.totalVideoFrames>0:N.readyState>=2&&N.videoWidth>0)&&Ge(!1)};N.addEventListener("loadeddata",Ae),N.addEventListener("timeupdate",Ae),N.addEventListener("playing",Ae),z.current=()=>{N.removeEventListener("loadeddata",Ae),N.removeEventListener("timeupdate",Ae),N.removeEventListener("playing",Ae)},Ae()},[]);(0,I.useEffect)(()=>()=>{z.current?.(),z.current=null},[]);let G=P==null?null:`${P.rtpTimestamp??""}|${P.ptsMs??""}`,Te=(0,I.useRef)(G);(0,I.useEffect)(()=>{if(Te.current===G||(Te.current=G,G==null))return;let S=ie.current;S&&W(S,!0)},[G,W]);let me=(0,I.useCallback)(()=>{if(typeof MediaStream>"u")return null;U.current||(U.current=new MediaStream);let S=x.current;return S&&S.srcObject!==U.current&&(S.srcObject=U.current),U.current},[]),ae=(0,I.useCallback)(S=>{let D=x.current;if(!D)return;let N=D.play();!N||typeof N.then!="function"||N.then(()=>{D.muted||oe(!0)}).catch(J=>{if((J instanceof Error?J.name:String(J))==="NotAllowedError"&&!D.muted){tn(`play() blocked pending a user gesture (${S})`),oe(!1);return}tn(`play() failed (${S})`,J)})},[oe]),Ve=(0,I.useCallback)(()=>{let S=x.current;S&&(me(),!S.muted&&(ae("gesture"),je(),oe(!0)))},[me,ae,oe]),ee=(0,I.useCallback)(S=>{let D=me();if(D){for(let N of D.getVideoTracks())N!==S&&D.removeTrack(N);if(S&&!D.getVideoTracks().includes(S)){D.addTrack(S);let N=x.current;N&&(N.srcObject=D)}S&&ae("track-attach"),E(S!==null),W(S),O.current?.(S)}},[me,ae,W]),ue=(0,I.useCallback)(S=>{let D=me();if(D){for(let N of D.getAudioTracks())N!==S&&D.removeTrack(N);S&&!D.getAudioTracks().includes(S)&&D.addTrack(S),S&&ae("audio-attach")}},[me,ae]),Z=(0,I.useCallback)(S=>{x.current=S,S&&(a?(S.muted=!0,S.defaultMuted=!0,S.setAttribute("muted",""),q.current=null):(S.muted=!1,S.defaultMuted=!1,S.removeAttribute("muted")),S.setAttribute("playsinline",""),S.setAttribute("webkit-playsinline",""),me())},[me,a]);(0,I.useImperativeHandle)(r,()=>({get element(){return x.current},get live(){return U.current?U.current.getVideoTracks().length>0:!1},get framed(){return B.current},unlock:Ve,get unlocked(){return q.current===!0}}),[Ve]);let ce=(0,on.derivedLegRole)(n)!==void 0;(0,I.useEffect)(()=>{ce&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[ce,n]);let le=i!==void 0;return(0,I.useEffect)(()=>{if(le){ee(i??null);return}if(ce){ee(null);return}if(!T)return;let S=rn(T,nn(n,"video")),D=()=>{let M=U.current;return M?M.getVideoTracks()[0]??null:null},N=M=>{if(M!==D()&&(ee(M),M)){let Ue=()=>{D()===M&&ee(null)};M.addEventListener("ended",Ue)}},J=S.track;J&&J.readyState==="live"&&N(J);let he=S.on("track",M=>{M&&M.readyState!=="live"||N(M)}),xe=setInterval(()=>{let M=S.track;M&&M.readyState==="live"&&N(M)},en);return()=>{he(),clearInterval(xe)}},[T,n,ce,le,i,ee]),(0,I.useEffect)(()=>{if(le||!T||s===!1||ce)return;let S=rn(T,nn(n,"audio",s)),D=()=>{let M=U.current;return M?M.getAudioTracks()[0]??null:null},N=M=>{if(M!==D()&&(ue(M),M)){let Ue=()=>{D()===M&&ue(null)};M.addEventListener("ended",Ue)}},J=S.track;J&&J.readyState==="live"&&N(J);let he=S.on("track",M=>{M&&M.readyState!=="live"||N(M)}),xe=setInterval(()=>{let M=S.track;M&&M.readyState==="live"&&N(M)},en);return()=>{he(),clearInterval(xe)}},[T,n,ce,s,le,ue]),(0,kt.jsxs)("div",{className:f,style:{position:"relative",width:"100%",height:"100%",...d},"data-urun-video":"","data-urun-video-live":p?"true":"false","data-urun-video-framed":v?"true":"false",children:[(0,kt.jsx)("video",{ref:Z,className:y,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...u?{transform:"scaleX(-1)"}:{}}}),p?null:b,k===void 0?null:(0,kt.jsx)("div",{"data-urun-video-poster":"","aria-hidden":v||void 0,style:{position:"absolute",inset:0,...v?{opacity:0,pointerEvents:"none"}:null},children:k}),l]})});var bt=require("react/jsx-runtime"),Ro={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},an=(0,pe.forwardRef)(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:u=!0,documentTarget:c,...f}=o??{},d=c!==void 0?c:typeof document<"u"?document:null,y=(0,pe.useRef)(null),b=(0,pe.useRef)(null),k=(0,pe.useRef)(0),l=(0,pe.useRef)(f);l.current=f;let g=(0,pe.useMemo)(()=>(0,sn.createCameraWarp)(l.current),[]);return(0,pe.useImperativeHandle)(r,()=>({get video(){return y.current},get canvas(){return b.current},warp:g,get lastDrawTs(){return k.current}}),[g]),(0,pe.useEffect)(()=>{if(!i)return;let m=0,P=0,R=null,w=C=>{typeof C.requestVideoFrameCallback=="function"&&(R=C,P=C.requestVideoFrameCallback(function T(){g.frameArrived(),P=C.requestVideoFrameCallback(T)}))},h=C=>{m=requestAnimationFrame(h);let T=b.current,x=y.current?.element??null;if(!T||!x||(x!==R&&(R&&P&&R.cancelVideoFrameCallback?.(P),w(x)),x.readyState<2))return;g.tick(C);let U=typeof devicePixelRatio=="number"?devicePixelRatio:1,p=Math.max(1,Math.round(T.clientWidth*U)),E=Math.max(1,Math.round(T.clientHeight*U));(T.width!==p||T.height!==E)&&(T.width=p,T.height=E);let v=T.getContext("2d");if(!v)return;let _=g.transform(),B=x.videoWidth||p,q=x.videoHeight||E,L=Math.max(p/B,E/q)*(1+a)*_.scale;v.setTransform(L,0,0,L,p/2+_.translateX*p,E/2+_.translateY*E),v.drawImage(x,-B/2,-q/2),k.current=C};return m=requestAnimationFrame(h),()=>{cancelAnimationFrame(m),R&&P&&R.cancelVideoFrameCallback?.(P)}},[i,a,g]),(0,pe.useEffect)(()=>{if(!i||!u||!d)return;let m=()=>!!d.pointerLockElement,P=T=>{m()&&g.keyDown(T.key)},R=T=>g.keyUp(T.key),w=T=>{m()&&g.pointerDelta(T.movementX,T.movementY)},h=()=>{m()||g.clearKeys()},C=()=>g.clearKeys();return d.addEventListener("keydown",P),d.addEventListener("keyup",R),d.addEventListener("mousemove",w),d.addEventListener("pointerlockchange",h),d.defaultView?.addEventListener("blur",C),()=>{d.removeEventListener("keydown",P),d.removeEventListener("keyup",R),d.removeEventListener("mousemove",w),d.removeEventListener("pointerlockchange",h),d.defaultView?.removeEventListener("blur",C)}},[i,u,d,g]),i?(0,bt.jsxs)(Ke,{ref:y,...s,videoClassName:s.videoClassName,style:{...s.style},children:[(0,bt.jsx)("canvas",{ref:b,style:Ro,"data-urun-warp":""}),n]}):(0,bt.jsx)(Ke,{ref:y,...s,children:n})});var un=new Map;function cn(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);un.set(e,{component:t,schema:r})}function ln(e,t){let r=un.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 $e=require("react/jsx-runtime");function dn({name:e,props:t,fallback:r}){let o=ln(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,$e.jsx)($e.Fragment,{children:r}):(0,$e.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,$e.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,$e.jsx)(n,{...o.validatedProps})}var nt=require("zod"),Xe=require("react/jsx-runtime"),pn=nt.z.object({step:nt.z.number().min(0),total:nt.z.number().min(1),label:nt.z.string().optional(),variant:nt.z.enum(["default","success","error"]).default("default")});function mr(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 mn(e){let{step:t,total:r,label:o,variant:n,percentage:s}=mr(e);return(0,Xe.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Xe.jsx)("div",{className:"urun-progress-label",children:o}),(0,Xe.jsx)("div",{className:"urun-progress-bar",children:(0,Xe.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Xe.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var Dt=require("zod"),Rt=require("react/jsx-runtime"),fn=Dt.z.object({state:Dt.z.enum(["thinking","generating","idle","error"]),message:Dt.z.string().optional()}),Co={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function fr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??Co[t]??t;return{state:t,message:n,isActive:o}}function gn(e){let{state:t,message:r,isActive:o}=fr(e);return(0,Rt.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,Rt.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,Rt.jsx)("span",{className:"urun-status-message",children:r})]})}var Ct=require("react"),Vt=require("zod"),Pt=require("react/jsx-runtime"),hn=Vt.z.object({text:Vt.z.string(),streaming:Vt.z.boolean().default(!1)});function gr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Sn(e){let{text:t,streaming:r}=gr(e),o=(0,Ct.useRef)(null),n=(0,Ct.useRef)(0);return(0,Ct.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,Pt.jsxs)("div",{className:"urun-text-stream",children:[(0,Pt.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,Pt.jsx)("span",{className:"urun-text-cursor"})]})}var Et=require("zod"),Tt=require("react/jsx-runtime"),vn=Et.z.object({src:Et.z.string().url(),alt:Et.z.string().optional(),caption:Et.z.string().optional()});function hr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function yn(e){let{src:t,alt:r,caption:o}=hr(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 Ie=require("zod"),ot=require("react/jsx-runtime"),kn=Ie.z.object({metrics:Ie.z.array(Ie.z.object({label:Ie.z.string(),value:Ie.z.union([Ie.z.string(),Ie.z.number()]),unit:Ie.z.string().optional()}))});function Sr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function bn(e){let{metrics:t}=Sr(e);return(0,ot.jsx)("div",{className:"urun-metrics-panel",children:t.map((r,o)=>(0,ot.jsxs)("div",{className:"urun-metric-card",children:[(0,ot.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,ot.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var Rn=require("react");var Pn=require("react/jsx-runtime"),Cn=(0,Rn.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,Pn.jsx)(Ke,{ref:r,stream:o,...n})});var X=require("react"),Tn=require("@urun-sh/core");var xn=require("react/jsx-runtime"),Po=1e3,En=200;function vr(...e){console.debug("[audio]",...e)}var wt=(0,X.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=we(),y=o??d,b=(0,X.useRef)(null),k=(0,X.useRef)(null),l=(0,X.useRef)(null),g=(0,X.useRef)(null),m=(0,X.useRef)(u);m.current=u;let P=(0,X.useRef)(c);P.current=c;let R=(0,X.useCallback)(p=>{l.current!==p&&(l.current=p,P.current?.(p))},[]),w=(0,X.useCallback)(()=>{if(typeof MediaStream>"u")return null;k.current||(k.current=new MediaStream);let p=b.current;return p&&p.srcObject!==k.current&&(p.srcObject=k.current),k.current},[]),h=(0,X.useCallback)(p=>{let E=b.current;if(!E)return;let v=E.play();!v||typeof v.then!="function"||v.then(()=>{E.muted||R(!0)}).catch(_=>{let B=_ instanceof Error?_.name:String(_);if(B==="AbortError"){vr(`play() aborted (${p}); retrying in ${En}ms`),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{g.current=null,h(`${p}:retry`)},En);return}if(B==="NotAllowedError"){vr(`play() blocked pending a user gesture (${p})`),R(!1);return}vr(`play() failed (${p})`,_)})},[R]),C=(0,X.useCallback)(p=>{let E=w();if(E){for(let v of E.getAudioTracks())v!==p&&E.removeTrack(v);p&&!E.getAudioTracks().includes(p)&&E.addTrack(p),p&&h("track-attach"),m.current?.(p)}},[w,h]),T=(0,X.useCallback)(()=>{let p=b.current;p&&(w(),p.muted=!1,h("gesture"),je(),R(!0))},[w,h,R]);(0,X.useImperativeHandle)(r,()=>({unlock:T,get unlocked(){return l.current===!0},get element(){return b.current}}),[T]);let x=(0,X.useCallback)(p=>{b.current=p,p&&(p.setAttribute("playsinline",""),p.setAttribute("webkit-playsinline",""),w()),f?.(p)},[w,f]),U=s!==void 0;return(0,X.useEffect)(()=>{if(U){C(s??null);return}if(!y)return;let p=y.stream(n),E=()=>{let O=k.current;return O?O.getAudioTracks()[0]??null:null},v=O=>{if(O!==E()&&(C(O),O)){let L=()=>{E()===O&&C(null)};O.addEventListener("ended",L)}},_=p.track;_&&_.readyState==="live"&&v(_);let B=p.on("track",O=>{O&&O.readyState!=="live"||v(O)}),q=setInterval(()=>{let O=p.track;O&&O.readyState==="live"&&v(O)},Po);return()=>{B(),clearInterval(q)}},[y,n,U,s,C]),(0,X.useEffect)(()=>(0,Tn.observePageLifecycle)(()=>{je(),l.current===!0&&h("foreground")}),[h]),(0,X.useEffect)(()=>()=>{g.current&&clearTimeout(g.current)},[]),(0,xn.jsx)("audio",{ref:x,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),wn=wt;var j=require("react"),st=require("@urun-sh/core");var An=require("react/jsx-runtime"),yr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Ft(...e){console.debug("[voice]",...e)}var xt=(0,j.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=yr,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:f,onError:d,onMicStream:y,onTrack:b,onUnlockChange:k,capture:l}=t,g=we(),m=o??g,P=(0,j.useRef)(null),R=(0,j.useRef)(null),w=(0,j.useRef)(null),h=(0,j.useRef)([]),C=(0,j.useRef)(!1),T=(0,j.useRef)(f);T.current=f;let x=(0,j.useRef)(d);x.current=d;let U=(0,j.useRef)(y);U.current=y;let p=(0,j.useCallback)(L=>{C.current!==L&&(C.current=L,T.current?.(L))},[]),E=(0,j.useCallback)(()=>{for(let L of h.current)L();h.current=[],w.current?.release(),w.current=null,R.current&&(R.current=null,U.current?.(null))},[]),v=(0,j.useCallback)(async()=>{let L=w.current;if(L){let $=await L.update(i);return R.current=L.stream,U.current?.(L.stream),$}let K=await(l??(0,st.sharedCaptureController)()).claim("audio",i);w.current=K,h.current=[K.onTrack(($,oe)=>{R.current=oe,U.current?.(oe),C.current&&m?.stream(n).attach($).catch(ie=>Ft("mic re-attach after one-capture re-acquire failed",ie))}),K.onLost($=>{w.current=null,h.current=[],R.current=null,U.current?.(null),p(!1),x.current?.($)})],R.current=K.stream,U.current?.(K.stream);let re=K.track;if(!re)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return re},[l,i,m,n,p]),_=(0,j.useCallback)(async()=>{E(),p(!1),await m?.stream(n).detach().catch(()=>{})},[m,n,E,p]),B=(0,j.useCallback)(async()=>{if(!m)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");P.current?.unlock();let L;try{L=await v()}catch(re){E();let $=(0,st.sessionFailureFromMediaError)(re,m.status);throw x.current?.($),$}m.connect?.();let H;for(let re=1;re<=u;re++)try{await m.whenLive(a!==void 0?{timeout:a}:void 0),await m.stream(n).attach(L),p(!0);return}catch($){H=$,Ft(`start attempt ${re}/${u} failed`,$),re<u&&await new Promise(oe=>setTimeout(oe,c))}E(),p(!1);let K=H instanceof Error?H:new Error(String(H??"voice start failed"));throw x.current?.(K),K},[m,n,a,u,c,v,E,p]);(0,j.useImperativeHandle)(r,()=>({start:B,stop:_,unlock:()=>P.current?.unlock(),get active(){return C.current},get micStream(){return R.current},get audio(){return P.current}}),[B,_]);let q=(0,j.useRef)(!1),O=(0,j.useCallback)(async()=>{if(!m||!C.current||q.current)return;let L=R.current?.getAudioTracks()[0]??null;if(L&&L.readyState==="live"){try{await m.stream(n).attach(L)}catch(H){Ft("foreground mic re-assert failed (will retry on next pass)",H)}return}q.current=!0;try{let H=await v();await m.stream(n).attach(H)}catch(H){let K=H instanceof Error?H:new Error(String(H));Ft("foreground mic re-acquire failed",K),x.current?.(K)}finally{q.current=!1}},[m,n,v]);return(0,j.useEffect)(()=>{let L=()=>{O()};return m&&typeof m.onRecovery=="function"?m.onRecovery(L):(0,st.observePageLifecycle)(L)},[m,O]),(0,j.useEffect)(()=>E,[E]),s?(0,An.jsx)(wt,{ref:P,session:m,stream:n,onTrack:b,onUnlockChange:k}):null}),Un=xt;var Pe=require("react");var qt=require("react");var kr={level:0,speaking:!1};function Ht(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,qt.useState)(kr);return(0,qt.useEffect)(()=>{if(!e){i(kr);return}let a=vt();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),b=setInterval(()=>{f.getByteTimeDomainData(d);let k=0;for(let g=0;g<d.length;g++){let m=(d[g]-128)/128;k+=m*m}let l=Math.sqrt(k/d.length);i(g=>{let m=l>n;return Math.abs(g.level-l)<.005&&g.speaking===m?g:{level:l,speaking:m}})},o);return()=>{clearInterval(b),c.disconnect(),i(kr)}},[e,r,o,n]),s}var Le=require("react/jsx-runtime"),Eo={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},To={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Mn=(0,Pe.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:y}=t,b=we(),k=o??b,l=(0,Pe.useRef)(null),[g,m]=(0,Pe.useState)(null),P=(0,Pe.useRef)(d);P.current=d;let{level:R,speaking:w}=Ht(a?g:null);return(0,Pe.useImperativeHandle)(r,()=>({start:()=>{let h=l.current;return h?h.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>l.current?.stop()??Promise.resolve(),get active(){return l.current?.active??!1},get micStream(){return l.current?.micStream??null}}),[]),(0,Pe.useEffect)(()=>{!i||!k||l.current?.start().catch(()=>{})},[i,k]),(0,Le.jsxs)(Le.Fragment,{children:[(0,Le.jsx)(xt,{ref:l,session:k,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...y!==void 0?{capture:y}:{},onActiveChange:c,onError:f,onMicStream:h=>{m(h),P.current?.(h)}}),a?(0,Le.jsx)("span",{className:u,style:Eo,"data-urun-mic":"","data-urun-mic-active":g?"true":"false","data-urun-mic-speaking":w?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(R*100)/100,children:(0,Le.jsx)("span",{style:To,children:(0,Le.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(R*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var it=require("@urun-sh/core"),A=require("react");var ye=require("react/jsx-runtime"),Rr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function br(...e){console.debug("[camera]",...e)}function wo(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function xo(){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 Cr=(0,A.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:y=!1,className:b,videoClassName:k,onActiveChange:l,onError:g,onStream:m,onTrack:P,children:R,capture:w,flipControl:h="auto",flipControlClassName:C,onDevices:T}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let x=i?"user":a?"environment":u??"environment",U=we(),p=o??U,E=(0,A.useRef)(null),v=(0,A.useRef)(null),_=(0,A.useRef)(null),B=(0,A.useRef)([]),q=(0,A.useRef)(null),O=(0,A.useRef)(!1),L=(0,A.useRef)(!1),H=(0,A.useRef)(x),[K,re]=(0,A.useState)(x),[$,oe]=(0,A.useState)(!1),[ie,z]=(0,A.useState)(null),[W,G]=(0,A.useState)(!1),[Te]=(0,A.useState)(wo),me=(0,A.useRef)(l);me.current=l;let ae=(0,A.useRef)(g);ae.current=g;let Ve=(0,A.useRef)(m);Ve.current=m;let ee=(0,A.useRef)(P);ee.current=P;let ue=(0,A.useRef)(T);ue.current=T;let Z=(0,A.useCallback)(V=>{O.current!==V&&(O.current=V,oe(V),me.current?.(V))},[]);(0,A.useEffect)(()=>{if(!$){z(null);return}let V=!1,F=()=>{xo().then(ve=>{V||(z(ve),ve&&ue.current?.(ve))})};F();let Se=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof Se?.addEventListener=="function"?(Se.addEventListener("devicechange",F),()=>{V=!0,Se.removeEventListener?.("devicechange",F)}):()=>{V=!0}},[$]);let ce=(0,A.useCallback)(V=>{let F=E.current;F&&(F.muted=!0,F.defaultMuted=!0,F.setAttribute("muted",""),F.setAttribute("playsinline",""),F.setAttribute("webkit-playsinline",""),F.srcObject=V,V&&F.play()?.catch?.(Se=>br("preview play() failed",Se)))},[]),le=(0,A.useCallback)(()=>{L.current=!1,q.current?.(),q.current=null;for(let V of B.current)V();B.current=[],_.current?.release(),_.current=null,v.current&&(v.current=null,Ve.current?.(null),ee.current?.(null)),ce(null)},[ce]),S=(0,A.useCallback)((V,F)=>{q.current?.(),v.current=F,ce(F),Ve.current?.(F);let Se=()=>{v.current===F&&(br("camera track ended (device removed or permission revoked)"),le(),Z(!1))};V.addEventListener("ended",Se),q.current=()=>V.removeEventListener("ended",Se)},[ce,le,Z]),D=(0,A.useCallback)(async V=>{let F=n!==!1;if(F&&!p)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let Se={...Rr,...s,facingMode:V},ve;try{let Re=_.current;if(Re)ve=await Re.update(Se);else{let mt=await(w??(0,it.sharedCaptureController)()).claim("video",Se);if(_.current=mt,B.current=[mt.onTrack((ft,eo)=>{S(ft,eo),O.current&&(!F||!p||p.stream(n).attachVideo(ft).then(()=>ee.current?.(ft)).catch(to=>br("camera re-publish after one-capture re-acquire failed",to)))}),mt.onLost(ft=>{_.current=null,B.current=[],le(),Z(!1),ae.current?.(ft)})],!mt.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ve=mt.track}}catch(Re){let Ye=(0,it.sessionFailureFromMediaError)(Re,p?.status);throw ae.current?.(Ye),Ye}H.current=V,re(V),S(ve,_.current?.stream??new MediaStream([ve]));try{F&&p&&(p.connect?.(),await p.whenLive(d!==void 0?{timeout:d}:void 0),await p.stream(n).attachVideo(ve)),L.current=F?n:!1}catch(Re){le(),Z(!1);let Ye=Re instanceof Error?Re:new Error(String(Re));throw ae.current?.(Ye),Ye}ee.current?.(ve),Z(!0)},[p,n,s,d,w,S,le,Z]),N=(0,A.useCallback)(V=>D(V?.facingMode??H.current),[D]),J=(0,A.useCallback)(async V=>{let F=L.current===n;O.current&&H.current===V&&F||await D(V)},[D,n]),he=(0,A.useCallback)(()=>D(H.current==="environment"?"user":"environment"),[D]),xe=(0,A.useCallback)(async()=>{le(),Z(!1),n!==!1&&await p?.stream(n).detachVideo().catch(()=>{})},[p,n,le,Z]),M=(0,A.useCallback)(async V=>{let F=E.current;if(!F)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await(0,it.captureStillFromVideo)(F,V)},[]);(0,A.useImperativeHandle)(r,()=>({start:N,stop:xe,flip:he,setFacingMode:J,capturePhoto:M,get active(){return O.current},get facingMode(){return H.current},get stream(){return v.current},get element(){return E.current}}),[N,xe,he,J,M]);let Ue=(0,A.useRef)(J);if(Ue.current=J,(0,A.useEffect)(()=>{c&&(n!==!1&&!p||Ue.current(x).catch(()=>{}))},[c,p,x,n]),(0,A.useEffect)(()=>le,[le]),!y)return null;let Ge=f==="auto"?K==="user":f,Ae=$&&(h===!0||h==="auto"&&Te&&(ie?.length??0)>1),Me=()=>{W||(G(!0),he().catch(()=>{}).finally(()=>G(!1)))};return(0,ye.jsxs)("div",{className:b,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":K,children:[(0,ye.jsx)("video",{ref:E,className:k,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Ge?{transform:"scaleX(-1)"}:{}}}),Ae?(0,ye.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Me,disabled:W,className:C,style:C?{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:(0,ye.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,ye.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,ye.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,ye.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,ye.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,ye.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,R]})}),_n=(0,A.forwardRef)(function({preview:t=!0,...r},o){return(0,ye.jsx)(Cr,{ref:o,...r,visible:t,autoStart:!1})});var at=require("@urun-sh/core"),te=require("react");function Nn(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=(0,te.useState)(null),[a,u]=(0,te.useState)(null),[c,f]=(0,te.useState)(!1),[d,y]=(0,te.useState)(null),[b]=(0,te.useState)(at.cameraCaptureAvailable),k=(0,te.useRef)(n);k.current=n;let l=(0,te.useRef)(null),g=(0,te.useRef)(0),m=(0,te.useCallback)(C=>{l.current&&URL.revokeObjectURL(l.current),l.current=C?URL.createObjectURL(new Blob([C.bytes],{type:C.type})):null,u(l.current),i(C),k.current?.(C)},[]);(0,te.useEffect)(()=>()=>{g.current++,l.current&&URL.revokeObjectURL(l.current),l.current=null},[]);let P=(0,te.useCallback)(async C=>{let T=++g.current;f(!0),y(null);try{let x=await C();if(g.current!==T)return;m(x)}catch(x){if(g.current!==T)return;y((0,at.referenceImageErrorMessage)(x))}finally{g.current===T&&f(!1)}},[m]),R=(0,te.useCallback)(C=>P(()=>(0,at.normalizeReferenceImage)(C,{maxSize:t,type:r,quality:o,source:"file"})),[P,t,r,o]),w=(0,te.useCallback)(C=>P(()=>C.capturePhoto({maxSize:t,type:r,quality:o})),[P,t,r,o]),h=(0,te.useCallback)(()=>{g.current++,y(null),f(!1),m(null)},[m]);return{reference:s,previewUrl:a,pick:R,capture:w,clear:h,busy:c,error:d,cameraAvailable:b}}var Wt=require("react");function In(e,t){let[r,o]=(0,Wt.useState)(null);return(0,Wt.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var Dn=require("react");var jt=require("react");var Ln=require("zustand/vanilla"),On=require("zustand"),Uo=()=>{};function Bt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=(0,Ln.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):Uo,u=(c=>(0,On.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 ut(e,t){let r=(0,jt.useMemo)(()=>Bt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,jt.useEffect)(()=>r.bind(),[r]),r}function Vn(e,t,r){let n=ut(e,t)(r??(a=>a)),s=(0,Dn.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 $t=require("react");var Fe=200;function Oe(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function ct(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Kt(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 Xt(e,t,r={}){let o=r.cap??200,[n,s]=(0,$t.useState)([]);return(0,$t.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=>Oe(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}var Ee=require("react/jsx-runtime");function Fn({session:e,name:t,cap:r,className:o}){let n=Xt(e,t,{cap:r});return(0,Ee.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,Ee.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,Ee.jsx)("code",{children:t}),(0,Ee.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,Ee.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,Ee.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,Ee.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,i)=>(0,Ee.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,Ee.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",ct(s.payload)]},`${s.at}-${i}`))})]})}var Ut=require("react");var ge=require("react/jsx-runtime");function At({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=Kt(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return(0,ge.jsxs)("div",{className:"urun-doc-patch",children:[(0,ge.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),(0,ge.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,ge.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?(0,ge.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function qn({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=ut(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return(0,ge.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,ge.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,ge.jsx)("code",{children:t}),(0,ge.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,ge.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,ge.jsx)(At,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}var zt=require("react");var De=require("react/jsx-runtime");function Hn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Wn({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=(0,zt.useState)([]);return(0,zt.useEffect)(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>Oe(u,{at:Date.now(),direction:"in",text:Hn(ct(a))},r))}):void 0),[e,t,r]),(0,De.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,De.jsx)(At,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>Oe(u,{at:Date.now(),direction:"out",text:Hn(a)},r))}}),(0,De.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,De.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>(0,De.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,De.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,De.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}var Jt=require("react");var ze=require("react/jsx-runtime");function Bn({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=(0,Jt.useState)([]),a=t.join(","),u=r.join(",");return(0,Jt.useEffect)(()=>{if(i([]),!e)return;let c=(d,y)=>i(b=>Oe(b,{at:Date.now(),kind:d,text:y},o)),f=[];f.push(e.onPhase(d=>c("phase",`phase \u2192 ${d.name}`)));for(let d of t){let y=e.stream(d);f.push(y.on("track",b=>c("track",`${d}: ${b?"track arrived":"track ended"}`)))}for(let d of r){let y=e.doc(d);f.push(y.on("change",()=>c("doc",`${d} changed`)))}return()=>f.forEach(d=>d())},[e,a,u,o]),(0,ze.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,ze.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,ze.jsxs)("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[(0,ze.jsx)("span",{className:"urun-event-spine-kind",children:c.kind})," ",(0,ze.jsx)("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${f}`))})}var rr=require("@urun-sh/core");var Gt=require("react");function ke(e){let[t,r]=(0,Gt.useState)(e?.phase??null);return(0,Gt.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var Kn=require("@urun-sh/core");var lt=require("react"),jn=require("@urun-sh/core");function Yt(e){let t=ke(e),r=(0,jn.isWakingPhase)(t?.name),o=(0,lt.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,lt.useState)(s);return(0,lt.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 qe=require("react/jsx-runtime");function Zt({session:e,render:t,className:r}){let o=Yt(e);return!o.waking||!o.phase?null:(0,qe.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,qe.jsxs)(qe.Fragment,{children:[(0,qe.jsx)("span",{className:"urun-session-waking-label",children:(0,Kn.describeSessionPhase)(o.phase)})," ",(0,qe.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var er=require("react");var He=require("react"),Ao={event:null,elapsedMs:0};function Qt(e,t){let[r,o]=(0,He.useState)(null),n=(0,He.useRef)(0);(0,He.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,He.useState)(0);return(0,He.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}:Ao}var dt=require("react/jsx-runtime"),Mo={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 _o(e){let[t,r]=(0,er.useState)(!1);return(0,er.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 tr({session:e,stream:t,videoElement:r,render:o,className:n}){let s=Qt(e,t),i=_o(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return(0,dt.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):(0,dt.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,dt.jsx)("span",{className:"urun-activation-overlay-copy",children:a.hint??Mo[u]})," ",(0,dt.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var be=require("react/jsx-runtime"),No={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function $n({session:e,className:t}){let r=ke(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,be.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,be.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,be.jsx)("span",{className:"urun-session-status-label",children:No[o]}),n?(0,be.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function Xn({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=ke(e);if(s?.name==="live")return(0,be.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,be.jsx)(tr,{session:e})]});let i=r?r(s):(0,be.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&(0,rr.isWakingPhase)(s.name)?(0,be.jsx)(Zt,{session:e}):s&&s.name!=="idle"?(0,rr.describeSessionPhase)(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return(0,be.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,be.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var nr=require("react");var Jn=require("react/jsx-runtime");function Pr(e){return ke(e)?.endsAt??null}function Io(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 zn({session:e,urgentMs:t=6e4,className:r}){let n=Pr(e)?.getTime()??null,[s,i]=(0,nr.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,nr.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=Io(s);return(0,Jn.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 Mt=require("react/jsx-runtime"),Lo=new Set(["expired","ended","error"]);function Gn({session:e,onNewSession:t,children:r,className:o}){let n=ke(e);if(!n||!Lo.has(n.name))return null;let s=r?r(n):(0,Mt.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,Mt.jsxs)("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?(0,Mt.jsx)("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}var We=require("react"),Je=require("react/jsx-runtime");function Er(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 Tr(e){let t=(0,We.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,We.useState)(()=>t?Er(t.get("idle")):null);return(0,We.useEffect)(()=>{if(!t){o(null);return}return o(Er(t.get("idle"))),t.on("change",()=>o(Er(t.get("idle"))))},[t]),r}function Oo(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Yn({session:e,onStillHere:t,className:r}){let o=Tr(e),n=o?.deadlineEpochS??null,[s,i]=(0,We.useState)(null);if((0,We.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,Je.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,Je.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,Je.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,Je.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Oo(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,Je.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var pt=require("react"),Zn=require("@urun-sh/core");function Qn(e){let t=(0,pt.useContext)(Qe),[r,o]=(0,pt.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,pt.useEffect)(()=>{if(!a||!u||!n||!s)return;let y=!1,b=()=>{(0,Zn.prewake)({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:f,authProvider:d}).then(l=>{y||o(l)}).catch(()=>{})};b();let k=setInterval(b,Math.max(1,i)*1e3);return()=>{y=!0,clearInterval(k)}},[n,s,i,a,u,c,f,d]),r}var or=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,ReprojectedVideo,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,useReferenceImage,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 ht,b as an,c as St}from"./chunk-WF2OBDSX.mjs";import{useCallback as nr,useEffect as yn,useMemo as kn,useRef as or,useState as kt}from"react";import{Component as un}from"react";import{jsx as Zt,jsxs as cn}from"react/jsx-runtime";var Fe=class extends un{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||cn("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:[Zt("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),Zt("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as ln}from"react";var we=ln(null);function me(e){return e&&e.trim()?e.trim():void 0}function ue(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return me(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return me(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return me(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return me(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return me(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return me(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return me(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return me(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return me(typeof process<"u"?process.env?.[e]:void 0)}}function Ge(){let e=ue("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||ue("VERCEL_ENV")==="production"?"workos":ue("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function dn(){return Ge()==="workos"}import{useEffect as pn,useRef as mn}from"react";var fn="urun.operator_token",er=null,Qt="op",gn="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function tr(){return typeof window<"u"}function rr(){return er}function hn(){if(!tr())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(Qt);if(!r)return null;er=r,t.delete(Qt);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Sn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function vt(e){let t=mn(e);t.current=e,pn(()=>{if(!tr())return;hn();let r=o=>{if(!Sn(o))return;let n=rr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as vn}from"react";function yt(e=!0){vn(()=>{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 Tn}from"react/jsx-runtime";var bn="/api/urun-token",Rn=1e4;function Cn(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 sr(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 ir(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function En(e,t){return typeof e=="function"?e(t):e!==void 0?e:Tn("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:g=!1,fallback:l,errorFallback:v,children:C}){let h=n===void 0&&t===void 0;if(!h&&(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(!h&&(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(h&&(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">.`);yt(g);let[m,f]=kt(),[P,E]=kt(null),U=or(void 0),S=or(null),[k,x]=kt(null);vt(G=>x({jwt:G}));let T=St(),L=ue("NEXT_PUBLIC_SESSION_TOKEN")??ue("NEXT_PUBLIC_URUN_JWT"),d=Ge(),b=k!==null,R=d==="workos"&&!n&&!b&&!h,M=n??(d==="jwt"?L:void 0)??m?.token,O=b?k.jwt:M,j=s??ue("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),I=R&&!O&&!T?.getAccessToken,_=t??m?.orgId,D=e??m?.gatewayUrl,B=h&&m===void 0,W=h&&m!==void 0&&!D?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,H=I?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,X=P??W??H,Y=ir("NEXT_PUBLIC_URUN_TOKEN_URL",ue("NEXT_PUBLIC_URUN_TOKEN_URL"))??u??bn,z=ir("NEXT_PUBLIC_URUN_EVENTS_URL",ue("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,q=nr(async G=>{if(!G?.forceRefresh){let N=U.current;if(!N)return N;let w=Cn(N);if(w===null||w-Date.now()>Rn)return N}return(await(S.current??(S.current=(async()=>{try{let N=await sr(Y);return U.current=N.token,f(N),N}finally{S.current=null}})()))).token},[Y]),K=nr(async()=>O,[O]),ee=typeof O=="string"&&O.trim().length>0,ke=R?T?.getAccessToken:h&&!b?q:ee?K:void 0,Q=kn(()=>({appId:p,baseUrl:D??"",orgId:_??"",jwt:O,getAccessToken:R?T?.getAccessToken:h&&!b?q:void 0,authProvider:j,eventsUrl:z,sessionKey:a,releaseOnLeave:c,priority:b?"preempt":void 0}),[p,T,D,j,O,z,_,a,c,R,b,h,q]);return yn(()=>{if(!h)return;let G=new AbortController;return E(null),(async()=>{try{let y=await sr(Y,G.signal);U.current=y.token,f(y)}catch(y){if(G.signal.aborted)return;E(y instanceof Error?y:new Error(String(y)))}})(),()=>G.abort()},[h,Y]),xe(Fe,{fallback:l,children:X?En(v,X):B?xe("div",{role:"status","aria-live":"polite",children:"Signing in..."}):xe(we.Provider,{value:Q,children:ke?xe(ht,{getAccessToken:ke,children:C}):C})})}import{useContext as wn,useEffect as xn,useMemo as ar,useReducer as Un,useRef as bt}from"react";import{App as An}from"@urun-sh/core";function Mn(e,t){return`${e}:${JSON.stringify(t??{})}`}function _n(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 be=new Map;var Rt=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()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}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()}},Et=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 Rt(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 Nn(){let e=wn(we);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=Un(i=>i+1,0),r=bt(new Map),o=bt(new Map),n=bt(null),s=ar(()=>An(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 xn(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=be.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 g=be.get(u);g===c&&(g.handle.removeNotifier(t),g.refCount=Math.max(0,g.refCount-1),a.set(u,g),g.refCount===0&&(g.disposeTimer=setTimeout(()=>{let l=be.get(u);!l||l.refCount!==0||(be.delete(u),l.handle.disconnect())},0)))}n.current=a}},[]),ar(()=>{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 g=l=>{let v=Mn(u,l),C=r.current.get(v);if(C&&!C.disposed)return C;let h=_n(e,u,l),p=be.get(h);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),be.delete(h),o.current.get(h)===p&&o.current.delete(h),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new Et(s[u](l),t,e.eventsUrl),refCount:0,disposeTimer:null},be.set(h,p)),o.current.get(h)!==p&&(o.current.set(h,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(v,p.handle),p.handle};return i.set(u,g),g}})},[e,s])}import{useCallback as Pt,useEffect as In,useMemo as Ln,useRef as Ye,useState as Tt}from"react";function Ue(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 On(e){return e instanceof Error?e:new Error(String(e))}function Dn(e,t){let r=Ln(()=>Ue(e),[e]),[o,n]=Tt(void 0),[s,i]=Tt(null),[a,u]=Tt(!1),c=Ye(t);c.current=t;let g=Ye(0),l=Ye(null),v=Ye(!0);In(()=>(v.current=!0,()=>{v.current=!1,l.current?.abort()}),[]);let C=Pt(async m=>{l.current?.abort();let f=new AbortController;l.current=f;let P=++g.current,E=()=>v.current&&g.current===P;E()&&(u(!0),i(null));try{let U=await r.request(m,{...c.current,signal:f.signal});return E()&&(n(U),u(!1),c.current?.onSuccess?.(U)),U}catch(U){let S=On(U);throw E()&&(i(S),u(!1),c.current?.onError?.(S)),S}},[r]),h=Pt(m=>{C(m).catch(()=>{})},[C]),p=Pt(()=>{g.current++,l.current?.abort(),l.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:h,mutateAsync:C,data:o,error:s,isPending:a,reset:p}}import{useCallback as ur,useEffect as Vn,useMemo as Fn,useRef as Ze,useState as wt}from"react";function cr(e){return e instanceof Error?e:new Error(String(e))}var qn=e=>typeof e=="string"?e:String(e);function Hn(e,t){let r=Fn(()=>Ue(e),[e]),[o,n]=wt(""),[s,i]=wt(!1),[a,u]=wt(null),c=Ze(t);c.current=t;let g=Ze(0),l=Ze(null),v=Ze(!0);Vn(()=>(v.current=!0,()=>{v.current=!1,l.current?.cancel(),l.current=null}),[]);let C=ur(()=>{g.current++,l.current?.cancel(),l.current=null,v.current&&i(!1)},[]),h=ur(async p=>{l.current?.cancel();let m=++g.current,f=()=>v.current&&g.current===m,P=c.current,E=P?.parseChunk??qn,U=P?.buildPayload??(R=>({prompt:R}));f()&&(n(""),u(null),i(!0));let{parseChunk:S,buildPayload:k,onFinish:x,onError:T,...L}=P??{},d="",b;try{b=r.requestStream(U(p),L),l.current=b}catch(R){let M=cr(R);f()&&(u(M),i(!1),P?.onError?.(M));return}try{for await(let R of b){if(g.current!==m)break;d+=E(R),f()&&n(d)}f()&&(i(!1),P?.onFinish?.(d))}catch(R){let M=cr(R);f()&&(u(M),i(!1),P?.onError?.(M))}finally{l.current===b&&(l.current=null)}},[r]);return{completion:o,complete:h,stop:C,isStreaming:s,error:a}}import{useCallback as lr,useEffect as Wn,useMemo as Bn,useRef as Ae,useState as Qe}from"react";function dr(e){return e instanceof Error?e:new Error(String(e))}var jn=e=>typeof e=="string"?e:String(e),pr=0;function xt(e){return pr+=1,`${e}-${pr}`}function Kn(e,t){let r=Bn(()=>Ue(e),[e]),[o,n]=Qe(()=>(t?.initialMessages??[]).map(E=>({id:E.id??xt("msg"),role:E.role,content:E.content}))),[s,i]=Qe(""),[a,u]=Qe(!1),[c,g]=Qe(null),l=Ae(t);l.current=t;let v=Ae(o);v.current=o;let C=Ae(s);C.current=s;let h=Ae(0),p=Ae(null),m=Ae(!0);Wn(()=>(m.current=!0,()=>{m.current=!1,p.current?.cancel(),p.current=null}),[]);let f=lr(()=>{h.current++,p.current?.cancel(),p.current=null,m.current&&u(!1)},[]),P=lr(async E=>{let U=E===void 0,S=(U?C.current:E)??"";if(!S.trim())return;p.current?.cancel();let x=++h.current,T=()=>m.current&&h.current===x,L=l.current,d=L?.parseChunk??jn,b={id:xt("msg"),role:"user",content:S},R={id:xt("msg"),role:"assistant",content:""},M=[...v.current,b].map(q=>({role:q.role,content:q.content})),O=[...v.current,b,R];v.current=O,n(O),U&&i(""),g(null),u(!0);let j=L?.buildPayload??(q=>({messages:q})),{initialMessages:I,parseChunk:_,buildPayload:D,onFinish:B,onError:W,...H}=L??{},X=q=>{n(K=>K.map(ee=>ee.id===R.id?{...ee,content:q}:ee))},Y="",z;try{z=r.requestStream(j(M),H),p.current=z}catch(q){let K=dr(q);T()&&(g(K),u(!1),L?.onError?.(K));return}try{for await(let q of z){if(h.current!==x)break;Y+=d(q),T()&&X(Y)}T()&&(u(!1),L?.onFinish?.({...R,content:Y}))}catch(q){let K=dr(q);T()&&(g(K),u(!1),L?.onError?.(K))}finally{p.current===z&&(p.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:P,stop:f,isStreaming:a,error:c}}import{useCallback as he,useEffect as mr,useMemo as $n,useRef as fr,useState as gr}from"react";import{createInputPresencePublisher as Xn,INPUT_PRESENCE_DEFAULT_HZ as zn,INPUT_PRESENCE_FIELD as Jn}from"@urun-sh/core";var Ut=[];function Gn(e,t={}){let{field:r=Jn,hz:o=zn}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=$n(()=>s?Xn({awareness:{setLocalStateField:(S,k)=>s.setField(S,k)},field:r,hz:o}):null,[s,r,o]),a=fr(null);a.current=i;let[u,c]=gr(!1),[g,l]=gr(Ut),v=fr(!1);mr(()=>{if(i)return()=>i.dispose()},[i]);let C=he(()=>{let S=a.current;l(S?S.heldKeys():Ut)},[]),h=he(()=>{a.current?.clear(),l(Ut)},[]);mr(()=>{if(!n)return;let S=()=>!!n.pointerLockElement,k=()=>{if(S()){v.current=!1,c(!0);return}v.current||(c(!1),h())},x=R=>{S()&&(a.current?.keyDown(R.key),C())},T=R=>{a.current?.keyUp(R.key),C()},L=R=>{S()&&a.current?.movePointer(R.movementX,R.movementY)},d=R=>{S()&&a.current?.setButtons(R.buttons)},b=()=>{h()};return n.addEventListener("pointerlockchange",k),n.addEventListener("keydown",x),n.addEventListener("keyup",T),n.addEventListener("mousemove",L),n.addEventListener("mousedown",d),n.addEventListener("mouseup",d),n.defaultView?.addEventListener("blur",b),()=>{n.removeEventListener("pointerlockchange",k),n.removeEventListener("keydown",x),n.removeEventListener("keyup",T),n.removeEventListener("mousemove",L),n.removeEventListener("mousedown",d),n.removeEventListener("mouseup",d),n.defaultView?.removeEventListener("blur",b)}},[n,h,C]);let p=he(S=>{S.requestPointerLock?.()},[]),m=he(()=>{v.current=!0,c(!0)},[]),f=he(()=>{v.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),h()},[n,h]),P=he(S=>{a.current?.keyDown(S),C()},[C]),E=he(S=>{a.current?.keyUp(S),C()},[C]),U=he((S,k)=>{a.current?.movePointer(S,k)},[]);return{engage:p,engageTouch:m,release:f,engaged:u,heldKeys:g,pressKey:P,releaseKey:E,movePointer:U}}import{forwardRef as ao,useEffect as Rr,useImperativeHandle as uo,useMemo as co,useRef as et}from"react";import{createCameraWarp as lo}from"@urun-sh/core";import{forwardRef as to,useCallback as Me,useEffect as qe,useImperativeHandle as ro,useRef as ne,useState as Sr}from"react";import{derivedLegRole as no}from"@urun-sh/core";import{createContext as Yn,useContext as hr}from"react";import{jsx as eo}from"react/jsx-runtime";var At=Yn(null);function Zn({session:e,children:t}){return eo(At.Provider,{value:e,children:t})}function ce(){return hr(At)}function Qn(){let e=hr(At);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{jsx as br,jsxs as io}from"react/jsx-runtime";function oo(e,t){return e-t>>>0<2147483648}var vr=1e3;function so(...e){console.debug("[video]",...e)}function yr(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(u=>u.on("track",()=>i(n())));return()=>{for(let u of a)u()}}}}function kr(e,t,r){return r?[r,t]:[e,t]}var _e=to(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:u=!1,objectFit:c="contain",className:g,style:l,videoClassName:v,placeholder:C,poster:h,children:p,onTrack:m,onFirstFrame:f,frameMarker:P,onFrameMarkerReached:E,onFrameMarkerUnsupported:U}=t,S=ce(),k=o??S,x=ne(null),T=ne(null),[L,d]=Sr(!1),[b,R]=Sr(!1),M=ne(!1),O=ne(m);O.current=m;let j=ne(f);j.current=f;let I=ne(E);I.current=E;let _=ne(U);_.current=U;let D=ne(P??null);D.current=P??null;let B=ne(null),W=ne(null),H=Me((y,N=!1)=>{if(!N&&y===B.current||(B.current=y,W.current?.(),W.current=null,M.current=!1,R(!1),!y))return;let w=x.current;if(!w)return;let $=D.current,J=$?.rtpTimestamp??null,se=!1,A=()=>{se||(se=!0,_.current?.())};$&&J==null&&A();let de=$!=null&&J!=null,pe=ie=>{W.current?.(),W.current=null,M.current=!0,R(!0),j.current?.(),ie&&I.current?.()};if(typeof w.requestVideoFrameCallback=="function"){let ie=!1,Pe=0,Oe=(Yt,gt)=>{if(!ie){if(de){let Je=gt?.rtpTimestamp;if(typeof Je!="number"){A(),pe(!1);return}if(!oo(Je,J)){Pe=w.requestVideoFrameCallback(Oe);return}pe(!0);return}pe(!1)}};Pe=w.requestVideoFrameCallback(Oe),W.current=()=>{ie=!0,w.cancelVideoFrameCallback?.(Pe)};return}de&&A();let te=()=>{let ie=w.getVideoPlaybackQuality?.();(ie?ie.totalVideoFrames>0:w.readyState>=2&&w.videoWidth>0)&&pe(!1)};w.addEventListener("loadeddata",te),w.addEventListener("timeupdate",te),w.addEventListener("playing",te),W.current=()=>{w.removeEventListener("loadeddata",te),w.removeEventListener("timeupdate",te),w.removeEventListener("playing",te)},te()},[]);qe(()=>()=>{W.current?.(),W.current=null},[]);let X=P==null?null:`${P.rtpTimestamp??""}|${P.ptsMs??""}`,Y=ne(X);qe(()=>{if(Y.current===X||(Y.current=X,X==null))return;let y=B.current;y&&H(y,!0)},[X,H]);let z=Me(()=>{if(typeof MediaStream>"u")return null;T.current||(T.current=new MediaStream);let y=x.current;return y&&y.srcObject!==T.current&&(y.srcObject=T.current),T.current},[]),q=Me(y=>{let N=x.current;if(!N)return;let w=N.play();!w||typeof w.catch!="function"||w.catch($=>so(`play() failed (${y})`,$))},[]),K=Me(y=>{let N=z();if(N){for(let w of N.getVideoTracks())w!==y&&N.removeTrack(w);if(y&&!N.getVideoTracks().includes(y)){N.addTrack(y);let w=x.current;w&&(w.srcObject=N)}y&&q("track-attach"),d(y!==null),H(y),O.current?.(y)}},[z,q,H]),ee=Me(y=>{let N=z();if(N){for(let w of N.getAudioTracks())w!==y&&N.removeTrack(w);y&&!N.getAudioTracks().includes(y)&&N.addTrack(y),y&&q("audio-attach")}},[z,q]),ke=Me(y=>{x.current=y,y&&(a&&(y.muted=!0,y.defaultMuted=!0,y.setAttribute("muted","")),y.setAttribute("playsinline",""),y.setAttribute("webkit-playsinline",""),z())},[z,a]);ro(r,()=>({get element(){return x.current},get live(){return T.current?T.current.getVideoTracks().length>0:!1},get framed(){return M.current}}),[]);let Q=no(n)!==void 0;qe(()=>{Q&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[Q,n]);let G=i!==void 0;return qe(()=>{if(G){K(i??null);return}if(Q){K(null);return}if(!k)return;let y=yr(k,kr(n,"video")),N=()=>{let A=T.current;return A?A.getVideoTracks()[0]??null:null},w=A=>{if(A!==N()&&(K(A),A)){let de=()=>{N()===A&&K(null)};A.addEventListener("ended",de)}},$=y.track;$&&$.readyState==="live"&&w($);let J=y.on("track",A=>{A&&A.readyState!=="live"||w(A)}),se=setInterval(()=>{let A=y.track;A&&A.readyState==="live"&&w(A)},vr);return()=>{J(),clearInterval(se)}},[k,n,Q,G,i,K]),qe(()=>{if(G||!k||s===!1||Q)return;let y=yr(k,kr(n,"audio",s)),N=()=>{let A=T.current;return A?A.getAudioTracks()[0]??null:null},w=A=>{if(A!==N()&&(ee(A),A)){let de=()=>{N()===A&&ee(null)};A.addEventListener("ended",de)}},$=y.track;$&&$.readyState==="live"&&w($);let J=y.on("track",A=>{A&&A.readyState!=="live"||w(A)}),se=setInterval(()=>{let A=y.track;A&&A.readyState==="live"&&w(A)},vr);return()=>{J(),clearInterval(se)}},[k,n,Q,s,G,ee]),io("div",{className:g,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":L?"true":"false","data-urun-video-framed":b?"true":"false",children:[br("video",{ref:ke,className:v,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...u?{transform:"scaleX(-1)"}:{}}}),L?null:C,h===void 0?null:br("div",{"data-urun-video-poster":"","aria-hidden":b||void 0,style:{position:"absolute",inset:0,...b?{opacity:0,pointerEvents:"none"}:null},children:h}),p]})});import{jsx as Cr,jsxs as fo}from"react/jsx-runtime";var po={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},mo=ao(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:u=!0,documentTarget:c,...g}=o??{},l=c!==void 0?c:typeof document<"u"?document:null,v=et(null),C=et(null),h=et(0),p=et(g);p.current=g;let m=co(()=>lo(p.current),[]);return uo(r,()=>({get video(){return v.current},get canvas(){return C.current},warp:m,get lastDrawTs(){return h.current}}),[m]),Rr(()=>{if(!i)return;let f=0,P=0,E=null,U=k=>{typeof k.requestVideoFrameCallback=="function"&&(E=k,P=k.requestVideoFrameCallback(function x(){m.frameArrived(),P=k.requestVideoFrameCallback(x)}))},S=k=>{f=requestAnimationFrame(S);let x=C.current,T=v.current?.element??null;if(!x||!T||(T!==E&&(E&&P&&E.cancelVideoFrameCallback?.(P),U(T)),T.readyState<2))return;m.tick(k);let L=typeof devicePixelRatio=="number"?devicePixelRatio:1,d=Math.max(1,Math.round(x.clientWidth*L)),b=Math.max(1,Math.round(x.clientHeight*L));(x.width!==d||x.height!==b)&&(x.width=d,x.height=b);let R=x.getContext("2d");if(!R)return;let M=m.transform(),O=T.videoWidth||d,j=T.videoHeight||b,_=Math.max(d/O,b/j)*(1+a)*M.scale;R.setTransform(_,0,0,_,d/2+M.translateX*d,b/2+M.translateY*b),R.drawImage(T,-O/2,-j/2),h.current=k};return f=requestAnimationFrame(S),()=>{cancelAnimationFrame(f),E&&P&&E.cancelVideoFrameCallback?.(P)}},[i,a,m]),Rr(()=>{if(!i||!u||!l)return;let f=()=>!!l.pointerLockElement,P=x=>{f()&&m.keyDown(x.key)},E=x=>m.keyUp(x.key),U=x=>{f()&&m.pointerDelta(x.movementX,x.movementY)},S=()=>{f()||m.clearKeys()},k=()=>m.clearKeys();return l.addEventListener("keydown",P),l.addEventListener("keyup",E),l.addEventListener("mousemove",U),l.addEventListener("pointerlockchange",S),l.defaultView?.addEventListener("blur",k),()=>{l.removeEventListener("keydown",P),l.removeEventListener("keyup",E),l.removeEventListener("mousemove",U),l.removeEventListener("pointerlockchange",S),l.defaultView?.removeEventListener("blur",k)}},[i,u,l,m]),i?fo(_e,{ref:v,...s,videoClassName:s.videoClassName,style:{...s.style},children:[Cr("canvas",{ref:C,style:po,"data-urun-warp":""}),n]}):Cr(_e,{ref:v,...s,children:n})});var Er=new Map;function go(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Er.set(e,{component:t,schema:r})}function Pr(e,t){let r=Er.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 So,jsx as tt}from"react/jsx-runtime";function ho({name:e,props:t,fallback:r}){let o=Pr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?tt(So,{children:r}):tt("div",{className:"urun-component-error",role:"alert",children:tt("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return tt(n,{...o.validatedProps})}import{z as He}from"zod";import{jsx as Mt,jsxs as Tr}from"react/jsx-runtime";var vo=He.object({step:He.number().min(0),total:He.number().min(1),label:He.string().optional(),variant:He.enum(["default","success","error"]).default("default")});function wr(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 yo(e){let{step:t,total:r,label:o,variant:n,percentage:s}=wr(e);return Tr("div",{className:"urun-progress-card","data-variant":n,children:[o&&Mt("div",{className:"urun-progress-label",children:o}),Mt("div",{className:"urun-progress-bar",children:Mt("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),Tr("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as _t}from"zod";import{jsx as xr,jsxs as Co}from"react/jsx-runtime";var ko=_t.object({state:_t.enum(["thinking","generating","idle","error"]),message:_t.string().optional()}),bo={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Ur(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??bo[t]??t;return{state:t,message:n,isActive:o}}function Ro(e){let{state:t,message:r,isActive:o}=Ur(e);return Co("span",{className:"urun-status-badge","data-state":t,children:[xr("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),xr("span",{className:"urun-status-message",children:r})]})}import{useRef as Ar,useEffect as Eo}from"react";import{z as Nt}from"zod";import{jsx as Mr,jsxs as wo}from"react/jsx-runtime";var Po=Nt.object({text:Nt.string(),streaming:Nt.boolean().default(!1)});function _r(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function To(e){let{text:t,streaming:r}=_r(e),o=Ar(null),n=Ar(0);return Eo(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),wo("div",{className:"urun-text-stream",children:[Mr("span",{ref:o,className:"urun-text-content"}),r&&Mr("span",{className:"urun-text-cursor"})]})}import{z as rt}from"zod";import{jsx as Nr,jsxs as Ao}from"react/jsx-runtime";var xo=rt.object({src:rt.string().url(),alt:rt.string().optional(),caption:rt.string().optional()});function Ir(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Uo(e){let{src:t,alt:r,caption:o}=Ir(e);return Ao("figure",{className:"urun-image-frame",children:[Nr("img",{className:"urun-image",src:t,alt:r}),o&&Nr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as Se}from"zod";import{jsx as It,jsxs as No}from"react/jsx-runtime";var Mo=Se.object({metrics:Se.array(Se.object({label:Se.string(),value:Se.union([Se.string(),Se.number()]),unit:Se.string().optional()}))});function Lr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function _o(e){let{metrics:t}=Lr(e);return It("div",{className:"urun-metrics-panel",children:t.map((r,o)=>No("div",{className:"urun-metric-card",children:[It("div",{className:"urun-metric-label",children:r.label}),It("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{forwardRef as Io}from"react";import{jsx as Oo}from"react/jsx-runtime";var Lo=Io(function(t,r){let{stream:o="image",...n}=t;return Oo(_e,{ref:r,stream:o,...n})});import{forwardRef as Vo,useCallback as Ne,useEffect as Lt,useImperativeHandle as Fo,useRef as Ie}from"react";import{observePageLifecycle as qo}from"@urun-sh/core";var nt=null;function Do(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function ot(){if(nt)return nt;let e=Do();return e?(nt=new e,nt):null}function st(){let e=ot();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{jsx as Bo}from"react/jsx-runtime";var Ho=1e3,Or=200;function Ot(...e){console.debug("[audio]",...e)}var it=Vo(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:g}=t,l=ce(),v=o??l,C=Ie(null),h=Ie(null),p=Ie(null),m=Ie(null),f=Ie(u);f.current=u;let P=Ie(c);P.current=c;let E=Ne(d=>{p.current!==d&&(p.current=d,P.current?.(d))},[]),U=Ne(()=>{if(typeof MediaStream>"u")return null;h.current||(h.current=new MediaStream);let d=C.current;return d&&d.srcObject!==h.current&&(d.srcObject=h.current),h.current},[]),S=Ne(d=>{let b=C.current;if(!b)return;let R=b.play();!R||typeof R.then!="function"||R.then(()=>{b.muted||E(!0)}).catch(M=>{let O=M instanceof Error?M.name:String(M);if(O==="AbortError"){Ot(`play() aborted (${d}); retrying in ${Or}ms`),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{m.current=null,S(`${d}:retry`)},Or);return}if(O==="NotAllowedError"){Ot(`play() blocked pending a user gesture (${d})`),E(!1);return}Ot(`play() failed (${d})`,M)})},[E]),k=Ne(d=>{let b=U();if(b){for(let R of b.getAudioTracks())R!==d&&b.removeTrack(R);d&&!b.getAudioTracks().includes(d)&&b.addTrack(d),d&&S("track-attach"),f.current?.(d)}},[U,S]),x=Ne(()=>{let d=C.current;d&&(U(),d.muted=!1,S("gesture"),st(),E(!0))},[U,S,E]);Fo(r,()=>({unlock:x,get unlocked(){return p.current===!0},get element(){return C.current}}),[x]);let T=Ne(d=>{C.current=d,d&&(d.setAttribute("playsinline",""),d.setAttribute("webkit-playsinline",""),U()),g?.(d)},[U,g]),L=s!==void 0;return Lt(()=>{if(L){k(s??null);return}if(!v)return;let d=v.stream(n),b=()=>{let I=h.current;return I?I.getAudioTracks()[0]??null:null},R=I=>{if(I!==b()&&(k(I),I)){let _=()=>{b()===I&&k(null)};I.addEventListener("ended",_)}},M=d.track;M&&M.readyState==="live"&&R(M);let O=d.on("track",I=>{I&&I.readyState!=="live"||R(I)}),j=setInterval(()=>{let I=d.track;I&&I.readyState==="live"&&R(I)},Ho);return()=>{O(),clearInterval(j)}},[v,n,L,s,k]),Lt(()=>qo(()=>{st(),p.current===!0&&S("foreground")}),[S]),Lt(()=>()=>{m.current&&clearTimeout(m.current)},[]),Bo("audio",{ref:T,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),Wo=it;import{forwardRef as jo,useCallback as Le,useEffect as Dr,useImperativeHandle as Ko,useRef as fe}from"react";import{observePageLifecycle as $o,sessionFailureFromMediaError as Xo,sharedCaptureController as zo}from"@urun-sh/core";import{jsx as Go}from"react/jsx-runtime";var Vr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function at(...e){console.debug("[voice]",...e)}var ut=jo(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=Vr,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:g,onError:l,onMicStream:v,onTrack:C,onUnlockChange:h,capture:p}=t,m=ce(),f=o??m,P=fe(null),E=fe(null),U=fe(null),S=fe([]),k=fe(!1),x=fe(g);x.current=g;let T=fe(l);T.current=l;let L=fe(v);L.current=v;let d=Le(_=>{k.current!==_&&(k.current=_,x.current?.(_))},[]),b=Le(()=>{for(let _ of S.current)_();S.current=[],U.current?.release(),U.current=null,E.current&&(E.current=null,L.current?.(null))},[]),R=Le(async()=>{let _=U.current;if(_){let H=await _.update(i);return E.current=_.stream,L.current?.(_.stream),H}let B=await(p??zo()).claim("audio",i);U.current=B,S.current=[B.onTrack((H,X)=>{E.current=X,L.current?.(X),k.current&&f?.stream(n).attach(H).catch(Y=>at("mic re-attach after one-capture re-acquire failed",Y))}),B.onLost(H=>{U.current=null,S.current=[],E.current=null,L.current?.(null),d(!1),T.current?.(H)})],E.current=B.stream,L.current?.(B.stream);let W=B.track;if(!W)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return W},[p,i,f,n,d]),M=Le(async()=>{b(),d(!1),await f?.stream(n).detach().catch(()=>{})},[f,n,b,d]),O=Le(async()=>{if(!f)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");P.current?.unlock();let _;try{_=await R()}catch(W){b();let H=Xo(W,f.status);throw T.current?.(H),H}f.connect?.();let D;for(let W=1;W<=u;W++)try{await f.whenLive(a!==void 0?{timeout:a}:void 0),await f.stream(n).attach(_),d(!0);return}catch(H){D=H,at(`start attempt ${W}/${u} failed`,H),W<u&&await new Promise(X=>setTimeout(X,c))}b(),d(!1);let B=D instanceof Error?D:new Error(String(D??"voice start failed"));throw T.current?.(B),B},[f,n,a,u,c,R,b,d]);Ko(r,()=>({start:O,stop:M,unlock:()=>P.current?.unlock(),get active(){return k.current},get micStream(){return E.current},get audio(){return P.current}}),[O,M]);let j=fe(!1),I=Le(async()=>{if(!f||!k.current||j.current)return;let _=E.current?.getAudioTracks()[0]??null;if(_&&_.readyState==="live"){try{await f.stream(n).attach(_)}catch(D){at("foreground mic re-assert failed (will retry on next pass)",D)}return}j.current=!0;try{let D=await R();await f.stream(n).attach(D)}catch(D){let B=D instanceof Error?D:new Error(String(D));at("foreground mic re-acquire failed",B),T.current?.(B)}finally{j.current=!1}},[f,n,R]);return Dr(()=>{let _=()=>{I()};return f&&typeof f.onRecovery=="function"?f.onRecovery(_):$o(_)},[f,I]),Dr(()=>b,[b]),s?Go(it,{ref:P,session:f,stream:n,onTrack:C,onUnlockChange:h}):null}),Jo=ut;import{forwardRef as Qo,useEffect as es,useImperativeHandle as ts,useRef as Fr,useState as rs}from"react";import{useEffect as Yo,useState as Zo}from"react";var Dt={level:0,speaking:!1};function Vt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=Zo(Dt);return Yo(()=>{if(!e){i(Dt);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,g;try{c=a.createMediaStreamSource(u),g=a.createAnalyser(),g.fftSize=r,c.connect(g)}catch{return}let l=new Uint8Array(g.fftSize),C=setInterval(()=>{g.getByteTimeDomainData(l);let h=0;for(let m=0;m<l.length;m++){let f=(l[m]-128)/128;h+=f*f}let p=Math.sqrt(h/l.length);i(m=>{let f=p>n;return Math.abs(m.level-p)<.005&&m.speaking===f?m:{level:p,speaking:f}})},o);return()=>{clearInterval(C),c.disconnect(),i(Dt)}},[e,r,o,n]),s}import{Fragment as is,jsx as ct,jsxs as as}from"react/jsx-runtime";var ns={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},os={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},ss=Qo(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:g,onMicStream:l,capture:v}=t,C=ce(),h=o??C,p=Fr(null),[m,f]=rs(null),P=Fr(l);P.current=l;let{level:E,speaking:U}=Vt(a?m:null);return ts(r,()=>({start:()=>{let S=p.current;return S?S.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}}),[]),es(()=>{!i||!h||p.current?.start().catch(()=>{})},[i,h]),as(is,{children:[ct(ut,{ref:p,session:h,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...v!==void 0?{capture:v}:{},onActiveChange:c,onError:g,onMicStream:S=>{f(S),P.current?.(S)}}),a?ct("span",{className:u,style:ns,"data-urun-mic":"","data-urun-mic-active":m?"true":"false","data-urun-mic-speaking":U?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(E*100)/100,children:ct("span",{style:os,children:ct("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(E*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{captureStillFromVideo as us,sessionFailureFromMediaError as cs,sharedCaptureController as ls}from"@urun-sh/core";import{forwardRef as Hr,useCallback as le,useEffect as Ft,useImperativeHandle as ds,useRef as Z,useState as We}from"react";import{jsx as ve,jsxs as qr}from"react/jsx-runtime";var Wr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function qt(...e){console.debug("[camera]",...e)}function ps(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function ms(){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 Br=Hr(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:g="auto",connectTimeoutMs:l,visible:v=!1,className:C,videoClassName:h,onActiveChange:p,onError:m,onStream:f,onTrack:P,children:E,capture:U,flipControl:S="auto",flipControlClassName:k,onDevices:x}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let T=i?"user":a?"environment":u??"environment",L=ce(),d=o??L,b=Z(null),R=Z(null),M=Z(null),O=Z([]),j=Z(null),I=Z(!1),_=Z(!1),D=Z(T),[B,W]=We(T),[H,X]=We(!1),[Y,z]=We(null),[q,K]=We(!1),[ee]=We(ps),ke=Z(p);ke.current=p;let Q=Z(m);Q.current=m;let G=Z(f);G.current=f;let y=Z(P);y.current=P;let N=Z(x);N.current=x;let w=le(V=>{I.current!==V&&(I.current=V,X(V),ke.current?.(V))},[]);Ft(()=>{if(!H){z(null);return}let V=!1,F=()=>{ms().then(ae=>{V||(z(ae),ae&&N.current?.(ae))})};F();let re=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof re?.addEventListener=="function"?(re.addEventListener("devicechange",F),()=>{V=!0,re.removeEventListener?.("devicechange",F)}):()=>{V=!0}},[H]);let $=le(V=>{let F=b.current;F&&(F.muted=!0,F.defaultMuted=!0,F.setAttribute("muted",""),F.setAttribute("playsinline",""),F.setAttribute("webkit-playsinline",""),F.srcObject=V,V&&F.play()?.catch?.(re=>qt("preview play() failed",re)))},[]),J=le(()=>{_.current=!1,j.current?.(),j.current=null;for(let V of O.current)V();O.current=[],M.current?.release(),M.current=null,R.current&&(R.current=null,G.current?.(null),y.current?.(null)),$(null)},[$]),se=le((V,F)=>{j.current?.(),R.current=F,$(F),G.current?.(F);let re=()=>{R.current===F&&(qt("camera track ended (device removed or permission revoked)"),J(),w(!1))};V.addEventListener("ended",re),j.current=()=>V.removeEventListener("ended",re)},[$,J,w]),A=le(async V=>{let F=n!==!1;if(F&&!d)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let re={...Wr,...s,facingMode:V},ae;try{let ge=M.current;if(ge)ae=await ge.update(re);else{let De=await(U??ls()).claim("video",re);if(M.current=De,O.current=[De.onTrack((Ve,on)=>{se(Ve,on),I.current&&(!F||!d||d.stream(n).attachVideo(Ve).then(()=>y.current?.(Ve)).catch(sn=>qt("camera re-publish after one-capture re-acquire failed",sn)))}),De.onLost(Ve=>{M.current=null,O.current=[],J(),w(!1),Q.current?.(Ve)})],!De.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ae=De.track}}catch(ge){let Te=cs(ge,d?.status);throw Q.current?.(Te),Te}D.current=V,W(V),se(ae,M.current?.stream??new MediaStream([ae]));try{F&&d&&(d.connect?.(),await d.whenLive(l!==void 0?{timeout:l}:void 0),await d.stream(n).attachVideo(ae)),_.current=F?n:!1}catch(ge){J(),w(!1);let Te=ge instanceof Error?ge:new Error(String(ge));throw Q.current?.(Te),Te}y.current?.(ae),w(!0)},[d,n,s,l,U,se,J,w]),de=le(V=>A(V?.facingMode??D.current),[A]),pe=le(async V=>{let F=_.current===n;I.current&&D.current===V&&F||await A(V)},[A,n]),te=le(()=>A(D.current==="environment"?"user":"environment"),[A]),ie=le(async()=>{J(),w(!1),n!==!1&&await d?.stream(n).detachVideo().catch(()=>{})},[d,n,J,w]),Pe=le(async V=>{let F=b.current;if(!F)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await us(F,V)},[]);ds(r,()=>({start:de,stop:ie,flip:te,setFacingMode:pe,capturePhoto:Pe,get active(){return I.current},get facingMode(){return D.current},get stream(){return R.current},get element(){return b.current}}),[de,ie,te,pe,Pe]);let Oe=Z(pe);if(Oe.current=pe,Ft(()=>{c&&(n!==!1&&!d||Oe.current(T).catch(()=>{}))},[c,d,T,n]),Ft(()=>J,[J]),!v)return null;let Yt=g==="auto"?B==="user":g,gt=H&&(S===!0||S==="auto"&&ee&&(Y?.length??0)>1),Je=()=>{q||(K(!0),te().catch(()=>{}).finally(()=>K(!1)))};return qr("div",{className:C,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":B,children:[ve("video",{ref:b,className:h,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Yt?{transform:"scaleX(-1)"}:{}}}),gt?ve("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Je,disabled:q,className:k,style:k?{opacity:q?.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:q?.6:1},children:qr("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:[ve("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),ve("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),ve("path",{d:"M14.5 10.5v1.6h-1.6"}),ve("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),ve("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,E]})}),fs=Hr(function({preview:t=!0,...r},o){return ve(Br,{ref:o,...r,visible:t,autoStart:!1})});import{cameraCaptureAvailable as gs,normalizeReferenceImage as hs,referenceImageErrorMessage as Ss}from"@urun-sh/core";import{useCallback as Be,useEffect as vs,useRef as Ht,useState as je}from"react";function ys(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=je(null),[a,u]=je(null),[c,g]=je(!1),[l,v]=je(null),[C]=je(gs),h=Ht(n);h.current=n;let p=Ht(null),m=Ht(0),f=Be(k=>{p.current&&URL.revokeObjectURL(p.current),p.current=k?URL.createObjectURL(new Blob([k.bytes],{type:k.type})):null,u(p.current),i(k),h.current?.(k)},[]);vs(()=>()=>{m.current++,p.current&&URL.revokeObjectURL(p.current),p.current=null},[]);let P=Be(async k=>{let x=++m.current;g(!0),v(null);try{let T=await k();if(m.current!==x)return;f(T)}catch(T){if(m.current!==x)return;v(Ss(T))}finally{m.current===x&&g(!1)}},[f]),E=Be(k=>P(()=>hs(k,{maxSize:t,type:r,quality:o,source:"file"})),[P,t,r,o]),U=Be(k=>P(()=>k.capturePhoto({maxSize:t,type:r,quality:o})),[P,t,r,o]),S=Be(()=>{m.current++,v(null),g(!1),f(null)},[f]);return{reference:s,previewUrl:a,pick:E,capture:U,clear:S,busy:c,error:l,cameraAvailable:C}}import{useEffect as ks,useState as bs}from"react";function Rs(e,t){let[r,o]=bs(null);return ks(()=>{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 xs}from"react";import{useEffect as Ts,useMemo as ws}from"react";import{createStore as Cs}from"zustand/vanilla";import{useStore as Es}from"zustand";var Ps=()=>{};function Wt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=Cs(()=>({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):Ps,u=(c=>Es(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 Ke(e,t){let r=ws(()=>Wt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return Ts(()=>r.bind(),[r]),r}function Us(e,t,r){let n=Ke(e,t)(r??(a=>a)),s=xs(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 As,useState as Ms}from"react";var Re=200;function ye(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function $e(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Bt(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 jt(e,t,r={}){let o=r.cap??200,[n,s]=Ms([]);return As(()=>{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=>ye(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}import{jsx as lt,jsxs as Xe}from"react/jsx-runtime";function _s({session:e,name:t,cap:r,className:o}){let n=jt(e,t,{cap:r});return Xe("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[Xe("div",{className:"urun-stream-tail-meta",children:[lt("code",{children:t}),Xe("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),lt("div",{className:"urun-stream-tail-log",children:n.length===0?Xe("span",{className:"urun-stream-tail-empty",children:["Waiting for ",lt("code",{children:t})," messages\u2026"]}):n.map((s,i)=>Xe("div",{className:"urun-stream-tail-line",children:[lt("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",$e(s.payload)]},`${s.at}-${i}`))})]})}import{useCallback as Ns,useState as jr}from"react";import{jsx as Ce,jsxs as dt}from"react/jsx-runtime";function pt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=jr(""),[i,a]=jr(null),u=Ns(()=>{let c=Bt(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return dt("div",{className:"urun-doc-patch",children:[Ce("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),dt("div",{className:"urun-doc-patch-actions",children:[Ce("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?Ce("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function Is({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Ke(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return dt("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[dt("div",{className:"urun-doc-panel-meta",children:[Ce("code",{children:t}),Ce("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),Ce("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?Ce(pt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}import{useEffect as Ls,useState as Os}from"react";import{jsx as ze,jsxs as $r}from"react/jsx-runtime";function Kr(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Ds({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=Os([]);return Ls(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>ye(u,{at:Date.now(),direction:"in",text:Kr($e(a))},r))}):void 0),[e,t,r]),$r("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[ze(pt,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>ye(u,{at:Date.now(),direction:"out",text:Kr(a)},r))}}),ze("div",{className:"urun-control-sender-log",children:n.length===0?ze("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>$r("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[ze("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",ze("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}import{useEffect as Vs,useState as Fs}from"react";import{jsx as mt,jsxs as Hs}from"react/jsx-runtime";function qs({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=Fs([]),a=t.join(","),u=r.join(",");return Vs(()=>{if(i([]),!e)return;let c=(l,v)=>i(C=>ye(C,{at:Date.now(),kind:l,text:v},o)),g=[];g.push(e.onPhase(l=>c("phase",`phase \u2192 ${l.name}`)));for(let l of t){let v=e.stream(l);g.push(v.on("track",C=>c("track",`${l}: ${C?"track arrived":"track ended"}`)))}for(let l of r){let v=e.doc(l);g.push(v.on("change",()=>c("doc",`${l} changed`)))}return()=>g.forEach(l=>l())},[e,a,u,o]),mt("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?mt("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,g)=>Hs("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[mt("span",{className:"urun-event-spine-kind",children:c.kind})," ",mt("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${g}`))})}import{describeSessionPhase as ri,isWakingPhase as ni}from"@urun-sh/core";import{useEffect as Ws,useState as Bs}from"react";function oe(e){let[t,r]=Bs(e?.phase??null);return Ws(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as zs}from"@urun-sh/core";import{useEffect as js,useRef as Ks,useState as $s}from"react";import{isWakingPhase as Xs}from"@urun-sh/core";function Kt(e){let t=oe(e),r=Xs(t?.name),o=Ks(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]=$s(s);return js(()=>{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 Js,jsx as Xr,jsxs as zr}from"react/jsx-runtime";function $t({session:e,render:t,className:r}){let o=Kt(e);return!o.waking||!o.phase?null:Xr("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):zr(Js,{children:[Xr("span",{className:"urun-session-waking-label",children:zs(o.phase)})," ",zr("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as Zs,useState as Qs}from"react";import{useEffect as Jr,useRef as Gs,useState as Gr}from"react";var Ys={event:null,elapsedMs:0};function Xt(e,t){let[r,o]=Gr(null),n=Gs(0);Jr(()=>{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]=Gr(0);return Jr(()=>{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}:Ys}import{jsx as Yr,jsxs as Zr}from"react/jsx-runtime";var ei={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 ti(e){let[t,r]=Qs(!1);return Zs(()=>{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 zt({session:e,stream:t,videoElement:r,render:o,className:n}){let s=Xt(e,t),i=ti(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return Yr("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):Zr("div",{className:"urun-activation-overlay-card",children:[Yr("span",{className:"urun-activation-overlay-copy",children:a.hint??ei[u]})," ",Zr("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as Ee,jsxs as Jt}from"react/jsx-runtime";var oi={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function si({session:e,className:t}){let r=oe(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 Jt("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[Ee("span",{className:"urun-session-status-dot","data-phase":o}),Ee("span",{className:"urun-session-status-label",children:oi[o]}),n?Ee("span",{className:"urun-session-status-detail",children:n}):null]})}function ii({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=oe(e);if(s?.name==="live")return Jt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,Ee(zt,{session:e})]});let i=r?r(s):Ee("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&ni(s.name)?Ee($t,{session:e}):s&&s.name!=="idle"?ri(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return Jt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?Ee("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as ai,useState as ui}from"react";import{jsx as di}from"react/jsx-runtime";function Qr(e){return oe(e)?.endsAt??null}function ci(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 li({session:e,urgentMs:t=6e4,className:r}){let n=Qr(e)?.getTime()??null,[s,i]=ui(()=>n===null?null:Math.max(0,n-Date.now()));if(ai(()=>{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=ci(s);return di("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 en,jsxs as fi}from"react/jsx-runtime";var pi=new Set(["expired","ended","error"]);function mi({session:e,onNewSession:t,children:r,className:o}){let n=oe(e);if(!n||!pi.has(n.name))return null;let s=r?r(n):en("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 fi("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?en("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}import{useEffect as tn,useMemo as gi,useState as rn}from"react";import{jsx as ft,jsxs as vi}from"react/jsx-runtime";function Gt(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 nn(e){let t=gi(()=>e?e.doc("control"):null,[e]),[r,o]=rn(()=>t?Gt(t.get("idle")):null);return tn(()=>{if(!t){o(null);return}return o(Gt(t.get("idle"))),t.on("change",()=>o(Gt(t.get("idle"))))},[t]),r}function hi(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Si({session:e,onStillHere:t,className:r}){let o=nn(e),n=o?.deadlineEpochS??null,[s,i]=rn(null);if(tn(()=>{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 ft("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:vi("div",{className:"urun-idle-warning-card",children:[ft("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),ft("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${hi(s)} due to inactivity.`:"This session will end soon due to inactivity."}),ft("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useContext as yi,useEffect as ki,useState as bi}from"react";import{prewake as Ri}from"@urun-sh/core";function Ci(e){let t=yi(we),[r,o]=bi(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,g=t?.getAccessToken,l=t?.authProvider;return ki(()=>{if(!a||!u||!n||!s)return;let v=!1,C=()=>{Ri({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:g,authProvider:l}).then(p=>{v||o(p)}).catch(()=>{})};C();let h=setInterval(C,Math.max(1,i)*1e3);return()=>{v=!0,clearInterval(h)}},[n,s,i,a,u,c,g,l]),r}import{describeSessionPhase as Il,isWakingPhase as Ll}from"@urun-sh/core";export{it as Audio,Br as Camera,ho as ComponentRenderer,Wr as DEFAULT_CAMERA_CONSTRAINTS,Re as DEFAULT_LOG_CAP,Vr as DEFAULT_VOICE_CONSTRAINTS,pt as DocPatchForm,Lo as Image,Uo as ImageFrame,xo as ImageFrameSchema,_o as MetricsPanel,Mo as MetricsPanelSchema,ss as Mic,gn as OPERATOR_CHORD_LABEL,fn as OPERATOR_TOKEN_STORAGE_KEY,yo as ProgressCard,vo as ProgressCardSchema,mo as ReprojectedVideo,Zn as Session,Ro as StatusBadge,ko as StatusBadgeSchema,To as TextStream,Po as TextStreamSchema,zt as UrunActivationOverlay,Wo as UrunAudio,ht as UrunAuthProvider,fs as UrunCamera,Ds as UrunControlSender,Is as UrunDocPanel,Fe as UrunErrorBoundary,qs as UrunEventSpine,Si as UrunIdleWarning,an as UrunJwtProvider,Pn as UrunProvider,li as UrunSessionClock,mi as UrunSessionEnded,ii as UrunSessionGate,si as UrunSessionStatus,$t as UrunSessionWaking,_s as UrunStreamTail,Jo as UrunVoice,_e as Video,ut as Voice,Ge as authMode,Wt as createDocStore,Il as describeSessionPhase,$e as formatPayload,ot as getUrunAudioContext,Ll as isWakingPhase,Bt as parseJsonObject,ye as pushCapped,rr as readOperatorToken,go as registerComponent,st as resumeUrunAudioContext,ue as urunPublicEnv,Xt as useActivation,Nn as useApp,Kn as useChat,Hn as useCompletion,yt as useConfirmOnLeave,Ke as useDocStore,Ir as useImageFrame,Gn as useInputPresence,Lr as useMetricsPanel,vt as useOperatorOverride,wr as useProgressCard,ys as useReferenceImage,Dn as useRequest,Qn as useSession,Us as useSessionDoc,Qr as useSessionEndsAt,nn as useSessionIdle,oe as useSessionPhase,Rs as useSessionTrack,Kt as useSessionWake,Ur as useStatusBadge,jt as useStreamMessages,_r as useTextStream,Vt as useUrunAudioLevel,St as useUrunAuth,Ci as useUrunPrewake,dn as usesWorkOSAuth};
2
+ import{a as St,b as un,c as vt}from"./chunk-WF2OBDSX.mjs";import{useCallback as nr,useEffect as kn,useMemo as bn,useRef as or,useState as bt}from"react";import{Component as cn}from"react";import{jsx as Zt,jsxs as ln}from"react/jsx-runtime";var Be=class extends cn{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||ln("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:[Zt("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),Zt("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as dn}from"react";var _e=dn(null);function ve(e){return e&&e.trim()?e.trim():void 0}function de(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return ve(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return ve(typeof process<"u"?process.env?.[e]:void 0)}}function Qe(){let e=de("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||de("VERCEL_ENV")==="production"?"workos":de("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function pn(){return Qe()==="workos"}import{useEffect as mn,useRef as fn}from"react";var gn="urun.operator_token",er=null,Qt="op",hn="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function tr(){return typeof window<"u"}function rr(){return er}function Sn(){if(!tr())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(Qt);if(!r)return null;er=r,t.delete(Qt);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function vn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function yt(e){let t=fn(e);t.current=e,mn(()=>{if(!tr())return;Sn();let r=o=>{if(!vn(o))return;let n=rr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as yn}from"react";function kt(e=!0){yn(()=>{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 Ne,jsxs as wn}from"react/jsx-runtime";var Rn="/api/urun-token",Cn=1e4;function En(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 sr(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 ir(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function Pn(e,t){return typeof e=="function"?e(t):e!==void 0?e:wn("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:[Ne("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),Ne("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Tn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,audioPlayout:f,confirmOnLeave:d=!1,fallback:y,errorFallback:b,children:k}){let l=n===void 0&&t===void 0;if(!l&&(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(!l&&(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 g=r??o;if(l&&(typeof g!="string"||g.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);kt(d);let[m,E]=bt(),[R,w]=bt(null),h=or(void 0),C=or(null),[T,x]=bt(null);yt(z=>x({jwt:z}));let U=vt(),p=de("NEXT_PUBLIC_SESSION_TOKEN")??de("NEXT_PUBLIC_URUN_JWT"),P=Qe(),v=T!==null,M=P==="workos"&&!n&&!v&&!l,H=n??(P==="jwt"?p:void 0)??m?.token,V=v?T.jwt:H,I=s??de("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),N=M&&!V&&!U?.getAccessToken,F=t??m?.orgId,W=e??m?.gatewayUrl,J=l&&m===void 0,B=l&&m!==void 0&&!W?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,G=N?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,Y=R??B??G,j=ir("NEXT_PUBLIC_URUN_TOKEN_URL",de("NEXT_PUBLIC_URUN_TOKEN_URL"))??u??Rn,q=ir("NEXT_PUBLIC_URUN_EVENTS_URL",de("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,$=nr(async z=>{if(!z?.forceRefresh){let X=h.current;if(!X)return X;let ee=En(X);if(ee===null||ee-Date.now()>Cn)return X}return(await(C.current??(C.current=(async()=>{try{let X=await sr(j);return h.current=X.token,E(X),X}finally{C.current=null}})()))).token},[j]),le=nr(async()=>V,[V]),ne=typeof V=="string"&&V.trim().length>0,Z=M?U?.getAccessToken:l&&!v?$:ne?le:void 0,ke=bn(()=>({appId:g,baseUrl:W??"",orgId:F??"",jwt:V,getAccessToken:M?U?.getAccessToken:l&&!v?$:void 0,authProvider:I,eventsUrl:q,sessionKey:a,releaseOnLeave:c,audioPlayout:f,priority:v?"preempt":void 0}),[g,U,W,I,V,q,F,a,c,f,M,v,l,$]);return kn(()=>{if(!l)return;let z=new AbortController;return w(null),(async()=>{try{let Q=await sr(j,z.signal);h.current=Q.token,E(Q)}catch(Q){if(z.signal.aborted)return;w(Q instanceof Error?Q:new Error(String(Q)))}})(),()=>z.abort()},[l,j]),Ne(Be,{fallback:y,children:Y?Pn(b,Y):J?Ne("div",{role:"status","aria-live":"polite",children:"Signing in..."}):Ne(_e.Provider,{value:ke,children:Z?Ne(St,{getAccessToken:Z,children:k}):k})})}import{useContext as xn,useEffect as Un,useMemo as ar,useReducer as An,useRef as Rt}from"react";import{App as Mn}from"@urun-sh/core";function _n(e,t){return`${e}:${JSON.stringify(t??{})}`}function Nn(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 Te=new Map;var Ct=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()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}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()}},Et=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()}},Pt=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 Ct(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new Et(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 In(){let e=xn(_e);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=An(i=>i+1,0),r=Rt(new Map),o=Rt(new Map),n=Rt(null),s=ar(()=>Mn(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,audioPlayout:e.audioPlayout}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority,e.audioPlayout]);return Un(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=Te.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=Te.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=Te.get(u);!d||d.refCount!==0||(Te.delete(u),d.handle.disconnect())},0)))}n.current=a}},[]),ar(()=>{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 y=_n(u,d),b=r.current.get(y);if(b&&!b.disposed)return b;let k=Nn(e,u,d),l=Te.get(k);return l?.handle.disposed&&(l.disposeTimer&&clearTimeout(l.disposeTimer),Te.delete(k),o.current.get(k)===l&&o.current.delete(k),l=void 0),l?l.disposeTimer&&(clearTimeout(l.disposeTimer),l.disposeTimer=null):(l={handle:new Pt(s[u](d),t,e.eventsUrl),refCount:0,disposeTimer:null},Te.set(k,l)),o.current.get(k)!==l&&(o.current.set(k,l),l.handle.addNotifier(t),l.refCount+=1),r.current.set(y,l.handle),l.handle};return i.set(u,f),f}})},[e,s])}import{useCallback as Tt,useEffect as Ln,useMemo as On,useRef as et,useState as wt}from"react";function Ie(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 Dn(e){return e instanceof Error?e:new Error(String(e))}function Vn(e,t){let r=On(()=>Ie(e),[e]),[o,n]=wt(void 0),[s,i]=wt(null),[a,u]=wt(!1),c=et(t);c.current=t;let f=et(0),d=et(null),y=et(!0);Ln(()=>(y.current=!0,()=>{y.current=!1,d.current?.abort()}),[]);let b=Tt(async g=>{d.current?.abort();let m=new AbortController;d.current=m;let E=++f.current,R=()=>y.current&&f.current===E;R()&&(u(!0),i(null));try{let w=await r.request(g,{...c.current,signal:m.signal});return R()&&(n(w),u(!1),c.current?.onSuccess?.(w)),w}catch(w){let h=Dn(w);throw R()&&(i(h),u(!1),c.current?.onError?.(h)),h}},[r]),k=Tt(g=>{b(g).catch(()=>{})},[b]),l=Tt(()=>{f.current++,d.current?.abort(),d.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:k,mutateAsync:b,data:o,error:s,isPending:a,reset:l}}import{useCallback as ur,useEffect as Fn,useMemo as qn,useRef as tt,useState as xt}from"react";function cr(e){return e instanceof Error?e:new Error(String(e))}var Hn=e=>typeof e=="string"?e:String(e);function Wn(e,t){let r=qn(()=>Ie(e),[e]),[o,n]=xt(""),[s,i]=xt(!1),[a,u]=xt(null),c=tt(t);c.current=t;let f=tt(0),d=tt(null),y=tt(!0);Fn(()=>(y.current=!0,()=>{y.current=!1,d.current?.cancel(),d.current=null}),[]);let b=ur(()=>{f.current++,d.current?.cancel(),d.current=null,y.current&&i(!1)},[]),k=ur(async l=>{d.current?.cancel();let g=++f.current,m=()=>y.current&&f.current===g,E=c.current,R=E?.parseChunk??Hn,w=E?.buildPayload??(v=>({prompt:v}));m()&&(n(""),u(null),i(!0));let{parseChunk:h,buildPayload:C,onFinish:T,onError:x,...U}=E??{},p="",P;try{P=r.requestStream(w(l),U),d.current=P}catch(v){let M=cr(v);m()&&(u(M),i(!1),E?.onError?.(M));return}try{for await(let v of P){if(f.current!==g)break;p+=R(v),m()&&n(p)}m()&&(i(!1),E?.onFinish?.(p))}catch(v){let M=cr(v);m()&&(u(M),i(!1),E?.onError?.(M))}finally{d.current===P&&(d.current=null)}},[r]);return{completion:o,complete:k,stop:b,isStreaming:s,error:a}}import{useCallback as lr,useEffect as Bn,useMemo as jn,useRef as Le,useState as rt}from"react";function dr(e){return e instanceof Error?e:new Error(String(e))}var Kn=e=>typeof e=="string"?e:String(e),pr=0;function Ut(e){return pr+=1,`${e}-${pr}`}function $n(e,t){let r=jn(()=>Ie(e),[e]),[o,n]=rt(()=>(t?.initialMessages??[]).map(R=>({id:R.id??Ut("msg"),role:R.role,content:R.content}))),[s,i]=rt(""),[a,u]=rt(!1),[c,f]=rt(null),d=Le(t);d.current=t;let y=Le(o);y.current=o;let b=Le(s);b.current=s;let k=Le(0),l=Le(null),g=Le(!0);Bn(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let m=lr(()=>{k.current++,l.current?.cancel(),l.current=null,g.current&&u(!1)},[]),E=lr(async R=>{let w=R===void 0,h=(w?b.current:R)??"";if(!h.trim())return;l.current?.cancel();let T=++k.current,x=()=>g.current&&k.current===T,U=d.current,p=U?.parseChunk??Kn,P={id:Ut("msg"),role:"user",content:h},v={id:Ut("msg"),role:"assistant",content:""},M=[...y.current,P].map(q=>({role:q.role,content:q.content})),H=[...y.current,P,v];y.current=H,n(H),w&&i(""),f(null),u(!0);let V=U?.buildPayload??(q=>({messages:q})),{initialMessages:I,parseChunk:N,buildPayload:F,onFinish:W,onError:J,...B}=U??{},G=q=>{n($=>$.map(le=>le.id===v.id?{...le,content:q}:le))},Y="",j;try{j=r.requestStream(V(M),B),l.current=j}catch(q){let $=dr(q);x()&&(f($),u(!1),U?.onError?.($));return}try{for await(let q of j){if(k.current!==T)break;Y+=p(q),x()&&G(Y)}x()&&(u(!1),U?.onFinish?.({...v,content:Y}))}catch(q){let $=dr(q);x()&&(f($),u(!1),U?.onError?.($))}finally{l.current===j&&(l.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:E,stop:m,isStreaming:a,error:c}}import{useCallback as be,useEffect as mr,useMemo as Xn,useRef as fr,useState as gr}from"react";import{createInputPresencePublisher as zn,INPUT_PRESENCE_DEFAULT_HZ as Jn,INPUT_PRESENCE_FIELD as Gn}from"@urun-sh/core";var At=[];function Yn(e,t={}){let{field:r=Gn,hz:o=Jn}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=Xn(()=>s?zn({awareness:{setLocalStateField:(h,C)=>s.setField(h,C)},field:r,hz:o}):null,[s,r,o]),a=fr(null);a.current=i;let[u,c]=gr(!1),[f,d]=gr(At),y=fr(!1);mr(()=>{if(i)return()=>i.dispose()},[i]);let b=be(()=>{let h=a.current;d(h?h.heldKeys():At)},[]),k=be(()=>{a.current?.clear(),d(At)},[]);mr(()=>{if(!n)return;let h=()=>!!n.pointerLockElement,C=()=>{if(h()){y.current=!1,c(!0);return}y.current||(c(!1),k())},T=v=>{h()&&(a.current?.keyDown(v.key),b())},x=v=>{a.current?.keyUp(v.key),b()},U=v=>{h()&&a.current?.movePointer(v.movementX,v.movementY)},p=v=>{h()&&a.current?.setButtons(v.buttons)},P=()=>{k()};return n.addEventListener("pointerlockchange",C),n.addEventListener("keydown",T),n.addEventListener("keyup",x),n.addEventListener("mousemove",U),n.addEventListener("mousedown",p),n.addEventListener("mouseup",p),n.defaultView?.addEventListener("blur",P),()=>{n.removeEventListener("pointerlockchange",C),n.removeEventListener("keydown",T),n.removeEventListener("keyup",x),n.removeEventListener("mousemove",U),n.removeEventListener("mousedown",p),n.removeEventListener("mouseup",p),n.defaultView?.removeEventListener("blur",P)}},[n,k,b]);let l=be(h=>{h.requestPointerLock?.()},[]),g=be(()=>{y.current=!0,c(!0)},[]),m=be(()=>{y.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),k()},[n,k]),E=be(h=>{a.current?.keyDown(h),b()},[b]),R=be(h=>{a.current?.keyUp(h),b()},[b]),w=be((h,C)=>{a.current?.movePointer(h,C)},[]);return{engage:l,engageTouch:g,release:m,engaged:u,heldKeys:f,pressKey:E,releaseKey:R,movePointer:w}}import{forwardRef as uo,useEffect as Cr,useImperativeHandle as co,useMemo as lo,useRef as st}from"react";import{createCameraWarp as po}from"@urun-sh/core";import{forwardRef as no,useCallback as Re,useEffect as je,useImperativeHandle as oo,useRef as oe,useState as Sr}from"react";import{derivedLegRole as so}from"@urun-sh/core";var nt=null;function Zn(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function ot(){if(nt)return nt;let e=Zn();return e?(nt=new e,nt):null}function Oe(){let e=ot();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{createContext as Qn,useContext as hr}from"react";import{jsx as ro}from"react/jsx-runtime";var Mt=Qn(null);function eo({session:e,children:t}){return ro(Mt.Provider,{value:e,children:t})}function pe(){return hr(Mt)}function to(){let e=hr(Mt);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{jsx as Rr,jsxs as ao}from"react/jsx-runtime";function io(e,t){return e-t>>>0<2147483648}var vr=1e3;function yr(...e){console.debug("[video]",...e)}function kr(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(u=>u.on("track",()=>i(n())));return()=>{for(let u of a)u()}}}}function br(e,t,r){return r?[r,t]:[e,t]}var De=no(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:y,placeholder:b,poster:k,children:l,onTrack:g,onFirstFrame:m,frameMarker:E,onFrameMarkerReached:R,onFrameMarkerUnsupported:w,onUnlockChange:h}=t,C=pe(),T=o??C,x=oe(null),U=oe(null),[p,P]=Sr(!1),[v,M]=Sr(!1),H=oe(!1),V=oe(null),I=oe(g);I.current=g;let N=oe(h);N.current=h;let F=oe(m);F.current=m;let W=oe(R);W.current=R;let J=oe(w);J.current=w;let B=oe(E??null);B.current=E??null;let G=Re(S=>{V.current!==S&&(V.current=S,N.current?.(S))},[]),Y=oe(null),j=oe(null),q=Re((S,L=!1)=>{if(!L&&S===Y.current||(Y.current=S,j.current?.(),j.current=null,H.current=!1,M(!1),!S))return;let _=x.current;if(!_)return;let K=B.current,se=K?.rtpTimestamp??null,fe=!1,A=()=>{fe||(fe=!0,J.current?.())};K&&se==null&&A();let ge=K!=null&&se!=null,Ae=Se=>{j.current?.(),j.current=null,H.current=!0,M(!0),F.current?.(),Se&&W.current?.()};if(typeof _.requestVideoFrameCallback=="function"){let Se=!1,O=0,D=(ie,ae)=>{if(!Se){if(ge){let ue=ae?.rtpTimestamp;if(typeof ue!="number"){A(),Ae(!1);return}if(!io(ue,se)){O=_.requestVideoFrameCallback(D);return}Ae(!0);return}Ae(!1)}};O=_.requestVideoFrameCallback(D),j.current=()=>{Se=!0,_.cancelVideoFrameCallback?.(O)};return}ge&&A();let he=()=>{let Se=_.getVideoPlaybackQuality?.();(Se?Se.totalVideoFrames>0:_.readyState>=2&&_.videoWidth>0)&&Ae(!1)};_.addEventListener("loadeddata",he),_.addEventListener("timeupdate",he),_.addEventListener("playing",he),j.current=()=>{_.removeEventListener("loadeddata",he),_.removeEventListener("timeupdate",he),_.removeEventListener("playing",he)},he()},[]);je(()=>()=>{j.current?.(),j.current=null},[]);let $=E==null?null:`${E.rtpTimestamp??""}|${E.ptsMs??""}`,le=oe($);je(()=>{if(le.current===$||(le.current=$,$==null))return;let S=Y.current;S&&q(S,!0)},[$,q]);let ne=Re(()=>{if(typeof MediaStream>"u")return null;U.current||(U.current=new MediaStream);let S=x.current;return S&&S.srcObject!==U.current&&(S.srcObject=U.current),U.current},[]),Z=Re(S=>{let L=x.current;if(!L)return;let _=L.play();!_||typeof _.then!="function"||_.then(()=>{L.muted||G(!0)}).catch(K=>{if((K instanceof Error?K.name:String(K))==="NotAllowedError"&&!L.muted){yr(`play() blocked pending a user gesture (${S})`),G(!1);return}yr(`play() failed (${S})`,K)})},[G]),ke=Re(()=>{let S=x.current;S&&(ne(),!S.muted&&(Z("gesture"),Oe(),G(!0)))},[ne,Z,G]),z=Re(S=>{let L=ne();if(L){for(let _ of L.getVideoTracks())_!==S&&L.removeTrack(_);if(S&&!L.getVideoTracks().includes(S)){L.addTrack(S);let _=x.current;_&&(_.srcObject=L)}S&&Z("track-attach"),P(S!==null),q(S),I.current?.(S)}},[ne,Z,q]),Q=Re(S=>{let L=ne();if(L){for(let _ of L.getAudioTracks())_!==S&&L.removeTrack(_);S&&!L.getAudioTracks().includes(S)&&L.addTrack(S),S&&Z("audio-attach")}},[ne,Z]),X=Re(S=>{x.current=S,S&&(a?(S.muted=!0,S.defaultMuted=!0,S.setAttribute("muted",""),V.current=null):(S.muted=!1,S.defaultMuted=!1,S.removeAttribute("muted")),S.setAttribute("playsinline",""),S.setAttribute("webkit-playsinline",""),ne())},[ne,a]);oo(r,()=>({get element(){return x.current},get live(){return U.current?U.current.getVideoTracks().length>0:!1},get framed(){return H.current},unlock:ke,get unlocked(){return V.current===!0}}),[ke]);let ee=so(n)!==void 0;je(()=>{ee&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[ee,n]);let te=i!==void 0;return je(()=>{if(te){z(i??null);return}if(ee){z(null);return}if(!T)return;let S=kr(T,br(n,"video")),L=()=>{let A=U.current;return A?A.getVideoTracks()[0]??null:null},_=A=>{if(A!==L()&&(z(A),A)){let ge=()=>{L()===A&&z(null)};A.addEventListener("ended",ge)}},K=S.track;K&&K.readyState==="live"&&_(K);let se=S.on("track",A=>{A&&A.readyState!=="live"||_(A)}),fe=setInterval(()=>{let A=S.track;A&&A.readyState==="live"&&_(A)},vr);return()=>{se(),clearInterval(fe)}},[T,n,ee,te,i,z]),je(()=>{if(te||!T||s===!1||ee)return;let S=kr(T,br(n,"audio",s)),L=()=>{let A=U.current;return A?A.getAudioTracks()[0]??null:null},_=A=>{if(A!==L()&&(Q(A),A)){let ge=()=>{L()===A&&Q(null)};A.addEventListener("ended",ge)}},K=S.track;K&&K.readyState==="live"&&_(K);let se=S.on("track",A=>{A&&A.readyState!=="live"||_(A)}),fe=setInterval(()=>{let A=S.track;A&&A.readyState==="live"&&_(A)},vr);return()=>{se(),clearInterval(fe)}},[T,n,ee,s,te,Q]),ao("div",{className:f,style:{position:"relative",width:"100%",height:"100%",...d},"data-urun-video":"","data-urun-video-live":p?"true":"false","data-urun-video-framed":v?"true":"false",children:[Rr("video",{ref:X,className:y,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...u?{transform:"scaleX(-1)"}:{}}}),p?null:b,k===void 0?null:Rr("div",{"data-urun-video-poster":"","aria-hidden":v||void 0,style:{position:"absolute",inset:0,...v?{opacity:0,pointerEvents:"none"}:null},children:k}),l]})});import{jsx as Er,jsxs as go}from"react/jsx-runtime";var mo={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},fo=uo(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:u=!0,documentTarget:c,...f}=o??{},d=c!==void 0?c:typeof document<"u"?document:null,y=st(null),b=st(null),k=st(0),l=st(f);l.current=f;let g=lo(()=>po(l.current),[]);return co(r,()=>({get video(){return y.current},get canvas(){return b.current},warp:g,get lastDrawTs(){return k.current}}),[g]),Cr(()=>{if(!i)return;let m=0,E=0,R=null,w=C=>{typeof C.requestVideoFrameCallback=="function"&&(R=C,E=C.requestVideoFrameCallback(function T(){g.frameArrived(),E=C.requestVideoFrameCallback(T)}))},h=C=>{m=requestAnimationFrame(h);let T=b.current,x=y.current?.element??null;if(!T||!x||(x!==R&&(R&&E&&R.cancelVideoFrameCallback?.(E),w(x)),x.readyState<2))return;g.tick(C);let U=typeof devicePixelRatio=="number"?devicePixelRatio:1,p=Math.max(1,Math.round(T.clientWidth*U)),P=Math.max(1,Math.round(T.clientHeight*U));(T.width!==p||T.height!==P)&&(T.width=p,T.height=P);let v=T.getContext("2d");if(!v)return;let M=g.transform(),H=x.videoWidth||p,V=x.videoHeight||P,N=Math.max(p/H,P/V)*(1+a)*M.scale;v.setTransform(N,0,0,N,p/2+M.translateX*p,P/2+M.translateY*P),v.drawImage(x,-H/2,-V/2),k.current=C};return m=requestAnimationFrame(h),()=>{cancelAnimationFrame(m),R&&E&&R.cancelVideoFrameCallback?.(E)}},[i,a,g]),Cr(()=>{if(!i||!u||!d)return;let m=()=>!!d.pointerLockElement,E=T=>{m()&&g.keyDown(T.key)},R=T=>g.keyUp(T.key),w=T=>{m()&&g.pointerDelta(T.movementX,T.movementY)},h=()=>{m()||g.clearKeys()},C=()=>g.clearKeys();return d.addEventListener("keydown",E),d.addEventListener("keyup",R),d.addEventListener("mousemove",w),d.addEventListener("pointerlockchange",h),d.defaultView?.addEventListener("blur",C),()=>{d.removeEventListener("keydown",E),d.removeEventListener("keyup",R),d.removeEventListener("mousemove",w),d.removeEventListener("pointerlockchange",h),d.defaultView?.removeEventListener("blur",C)}},[i,u,d,g]),i?go(De,{ref:y,...s,videoClassName:s.videoClassName,style:{...s.style},children:[Er("canvas",{ref:b,style:mo,"data-urun-warp":""}),n]}):Er(De,{ref:y,...s,children:n})});var Pr=new Map;function ho(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Pr.set(e,{component:t,schema:r})}function Tr(e,t){let r=Pr.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 vo,jsx as it}from"react/jsx-runtime";function So({name:e,props:t,fallback:r}){let o=Tr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?it(vo,{children:r}):it("div",{className:"urun-component-error",role:"alert",children:it("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return it(n,{...o.validatedProps})}import{z as Ke}from"zod";import{jsx as _t,jsxs as wr}from"react/jsx-runtime";var yo=Ke.object({step:Ke.number().min(0),total:Ke.number().min(1),label:Ke.string().optional(),variant:Ke.enum(["default","success","error"]).default("default")});function xr(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 ko(e){let{step:t,total:r,label:o,variant:n,percentage:s}=xr(e);return wr("div",{className:"urun-progress-card","data-variant":n,children:[o&&_t("div",{className:"urun-progress-label",children:o}),_t("div",{className:"urun-progress-bar",children:_t("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),wr("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as Nt}from"zod";import{jsx as Ur,jsxs as Eo}from"react/jsx-runtime";var bo=Nt.object({state:Nt.enum(["thinking","generating","idle","error"]),message:Nt.string().optional()}),Ro={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Ar(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??Ro[t]??t;return{state:t,message:n,isActive:o}}function Co(e){let{state:t,message:r,isActive:o}=Ar(e);return Eo("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 Mr,useEffect as Po}from"react";import{z as It}from"zod";import{jsx as _r,jsxs as xo}from"react/jsx-runtime";var To=It.object({text:It.string(),streaming:It.boolean().default(!1)});function Nr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function wo(e){let{text:t,streaming:r}=Nr(e),o=Mr(null),n=Mr(0);return Po(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),xo("div",{className:"urun-text-stream",children:[_r("span",{ref:o,className:"urun-text-content"}),r&&_r("span",{className:"urun-text-cursor"})]})}import{z as at}from"zod";import{jsx as Ir,jsxs as Mo}from"react/jsx-runtime";var Uo=at.object({src:at.string().url(),alt:at.string().optional(),caption:at.string().optional()});function Lr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Ao(e){let{src:t,alt:r,caption:o}=Lr(e);return Mo("figure",{className:"urun-image-frame",children:[Ir("img",{className:"urun-image",src:t,alt:r}),o&&Ir("figcaption",{className:"urun-image-caption",children:o})]})}import{z as Ce}from"zod";import{jsx as Lt,jsxs as Io}from"react/jsx-runtime";var _o=Ce.object({metrics:Ce.array(Ce.object({label:Ce.string(),value:Ce.union([Ce.string(),Ce.number()]),unit:Ce.string().optional()}))});function Or(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function No(e){let{metrics:t}=Or(e);return Lt("div",{className:"urun-metrics-panel",children:t.map((r,o)=>Io("div",{className:"urun-metric-card",children:[Lt("div",{className:"urun-metric-label",children:r.label}),Lt("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{forwardRef as Lo}from"react";import{jsx as Do}from"react/jsx-runtime";var Oo=Lo(function(t,r){let{stream:o="image",...n}=t;return Do(De,{ref:r,stream:o,...n})});import{forwardRef as Vo,useCallback as Ve,useEffect as Ot,useImperativeHandle as Fo,useRef as Fe}from"react";import{observePageLifecycle as qo}from"@urun-sh/core";import{jsx as Bo}from"react/jsx-runtime";var Ho=1e3,Dr=200;function Dt(...e){console.debug("[audio]",...e)}var ut=Vo(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(),y=o??d,b=Fe(null),k=Fe(null),l=Fe(null),g=Fe(null),m=Fe(u);m.current=u;let E=Fe(c);E.current=c;let R=Ve(p=>{l.current!==p&&(l.current=p,E.current?.(p))},[]),w=Ve(()=>{if(typeof MediaStream>"u")return null;k.current||(k.current=new MediaStream);let p=b.current;return p&&p.srcObject!==k.current&&(p.srcObject=k.current),k.current},[]),h=Ve(p=>{let P=b.current;if(!P)return;let v=P.play();!v||typeof v.then!="function"||v.then(()=>{P.muted||R(!0)}).catch(M=>{let H=M instanceof Error?M.name:String(M);if(H==="AbortError"){Dt(`play() aborted (${p}); retrying in ${Dr}ms`),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{g.current=null,h(`${p}:retry`)},Dr);return}if(H==="NotAllowedError"){Dt(`play() blocked pending a user gesture (${p})`),R(!1);return}Dt(`play() failed (${p})`,M)})},[R]),C=Ve(p=>{let P=w();if(P){for(let v of P.getAudioTracks())v!==p&&P.removeTrack(v);p&&!P.getAudioTracks().includes(p)&&P.addTrack(p),p&&h("track-attach"),m.current?.(p)}},[w,h]),T=Ve(()=>{let p=b.current;p&&(w(),p.muted=!1,h("gesture"),Oe(),R(!0))},[w,h,R]);Fo(r,()=>({unlock:T,get unlocked(){return l.current===!0},get element(){return b.current}}),[T]);let x=Ve(p=>{b.current=p,p&&(p.setAttribute("playsinline",""),p.setAttribute("webkit-playsinline",""),w()),f?.(p)},[w,f]),U=s!==void 0;return Ot(()=>{if(U){C(s??null);return}if(!y)return;let p=y.stream(n),P=()=>{let I=k.current;return I?I.getAudioTracks()[0]??null:null},v=I=>{if(I!==P()&&(C(I),I)){let N=()=>{P()===I&&C(null)};I.addEventListener("ended",N)}},M=p.track;M&&M.readyState==="live"&&v(M);let H=p.on("track",I=>{I&&I.readyState!=="live"||v(I)}),V=setInterval(()=>{let I=p.track;I&&I.readyState==="live"&&v(I)},Ho);return()=>{H(),clearInterval(V)}},[y,n,U,s,C]),Ot(()=>qo(()=>{Oe(),l.current===!0&&h("foreground")}),[h]),Ot(()=>()=>{g.current&&clearTimeout(g.current)},[]),Bo("audio",{ref:x,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),Wo=ut;import{forwardRef as jo,useCallback as qe,useEffect as Vr,useImperativeHandle as Ko,useRef as ye}from"react";import{observePageLifecycle as $o,sessionFailureFromMediaError as Xo,sharedCaptureController as zo}from"@urun-sh/core";import{jsx as Go}from"react/jsx-runtime";var Fr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function ct(...e){console.debug("[voice]",...e)}var lt=jo(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=Fr,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:f,onError:d,onMicStream:y,onTrack:b,onUnlockChange:k,capture:l}=t,g=pe(),m=o??g,E=ye(null),R=ye(null),w=ye(null),h=ye([]),C=ye(!1),T=ye(f);T.current=f;let x=ye(d);x.current=d;let U=ye(y);U.current=y;let p=qe(N=>{C.current!==N&&(C.current=N,T.current?.(N))},[]),P=qe(()=>{for(let N of h.current)N();h.current=[],w.current?.release(),w.current=null,R.current&&(R.current=null,U.current?.(null))},[]),v=qe(async()=>{let N=w.current;if(N){let B=await N.update(i);return R.current=N.stream,U.current?.(N.stream),B}let W=await(l??zo()).claim("audio",i);w.current=W,h.current=[W.onTrack((B,G)=>{R.current=G,U.current?.(G),C.current&&m?.stream(n).attach(B).catch(Y=>ct("mic re-attach after one-capture re-acquire failed",Y))}),W.onLost(B=>{w.current=null,h.current=[],R.current=null,U.current?.(null),p(!1),x.current?.(B)})],R.current=W.stream,U.current?.(W.stream);let J=W.track;if(!J)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return J},[l,i,m,n,p]),M=qe(async()=>{P(),p(!1),await m?.stream(n).detach().catch(()=>{})},[m,n,P,p]),H=qe(async()=>{if(!m)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");E.current?.unlock();let N;try{N=await v()}catch(J){P();let B=Xo(J,m.status);throw x.current?.(B),B}m.connect?.();let F;for(let J=1;J<=u;J++)try{await m.whenLive(a!==void 0?{timeout:a}:void 0),await m.stream(n).attach(N),p(!0);return}catch(B){F=B,ct(`start attempt ${J}/${u} failed`,B),J<u&&await new Promise(G=>setTimeout(G,c))}P(),p(!1);let W=F instanceof Error?F:new Error(String(F??"voice start failed"));throw x.current?.(W),W},[m,n,a,u,c,v,P,p]);Ko(r,()=>({start:H,stop:M,unlock:()=>E.current?.unlock(),get active(){return C.current},get micStream(){return R.current},get audio(){return E.current}}),[H,M]);let V=ye(!1),I=qe(async()=>{if(!m||!C.current||V.current)return;let N=R.current?.getAudioTracks()[0]??null;if(N&&N.readyState==="live"){try{await m.stream(n).attach(N)}catch(F){ct("foreground mic re-assert failed (will retry on next pass)",F)}return}V.current=!0;try{let F=await v();await m.stream(n).attach(F)}catch(F){let W=F instanceof Error?F:new Error(String(F));ct("foreground mic re-acquire failed",W),x.current?.(W)}finally{V.current=!1}},[m,n,v]);return Vr(()=>{let N=()=>{I()};return m&&typeof m.onRecovery=="function"?m.onRecovery(N):$o(N)},[m,I]),Vr(()=>P,[P]),s?Go(ut,{ref:E,session:m,stream:n,onTrack:b,onUnlockChange:k}):null}),Jo=lt;import{forwardRef as Qo,useEffect as es,useImperativeHandle as ts,useRef as qr,useState as rs}from"react";import{useEffect as Yo,useState as Zo}from"react";var Vt={level:0,speaking:!1};function Ft(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=Zo(Vt);return Yo(()=>{if(!e){i(Vt);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),b=setInterval(()=>{f.getByteTimeDomainData(d);let k=0;for(let g=0;g<d.length;g++){let m=(d[g]-128)/128;k+=m*m}let l=Math.sqrt(k/d.length);i(g=>{let m=l>n;return Math.abs(g.level-l)<.005&&g.speaking===m?g:{level:l,speaking:m}})},o);return()=>{clearInterval(b),c.disconnect(),i(Vt)}},[e,r,o,n]),s}import{Fragment as is,jsx as dt,jsxs as as}from"react/jsx-runtime";var ns={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},os={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},ss=Qo(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:y}=t,b=pe(),k=o??b,l=qr(null),[g,m]=rs(null),E=qr(d);E.current=d;let{level:R,speaking:w}=Ft(a?g:null);return ts(r,()=>({start:()=>{let h=l.current;return h?h.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>l.current?.stop()??Promise.resolve(),get active(){return l.current?.active??!1},get micStream(){return l.current?.micStream??null}}),[]),es(()=>{!i||!k||l.current?.start().catch(()=>{})},[i,k]),as(is,{children:[dt(lt,{ref:l,session:k,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...y!==void 0?{capture:y}:{},onActiveChange:c,onError:f,onMicStream:h=>{m(h),E.current?.(h)}}),a?dt("span",{className:u,style:ns,"data-urun-mic":"","data-urun-mic-active":g?"true":"false","data-urun-mic-speaking":w?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(R*100)/100,children:dt("span",{style:os,children:dt("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(R*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{captureStillFromVideo as us,sessionFailureFromMediaError as cs,sharedCaptureController as ls}from"@urun-sh/core";import{forwardRef as Wr,useCallback as me,useEffect as qt,useImperativeHandle as ds,useRef as re,useState as $e}from"react";import{jsx as Ee,jsxs as Hr}from"react/jsx-runtime";var Br={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Ht(...e){console.debug("[camera]",...e)}function ps(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function ms(){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 jr=Wr(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:y=!1,className:b,videoClassName:k,onActiveChange:l,onError:g,onStream:m,onTrack:E,children:R,capture:w,flipControl:h="auto",flipControlClassName:C,onDevices:T}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let x=i?"user":a?"environment":u??"environment",U=pe(),p=o??U,P=re(null),v=re(null),M=re(null),H=re([]),V=re(null),I=re(!1),N=re(!1),F=re(x),[W,J]=$e(x),[B,G]=$e(!1),[Y,j]=$e(null),[q,$]=$e(!1),[le]=$e(ps),ne=re(l);ne.current=l;let Z=re(g);Z.current=g;let ke=re(m);ke.current=m;let z=re(E);z.current=E;let Q=re(T);Q.current=T;let X=me(O=>{I.current!==O&&(I.current=O,G(O),ne.current?.(O))},[]);qt(()=>{if(!B){j(null);return}let O=!1,D=()=>{ms().then(ae=>{O||(j(ae),ae&&Q.current?.(ae))})};D();let ie=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof ie?.addEventListener=="function"?(ie.addEventListener("devicechange",D),()=>{O=!0,ie.removeEventListener?.("devicechange",D)}):()=>{O=!0}},[B]);let ee=me(O=>{let D=P.current;D&&(D.muted=!0,D.defaultMuted=!0,D.setAttribute("muted",""),D.setAttribute("playsinline",""),D.setAttribute("webkit-playsinline",""),D.srcObject=O,O&&D.play()?.catch?.(ie=>Ht("preview play() failed",ie)))},[]),te=me(()=>{N.current=!1,V.current?.(),V.current=null;for(let O of H.current)O();H.current=[],M.current?.release(),M.current=null,v.current&&(v.current=null,ke.current?.(null),z.current?.(null)),ee(null)},[ee]),S=me((O,D)=>{V.current?.(),v.current=D,ee(D),ke.current?.(D);let ie=()=>{v.current===D&&(Ht("camera track ended (device removed or permission revoked)"),te(),X(!1))};O.addEventListener("ended",ie),V.current=()=>O.removeEventListener("ended",ie)},[ee,te,X]),L=me(async O=>{let D=n!==!1;if(D&&!p)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let ie={...Br,...s,facingMode:O},ae;try{let ue=M.current;if(ue)ae=await ue.update(ie);else{let He=await(w??ls()).claim("video",ie);if(M.current=He,H.current=[He.onTrack((We,sn)=>{S(We,sn),I.current&&(!D||!p||p.stream(n).attachVideo(We).then(()=>z.current?.(We)).catch(an=>Ht("camera re-publish after one-capture re-acquire failed",an)))}),He.onLost(We=>{M.current=null,H.current=[],te(),X(!1),Z.current?.(We)})],!He.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ae=He.track}}catch(ue){let Me=cs(ue,p?.status);throw Z.current?.(Me),Me}F.current=O,J(O),S(ae,M.current?.stream??new MediaStream([ae]));try{D&&p&&(p.connect?.(),await p.whenLive(d!==void 0?{timeout:d}:void 0),await p.stream(n).attachVideo(ae)),N.current=D?n:!1}catch(ue){te(),X(!1);let Me=ue instanceof Error?ue:new Error(String(ue));throw Z.current?.(Me),Me}z.current?.(ae),X(!0)},[p,n,s,d,w,S,te,X]),_=me(O=>L(O?.facingMode??F.current),[L]),K=me(async O=>{let D=N.current===n;I.current&&F.current===O&&D||await L(O)},[L,n]),se=me(()=>L(F.current==="environment"?"user":"environment"),[L]),fe=me(async()=>{te(),X(!1),n!==!1&&await p?.stream(n).detachVideo().catch(()=>{})},[p,n,te,X]),A=me(async O=>{let D=P.current;if(!D)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await us(D,O)},[]);ds(r,()=>({start:_,stop:fe,flip:se,setFacingMode:K,capturePhoto:A,get active(){return I.current},get facingMode(){return F.current},get stream(){return v.current},get element(){return P.current}}),[_,fe,se,K,A]);let ge=re(K);if(ge.current=K,qt(()=>{c&&(n!==!1&&!p||ge.current(x).catch(()=>{}))},[c,p,x,n]),qt(()=>te,[te]),!y)return null;let Ae=f==="auto"?W==="user":f,he=B&&(h===!0||h==="auto"&&le&&(Y?.length??0)>1),Se=()=>{q||($(!0),se().catch(()=>{}).finally(()=>$(!1)))};return Hr("div",{className:b,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":W,children:[Ee("video",{ref:P,className:k,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Ae?{transform:"scaleX(-1)"}:{}}}),he?Ee("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Se,disabled:q,className:C,style:C?{opacity:q?.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:q?.6:1},children:Hr("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:[Ee("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),Ee("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),Ee("path",{d:"M14.5 10.5v1.6h-1.6"}),Ee("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),Ee("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,R]})}),fs=Wr(function({preview:t=!0,...r},o){return Ee(jr,{ref:o,...r,visible:t,autoStart:!1})});import{cameraCaptureAvailable as gs,normalizeReferenceImage as hs,referenceImageErrorMessage as Ss}from"@urun-sh/core";import{useCallback as Xe,useEffect as vs,useRef as Wt,useState as ze}from"react";function ys(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=ze(null),[a,u]=ze(null),[c,f]=ze(!1),[d,y]=ze(null),[b]=ze(gs),k=Wt(n);k.current=n;let l=Wt(null),g=Wt(0),m=Xe(C=>{l.current&&URL.revokeObjectURL(l.current),l.current=C?URL.createObjectURL(new Blob([C.bytes],{type:C.type})):null,u(l.current),i(C),k.current?.(C)},[]);vs(()=>()=>{g.current++,l.current&&URL.revokeObjectURL(l.current),l.current=null},[]);let E=Xe(async C=>{let T=++g.current;f(!0),y(null);try{let x=await C();if(g.current!==T)return;m(x)}catch(x){if(g.current!==T)return;y(Ss(x))}finally{g.current===T&&f(!1)}},[m]),R=Xe(C=>E(()=>hs(C,{maxSize:t,type:r,quality:o,source:"file"})),[E,t,r,o]),w=Xe(C=>E(()=>C.capturePhoto({maxSize:t,type:r,quality:o})),[E,t,r,o]),h=Xe(()=>{g.current++,y(null),f(!1),m(null)},[m]);return{reference:s,previewUrl:a,pick:R,capture:w,clear:h,busy:c,error:d,cameraAvailable:b}}import{useEffect as ks,useState as bs}from"react";function Rs(e,t){let[r,o]=bs(null);return ks(()=>{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 xs}from"react";import{useEffect as Ts,useMemo as ws}from"react";import{createStore as Cs}from"zustand/vanilla";import{useStore as Es}from"zustand";var Ps=()=>{};function Bt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=Cs(()=>({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):Ps,u=(c=>Es(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 Je(e,t){let r=ws(()=>Bt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return Ts(()=>r.bind(),[r]),r}function Us(e,t,r){let n=Je(e,t)(r??(a=>a)),s=xs(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 As,useState as Ms}from"react";var we=200;function Pe(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Ge(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function jt(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 Kt(e,t,r={}){let o=r.cap??200,[n,s]=Ms([]);return As(()=>{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=>Pe(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}import{jsx as pt,jsxs as Ye}from"react/jsx-runtime";function _s({session:e,name:t,cap:r,className:o}){let n=Kt(e,t,{cap:r});return Ye("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[Ye("div",{className:"urun-stream-tail-meta",children:[pt("code",{children:t}),Ye("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),pt("div",{className:"urun-stream-tail-log",children:n.length===0?Ye("span",{className:"urun-stream-tail-empty",children:["Waiting for ",pt("code",{children:t})," messages\u2026"]}):n.map((s,i)=>Ye("div",{className:"urun-stream-tail-line",children:[pt("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Ge(s.payload)]},`${s.at}-${i}`))})]})}import{useCallback as Ns,useState as Kr}from"react";import{jsx as xe,jsxs as mt}from"react/jsx-runtime";function ft({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=Kr(""),[i,a]=Kr(null),u=Ns(()=>{let c=jt(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return mt("div",{className:"urun-doc-patch",children:[xe("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),mt("div",{className:"urun-doc-patch-actions",children:[xe("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?xe("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function Is({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Je(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return mt("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[mt("div",{className:"urun-doc-panel-meta",children:[xe("code",{children:t}),xe("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),xe("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?xe(ft,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}import{useEffect as Ls,useState as Os}from"react";import{jsx as Ze,jsxs as Xr}from"react/jsx-runtime";function $r(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Ds({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=Os([]);return Ls(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>Pe(u,{at:Date.now(),direction:"in",text:$r(Ge(a))},r))}):void 0),[e,t,r]),Xr("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[Ze(ft,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>Pe(u,{at:Date.now(),direction:"out",text:$r(a)},r))}}),Ze("div",{className:"urun-control-sender-log",children:n.length===0?Ze("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>Xr("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[Ze("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",Ze("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}import{useEffect as Vs,useState as Fs}from"react";import{jsx as gt,jsxs as Hs}from"react/jsx-runtime";function qs({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=Fs([]),a=t.join(","),u=r.join(",");return Vs(()=>{if(i([]),!e)return;let c=(d,y)=>i(b=>Pe(b,{at:Date.now(),kind:d,text:y},o)),f=[];f.push(e.onPhase(d=>c("phase",`phase \u2192 ${d.name}`)));for(let d of t){let y=e.stream(d);f.push(y.on("track",b=>c("track",`${d}: ${b?"track arrived":"track ended"}`)))}for(let d of r){let y=e.doc(d);f.push(y.on("change",()=>c("doc",`${d} changed`)))}return()=>f.forEach(d=>d())},[e,a,u,o]),gt("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?gt("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)=>Hs("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[gt("span",{className:"urun-event-spine-kind",children:c.kind})," ",gt("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${f}`))})}import{describeSessionPhase as ri,isWakingPhase as ni}from"@urun-sh/core";import{useEffect as Ws,useState as Bs}from"react";function ce(e){let[t,r]=Bs(e?.phase??null);return Ws(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as zs}from"@urun-sh/core";import{useEffect as js,useRef as Ks,useState as $s}from"react";import{isWakingPhase as Xs}from"@urun-sh/core";function $t(e){let t=ce(e),r=Xs(t?.name),o=Ks(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]=$s(s);return js(()=>{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 Js,jsx as zr,jsxs as Jr}from"react/jsx-runtime";function Xt({session:e,render:t,className:r}){let o=$t(e);return!o.waking||!o.phase?null:zr("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):Jr(Js,{children:[zr("span",{className:"urun-session-waking-label",children:zs(o.phase)})," ",Jr("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as Zs,useState as Qs}from"react";import{useEffect as Gr,useRef as Gs,useState as Yr}from"react";var Ys={event:null,elapsedMs:0};function zt(e,t){let[r,o]=Yr(null),n=Gs(0);Gr(()=>{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]=Yr(0);return Gr(()=>{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}:Ys}import{jsx as Zr,jsxs as Qr}from"react/jsx-runtime";var ei={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 ti(e){let[t,r]=Qs(!1);return Zs(()=>{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 Jt({session:e,stream:t,videoElement:r,render:o,className:n}){let s=zt(e,t),i=ti(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return Zr("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):Qr("div",{className:"urun-activation-overlay-card",children:[Zr("span",{className:"urun-activation-overlay-copy",children:a.hint??ei[u]})," ",Qr("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as Ue,jsxs as Gt}from"react/jsx-runtime";var oi={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function si({session:e,className:t}){let r=ce(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 Gt("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[Ue("span",{className:"urun-session-status-dot","data-phase":o}),Ue("span",{className:"urun-session-status-label",children:oi[o]}),n?Ue("span",{className:"urun-session-status-detail",children:n}):null]})}function ii({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=ce(e);if(s?.name==="live")return Gt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,Ue(Jt,{session:e})]});let i=r?r(s):Ue("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&ni(s.name)?Ue(Xt,{session:e}):s&&s.name!=="idle"?ri(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return Gt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?Ue("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as ai,useState as ui}from"react";import{jsx as di}from"react/jsx-runtime";function en(e){return ce(e)?.endsAt??null}function ci(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 li({session:e,urgentMs:t=6e4,className:r}){let n=en(e)?.getTime()??null,[s,i]=ui(()=>n===null?null:Math.max(0,n-Date.now()));if(ai(()=>{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=ci(s);return di("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 tn,jsxs as fi}from"react/jsx-runtime";var pi=new Set(["expired","ended","error"]);function mi({session:e,onNewSession:t,children:r,className:o}){let n=ce(e);if(!n||!pi.has(n.name))return null;let s=r?r(n):tn("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 fi("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?tn("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}import{useEffect as rn,useMemo as gi,useState as nn}from"react";import{jsx as ht,jsxs as vi}from"react/jsx-runtime";function Yt(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 on(e){let t=gi(()=>e?e.doc("control"):null,[e]),[r,o]=nn(()=>t?Yt(t.get("idle")):null);return rn(()=>{if(!t){o(null);return}return o(Yt(t.get("idle"))),t.on("change",()=>o(Yt(t.get("idle"))))},[t]),r}function hi(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Si({session:e,onStillHere:t,className:r}){let o=on(e),n=o?.deadlineEpochS??null,[s,i]=nn(null);if(rn(()=>{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 ht("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:vi("div",{className:"urun-idle-warning-card",children:[ht("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),ht("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${hi(s)} due to inactivity.`:"This session will end soon due to inactivity."}),ht("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useContext as yi,useEffect as ki,useState as bi}from"react";import{prewake as Ri}from"@urun-sh/core";function Ci(e){let t=yi(_e),[r,o]=bi(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 ki(()=>{if(!a||!u||!n||!s)return;let y=!1,b=()=>{Ri({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:f,authProvider:d}).then(l=>{y||o(l)}).catch(()=>{})};b();let k=setInterval(b,Math.max(1,i)*1e3);return()=>{y=!0,clearInterval(k)}},[n,s,i,a,u,c,f,d]),r}import{describeSessionPhase as Ll,isWakingPhase as Ol}from"@urun-sh/core";export{ut as Audio,jr as Camera,So as ComponentRenderer,Br as DEFAULT_CAMERA_CONSTRAINTS,we as DEFAULT_LOG_CAP,Fr as DEFAULT_VOICE_CONSTRAINTS,ft as DocPatchForm,Oo as Image,Ao as ImageFrame,Uo as ImageFrameSchema,No as MetricsPanel,_o as MetricsPanelSchema,ss as Mic,hn as OPERATOR_CHORD_LABEL,gn as OPERATOR_TOKEN_STORAGE_KEY,ko as ProgressCard,yo as ProgressCardSchema,fo as ReprojectedVideo,eo as Session,Co as StatusBadge,bo as StatusBadgeSchema,wo as TextStream,To as TextStreamSchema,Jt as UrunActivationOverlay,Wo as UrunAudio,St as UrunAuthProvider,fs as UrunCamera,Ds as UrunControlSender,Is as UrunDocPanel,Be as UrunErrorBoundary,qs as UrunEventSpine,Si as UrunIdleWarning,un as UrunJwtProvider,Tn as UrunProvider,li as UrunSessionClock,mi as UrunSessionEnded,ii as UrunSessionGate,si as UrunSessionStatus,Xt as UrunSessionWaking,_s as UrunStreamTail,Jo as UrunVoice,De as Video,lt as Voice,Qe as authMode,Bt as createDocStore,Ll as describeSessionPhase,Ge as formatPayload,ot as getUrunAudioContext,Ol as isWakingPhase,jt as parseJsonObject,Pe as pushCapped,rr as readOperatorToken,ho as registerComponent,Oe as resumeUrunAudioContext,de as urunPublicEnv,zt as useActivation,In as useApp,$n as useChat,Wn as useCompletion,kt as useConfirmOnLeave,Je as useDocStore,Lr as useImageFrame,Yn as useInputPresence,Or as useMetricsPanel,yt as useOperatorOverride,xr as useProgressCard,ys as useReferenceImage,Vn as useRequest,to as useSession,Us as useSessionDoc,en as useSessionEndsAt,on as useSessionIdle,ce as useSessionPhase,Rs as useSessionTrack,$t as useSessionWake,Ar as useStatusBadge,Kt as useStreamMessages,Nr as useTextStream,Ft as useUrunAudioLevel,vt as useUrunAuth,Ci as useUrunPrewake,pn as usesWorkOSAuth};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urun-sh/react",
3
- "version": "0.2.51",
3
+ "version": "0.2.53",
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.51",
56
+ "@urun-sh/core": "^0.2.53",
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",