@urun-sh/react 0.2.6 → 0.2.8
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 +11 -0
- package/README.md +50 -0
- package/dist/auth.mjs +1 -1
- package/dist/{chunk-QAEWAWV4.mjs → chunk-WF2OBDSX.mjs} +1 -0
- package/dist/index.d.mts +80 -39
- package/dist/index.d.ts +80 -39
- package/dist/index.js +2 -9
- package/dist/index.mjs +2 -9
- package/dist/next-workos.js +1 -0
- package/dist/next-workos.mjs +2 -1
- package/dist/styles.css +13 -0
- package/dist/{index.css → video.css} +1 -1
- package/dist/video.d.mts +38 -0
- package/dist/video.d.ts +38 -0
- package/dist/video.js +10 -0
- package/dist/video.mjs +10 -0
- package/dist/workos.js +1 -0
- package/dist/workos.mjs +2 -1
- package/package.json +8 -3
- package/dist/chunk-SSZO4I6Y.mjs +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
- **BREAKING**: `UrunVideo` moved from the root entry to the `./video` subpath
|
|
6
|
+
— import it as `import { UrunVideo } from '@urun-sh/react/video'`. video.js
|
|
7
|
+
is an optional peer dependency, but the root entry statically imported
|
|
8
|
+
`video.js/dist/video-js.css` (kept external), so every consumer WITHOUT
|
|
9
|
+
video.js installed failed module resolution at build time on ANY
|
|
10
|
+
`@urun-sh/react` import. The root entry graph is now video.js-free (guarded
|
|
11
|
+
by `videojs-optional-peer.test.ts` and `pack:check`); only apps that render
|
|
12
|
+
video install video.js and import from `@urun-sh/react/video`.
|
|
13
|
+
|
|
3
14
|
## 0.2.5
|
|
4
15
|
|
|
5
16
|
- Session workbench building blocks: generic, composable debug/steer components
|
package/README.md
CHANGED
|
@@ -78,6 +78,56 @@ For other auth providers, use `UrunAuthProvider` with a `getAccessToken` functio
|
|
|
78
78
|
- `session.doc(name)` — returns a render-safe synced document with `.get()`, `.set(patch)` (write `desired.*` state), and lifecycle events.
|
|
79
79
|
- `registerComponent()` and built-in components — optional generative UI support.
|
|
80
80
|
|
|
81
|
+
## Session docs as a zustand store
|
|
82
|
+
|
|
83
|
+
Session docs (prompts, desired state, status) read like a plain [zustand](https://github.com/pmndrs/zustand) store. The doc — a vanilla Yjs document synced by the platform — stays the single source of truth: the store is a read-projection plus write-through, never an authoritative copy. Selectors give granular re-renders; `set(patch)` deep-merges through the doc's field-granular CRDT write path, so concurrent writers to different subkeys both survive.
|
|
84
|
+
|
|
85
|
+
```tsx
|
|
86
|
+
import { useDocStore } from '@urun-sh/react'
|
|
87
|
+
|
|
88
|
+
type ControlDoc = {
|
|
89
|
+
session?: { status?: string }
|
|
90
|
+
desired?: { prompt?: { text?: string } }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function PromptControls({ session }) {
|
|
94
|
+
const useControl = useDocStore<ControlDoc>(session, 'control')
|
|
95
|
+
|
|
96
|
+
// Status field read — re-renders ONLY when the selected value changes.
|
|
97
|
+
const status = useControl((s) => s.doc.session?.status ?? 'idle')
|
|
98
|
+
|
|
99
|
+
// Desired-state write — write-through to the doc (field-granular merge).
|
|
100
|
+
const set = useControl((s) => s.set)
|
|
101
|
+
|
|
102
|
+
return (
|
|
103
|
+
<div>
|
|
104
|
+
<span>{status}</span>
|
|
105
|
+
<button onClick={() => set({ desired: { prompt: { text: 'a sunset' } } })}>
|
|
106
|
+
Set prompt
|
|
107
|
+
</button>
|
|
108
|
+
</div>
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Outside React (or with a session handle you own), bind a store directly to a doc:
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
import { createDocStore } from '@urun-sh/react'
|
|
117
|
+
|
|
118
|
+
const control = createDocStore<ControlDoc>(session.doc('control'))
|
|
119
|
+
control.getState().doc.session?.status
|
|
120
|
+
control.subscribe((s) => console.log(s.doc))
|
|
121
|
+
control.set({ desired: { prompt: { text: 'dawn' } } })
|
|
122
|
+
control.unbind() // detach the projection; the session still owns the doc
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Notes:
|
|
126
|
+
|
|
127
|
+
- Selectors that return objects/arrays should use zustand's `useShallow` (`zustand/react/shallow`) — each doc change produces a fresh snapshot tree.
|
|
128
|
+
- Arrays in the doc are read as plain snapshots. Do not read-modify-write an array through `set` for append-only logs; use the platform's stream/text primitives for growing data.
|
|
129
|
+
- `useSessionDoc(session, key, selector?)` also accepts a selector for one-off reads.
|
|
130
|
+
|
|
81
131
|
## Styling
|
|
82
132
|
|
|
83
133
|
Import the package CSS when using built-in components:
|
package/dist/auth.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
function n(e){return e&&e.trim()?e.trim():void 0}function r(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return n(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return n(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return n(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return n(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return n(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return n(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return n(typeof process<"u"?process.env?.[e]:void 0)}}function o(){let e=r("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||r("VERCEL_ENV")==="production"?"workos":r("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function t(){return o()==="workos"}export{o as authMode,r as urunPublicEnv,t as usesWorkOSAuth};
|
|
@@ -1 +1,2 @@
|
|
|
1
|
+
"use client"
|
|
1
2
|
import{createContext as t,useContext as u,useMemo as s}from"react";import{jsx as i}from"react/jsx-runtime";var r=t(null);function c({getAccessToken:e,children:n}){let o=s(()=>({getAccessToken:e}),[e]);return i(r.Provider,{value:o,children:n})}var U=c;function p(){return u(r)}export{c as a,U as b,p as c};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
2
|
import * as react from 'react';
|
|
3
3
|
import { RefObject, ReactNode, Component, ErrorInfo, ComponentType } from 'react';
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
export { App as AppInterface, AppOptions, SessionDocument, Session as SessionInterface, SessionPhase, SessionPhaseName, SessionStream } from '@urun-sh/core';
|
|
4
|
+
import { SessionInterface, SessionDocument, SessionStream, SessionPhase, SessionStatus, RuntimeAvailability } from '@urun-sh/core';
|
|
5
|
+
export { App as AppInterface, AppOptions, RuntimeAvailability, SessionDocument, Session as SessionInterface, SessionPhase, SessionPhaseName, SessionStream, describeSessionPhase, isWakingPhase } from '@urun-sh/core';
|
|
7
6
|
import { ZodSchema, z } from 'zod';
|
|
8
|
-
import
|
|
7
|
+
import { StoreApi } from 'zustand/vanilla';
|
|
9
8
|
|
|
10
9
|
interface UrunProviderProps {
|
|
11
10
|
baseUrl: string;
|
|
@@ -61,6 +60,11 @@ declare function UrunAuthProvider({ getAccessToken, children }: UrunAuthProvider
|
|
|
61
60
|
declare const UrunJwtProvider: typeof UrunAuthProvider;
|
|
62
61
|
declare function useUrunAuth(): UrunAuthContextValue | null;
|
|
63
62
|
|
|
63
|
+
type UrunAuthMode = 'workos' | 'jwt';
|
|
64
|
+
declare function urunPublicEnv(name: string): string | undefined;
|
|
65
|
+
declare function authMode(): UrunAuthMode;
|
|
66
|
+
declare function usesWorkOSAuth(): boolean;
|
|
67
|
+
|
|
64
68
|
type Unsubscribe = () => void;
|
|
65
69
|
type ReactSessionDocument<T = Record<string, unknown>> = Omit<SessionDocument, 'get' | 'set' | 'on'> & {
|
|
66
70
|
get(): T;
|
|
@@ -331,39 +335,6 @@ declare function useMetricsPanel(props: MetricsPanelProps): {
|
|
|
331
335
|
};
|
|
332
336
|
declare function MetricsPanel(props: MetricsPanelProps): react_jsx_runtime.JSX.Element;
|
|
333
337
|
|
|
334
|
-
interface UrunVideoProps {
|
|
335
|
-
|
|
336
|
-
track?: MediaStreamTrack | null;
|
|
337
|
-
|
|
338
|
-
stream?: MediaStream | null;
|
|
339
|
-
|
|
340
|
-
name?: string;
|
|
341
|
-
|
|
342
|
-
src?: string;
|
|
343
|
-
|
|
344
|
-
type?: string;
|
|
345
|
-
|
|
346
|
-
className?: string;
|
|
347
|
-
|
|
348
|
-
videoClassName?: string;
|
|
349
|
-
|
|
350
|
-
poster?: string;
|
|
351
|
-
|
|
352
|
-
controls?: boolean;
|
|
353
|
-
|
|
354
|
-
autoPlay?: boolean;
|
|
355
|
-
|
|
356
|
-
muted?: boolean;
|
|
357
|
-
|
|
358
|
-
onVideoElement?: (el: HTMLVideoElement | null) => void;
|
|
359
|
-
|
|
360
|
-
onPlayerReady?: (player: Player | null) => void;
|
|
361
|
-
|
|
362
|
-
children?: ReactNode;
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
declare const UrunVideo: react.ForwardRefExoticComponent<UrunVideoProps & react.RefAttributes<HTMLVideoElement>>;
|
|
366
|
-
|
|
367
338
|
interface UrunAudioStreamSource {
|
|
368
339
|
|
|
369
340
|
readonly track: MediaStreamTrack | null;
|
|
@@ -419,6 +390,8 @@ interface UrunVoiceSessionSource {
|
|
|
419
390
|
}): Promise<void>;
|
|
420
391
|
|
|
421
392
|
readonly status?: SessionStatus;
|
|
393
|
+
|
|
394
|
+
onRecovery?(hook: () => void): () => void;
|
|
422
395
|
}
|
|
423
396
|
|
|
424
397
|
interface UrunVoiceHandle {
|
|
@@ -598,6 +571,40 @@ interface WorkbenchSession {
|
|
|
598
571
|
|
|
599
572
|
declare function useSessionTrack(session: WorkbenchSession | null, name: string): MediaStreamTrack | null;
|
|
600
573
|
|
|
574
|
+
type DeepPartial<T> = {
|
|
575
|
+
[K in keyof T]?: T[K] extends readonly unknown[] ? T[K] : T[K] extends object ? DeepPartial<T[K]> : T[K];
|
|
576
|
+
};
|
|
577
|
+
|
|
578
|
+
type DocPatch<T> = DeepPartial<T> & Record<string, unknown>;
|
|
579
|
+
|
|
580
|
+
interface DocState<T = Record<string, unknown>> {
|
|
581
|
+
|
|
582
|
+
doc: T;
|
|
583
|
+
|
|
584
|
+
synced: boolean;
|
|
585
|
+
|
|
586
|
+
set: (patch: DocPatch<T>) => void;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
interface DocStore<T = Record<string, unknown>> extends Pick<StoreApi<DocState<T>>, 'getState' | 'getInitialState' | 'subscribe'> {
|
|
590
|
+
|
|
591
|
+
<U>(selector: (state: DocState<T>) => U): U;
|
|
592
|
+
|
|
593
|
+
(): DocState<T>;
|
|
594
|
+
|
|
595
|
+
set(patch: DocPatch<T>): void;
|
|
596
|
+
|
|
597
|
+
bind(): () => void;
|
|
598
|
+
|
|
599
|
+
unbind(): void;
|
|
600
|
+
}
|
|
601
|
+
interface CreateDocStoreOptions {
|
|
602
|
+
|
|
603
|
+
bind?: boolean;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
declare function createDocStore<T = Record<string, unknown>>(doc: WorkbenchDocSource | null, options?: CreateDocStoreOptions): DocStore<T>;
|
|
607
|
+
|
|
601
608
|
interface UseSessionDocResult<T> {
|
|
602
609
|
|
|
603
610
|
snapshot: T | null;
|
|
@@ -608,6 +615,11 @@ interface UseSessionDocResult<T> {
|
|
|
608
615
|
}
|
|
609
616
|
|
|
610
617
|
declare function useSessionDoc<T = Record<string, unknown>>(session: WorkbenchSession | null, key: string): UseSessionDocResult<T>;
|
|
618
|
+
declare function useSessionDoc<T = Record<string, unknown>, U = unknown>(session: WorkbenchSession | null, key: string, selector: (state: DocState<T>) => U): U;
|
|
619
|
+
|
|
620
|
+
type DocHost = Pick<WorkbenchSession, 'doc'>;
|
|
621
|
+
|
|
622
|
+
declare function useDocStore<T = Record<string, unknown>>(session: DocHost | null, key: string): DocStore<T>;
|
|
611
623
|
|
|
612
624
|
declare const DEFAULT_LOG_CAP = 200;
|
|
613
625
|
|
|
@@ -698,6 +710,7 @@ interface UrunEventSpineProps {
|
|
|
698
710
|
declare function UrunEventSpine({ session, trackNames, docKeys, cap, className, }: UrunEventSpineProps): react_jsx_runtime.JSX.Element;
|
|
699
711
|
|
|
700
712
|
declare function useSessionPhase(session: WorkbenchSession | null): SessionPhase | null;
|
|
713
|
+
|
|
701
714
|
interface UrunSessionStatusProps {
|
|
702
715
|
session: WorkbenchSession | null;
|
|
703
716
|
className?: string;
|
|
@@ -710,9 +723,37 @@ interface UrunSessionGateProps {
|
|
|
710
723
|
children: ReactNode;
|
|
711
724
|
|
|
712
725
|
fallback?: (phase: SessionPhase | null) => ReactNode;
|
|
726
|
+
|
|
727
|
+
onStartOver?: () => void;
|
|
728
|
+
className?: string;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
declare function UrunSessionGate({ session, children, fallback, onStartOver, className, }: UrunSessionGateProps): react_jsx_runtime.JSX.Element;
|
|
732
|
+
|
|
733
|
+
interface SessionWake {
|
|
734
|
+
|
|
735
|
+
waking: boolean;
|
|
736
|
+
|
|
737
|
+
phase: SessionPhase | null;
|
|
738
|
+
|
|
739
|
+
state?: RuntimeAvailability['state'];
|
|
740
|
+
|
|
741
|
+
reason?: string;
|
|
742
|
+
|
|
743
|
+
since?: number;
|
|
744
|
+
|
|
745
|
+
seconds: number;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
declare function useSessionWake(session: WorkbenchSession | null): SessionWake;
|
|
749
|
+
|
|
750
|
+
interface UrunSessionWakingProps {
|
|
751
|
+
session: WorkbenchSession | null;
|
|
752
|
+
|
|
753
|
+
render?: (wake: SessionWake) => ReactNode;
|
|
713
754
|
className?: string;
|
|
714
755
|
}
|
|
715
756
|
|
|
716
|
-
declare function
|
|
757
|
+
declare function UrunSessionWaking({ session, render, className }: UrunSessionWakingProps): react_jsx_runtime.JSX.Element | null;
|
|
717
758
|
|
|
718
|
-
export { type ChatMessage, type ChatRole, ComponentRenderer, DEFAULT_CAMERA_CONSTRAINTS, DEFAULT_LOG_CAP, DEFAULT_VOICE_CONSTRAINTS, DocPatchForm, ImageFrame, ImageFrameSchema, type JsonObjectParse, MetricsPanel, MetricsPanelSchema, ProgressCard, ProgressCardSchema, type ReactApp, type ReactSession, type ReactSessionDocument, type ReactSessionStream, type RegisteredComponent, type RequestCapableSession, type RequestStream, type SessionRequestOptions, type SpineEntry, StatusBadge, StatusBadgeSchema, type StreamMessageEntry, TextStream, TextStreamSchema, type UrunAccessToken, type UrunAccessTokenProvider, UrunAudio, type UrunAudioHandle, type UrunAudioLevel, type UrunAudioProps, type UrunAudioSessionSource, type UrunAudioStreamSource, type UrunAuthContextValue, UrunAuthProvider, type UrunAuthProviderProps, UrunCamera, type UrunCameraFacing, type UrunCameraHandle, type UrunCameraProps, type UrunCameraSessionSource, type UrunCameraStreamSource, UrunControlSender, type UrunControlSenderProps, UrunDocPanel, type UrunDocPanelProps, UrunErrorBoundary, UrunEventSpine, type UrunEventSpineProps, UrunJwtProvider, UrunProvider, UrunSessionGate, type UrunSessionGateProps, UrunSessionStatus, type UrunSessionStatusProps,
|
|
759
|
+
export { type ChatMessage, type ChatRole, ComponentRenderer, type CreateDocStoreOptions, DEFAULT_CAMERA_CONSTRAINTS, DEFAULT_LOG_CAP, DEFAULT_VOICE_CONSTRAINTS, type DeepPartial, type DocPatch, DocPatchForm, type DocState, type DocStore, ImageFrame, ImageFrameSchema, type JsonObjectParse, MetricsPanel, MetricsPanelSchema, ProgressCard, ProgressCardSchema, type ReactApp, type ReactSession, type ReactSessionDocument, type ReactSessionStream, type RegisteredComponent, type RequestCapableSession, type RequestStream, type SessionRequestOptions, type SessionWake, type SpineEntry, StatusBadge, StatusBadgeSchema, type StreamMessageEntry, TextStream, TextStreamSchema, type UrunAccessToken, type UrunAccessTokenProvider, UrunAudio, type UrunAudioHandle, type UrunAudioLevel, type UrunAudioProps, type UrunAudioSessionSource, type UrunAudioStreamSource, type UrunAuthContextValue, type UrunAuthMode, UrunAuthProvider, type UrunAuthProviderProps, UrunCamera, type UrunCameraFacing, type UrunCameraHandle, type UrunCameraProps, type UrunCameraSessionSource, type UrunCameraStreamSource, UrunControlSender, type UrunControlSenderProps, UrunDocPanel, type UrunDocPanelProps, UrunErrorBoundary, UrunEventSpine, type UrunEventSpineProps, UrunJwtProvider, UrunProvider, UrunSessionGate, type UrunSessionGateProps, UrunSessionStatus, type UrunSessionStatusProps, UrunSessionWaking, type UrunSessionWakingProps, UrunStreamTail, type UrunStreamTailProps, UrunVoice, type UrunVoiceHandle, type UrunVoiceProps, type UrunVoiceSessionSource, type UrunVoiceStreamSource, type UseChatOptions, type UseChatResult, type UseCompletionOptions, type UseCompletionResult, type UseRequestOptions, type UseRequestResult, type UseSessionDocResult, type UseStreamMessagesOptions, type UseUrunAudioLevelOptions, type WorkbenchDocSource, type WorkbenchSession, type WorkbenchStreamSource, authMode, createDocStore, formatPayload, getUrunAudioContext, parseJsonObject, pushCapped, registerComponent, resumeUrunAudioContext, urunPublicEnv, useApp, useChat, useCompletion, useDocStore, useImageFrame, useMetricsPanel, useProgressCard, useRequest, useSessionDoc, useSessionPhase, useSessionTrack, useSessionWake, useStatusBadge, useStreamMessages, useTextStream, useUrunAudioLevel, useUrunAuth, usesWorkOSAuth };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
2
|
import * as react from 'react';
|
|
3
3
|
import { RefObject, ReactNode, Component, ErrorInfo, ComponentType } from 'react';
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
export { App as AppInterface, AppOptions, SessionDocument, Session as SessionInterface, SessionPhase, SessionPhaseName, SessionStream } from '@urun-sh/core';
|
|
4
|
+
import { SessionInterface, SessionDocument, SessionStream, SessionPhase, SessionStatus, RuntimeAvailability } from '@urun-sh/core';
|
|
5
|
+
export { App as AppInterface, AppOptions, RuntimeAvailability, SessionDocument, Session as SessionInterface, SessionPhase, SessionPhaseName, SessionStream, describeSessionPhase, isWakingPhase } from '@urun-sh/core';
|
|
7
6
|
import { ZodSchema, z } from 'zod';
|
|
8
|
-
import
|
|
7
|
+
import { StoreApi } from 'zustand/vanilla';
|
|
9
8
|
|
|
10
9
|
interface UrunProviderProps {
|
|
11
10
|
baseUrl: string;
|
|
@@ -61,6 +60,11 @@ declare function UrunAuthProvider({ getAccessToken, children }: UrunAuthProvider
|
|
|
61
60
|
declare const UrunJwtProvider: typeof UrunAuthProvider;
|
|
62
61
|
declare function useUrunAuth(): UrunAuthContextValue | null;
|
|
63
62
|
|
|
63
|
+
type UrunAuthMode = 'workos' | 'jwt';
|
|
64
|
+
declare function urunPublicEnv(name: string): string | undefined;
|
|
65
|
+
declare function authMode(): UrunAuthMode;
|
|
66
|
+
declare function usesWorkOSAuth(): boolean;
|
|
67
|
+
|
|
64
68
|
type Unsubscribe = () => void;
|
|
65
69
|
type ReactSessionDocument<T = Record<string, unknown>> = Omit<SessionDocument, 'get' | 'set' | 'on'> & {
|
|
66
70
|
get(): T;
|
|
@@ -331,39 +335,6 @@ declare function useMetricsPanel(props: MetricsPanelProps): {
|
|
|
331
335
|
};
|
|
332
336
|
declare function MetricsPanel(props: MetricsPanelProps): react_jsx_runtime.JSX.Element;
|
|
333
337
|
|
|
334
|
-
interface UrunVideoProps {
|
|
335
|
-
|
|
336
|
-
track?: MediaStreamTrack | null;
|
|
337
|
-
|
|
338
|
-
stream?: MediaStream | null;
|
|
339
|
-
|
|
340
|
-
name?: string;
|
|
341
|
-
|
|
342
|
-
src?: string;
|
|
343
|
-
|
|
344
|
-
type?: string;
|
|
345
|
-
|
|
346
|
-
className?: string;
|
|
347
|
-
|
|
348
|
-
videoClassName?: string;
|
|
349
|
-
|
|
350
|
-
poster?: string;
|
|
351
|
-
|
|
352
|
-
controls?: boolean;
|
|
353
|
-
|
|
354
|
-
autoPlay?: boolean;
|
|
355
|
-
|
|
356
|
-
muted?: boolean;
|
|
357
|
-
|
|
358
|
-
onVideoElement?: (el: HTMLVideoElement | null) => void;
|
|
359
|
-
|
|
360
|
-
onPlayerReady?: (player: Player | null) => void;
|
|
361
|
-
|
|
362
|
-
children?: ReactNode;
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
declare const UrunVideo: react.ForwardRefExoticComponent<UrunVideoProps & react.RefAttributes<HTMLVideoElement>>;
|
|
366
|
-
|
|
367
338
|
interface UrunAudioStreamSource {
|
|
368
339
|
|
|
369
340
|
readonly track: MediaStreamTrack | null;
|
|
@@ -419,6 +390,8 @@ interface UrunVoiceSessionSource {
|
|
|
419
390
|
}): Promise<void>;
|
|
420
391
|
|
|
421
392
|
readonly status?: SessionStatus;
|
|
393
|
+
|
|
394
|
+
onRecovery?(hook: () => void): () => void;
|
|
422
395
|
}
|
|
423
396
|
|
|
424
397
|
interface UrunVoiceHandle {
|
|
@@ -598,6 +571,40 @@ interface WorkbenchSession {
|
|
|
598
571
|
|
|
599
572
|
declare function useSessionTrack(session: WorkbenchSession | null, name: string): MediaStreamTrack | null;
|
|
600
573
|
|
|
574
|
+
type DeepPartial<T> = {
|
|
575
|
+
[K in keyof T]?: T[K] extends readonly unknown[] ? T[K] : T[K] extends object ? DeepPartial<T[K]> : T[K];
|
|
576
|
+
};
|
|
577
|
+
|
|
578
|
+
type DocPatch<T> = DeepPartial<T> & Record<string, unknown>;
|
|
579
|
+
|
|
580
|
+
interface DocState<T = Record<string, unknown>> {
|
|
581
|
+
|
|
582
|
+
doc: T;
|
|
583
|
+
|
|
584
|
+
synced: boolean;
|
|
585
|
+
|
|
586
|
+
set: (patch: DocPatch<T>) => void;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
interface DocStore<T = Record<string, unknown>> extends Pick<StoreApi<DocState<T>>, 'getState' | 'getInitialState' | 'subscribe'> {
|
|
590
|
+
|
|
591
|
+
<U>(selector: (state: DocState<T>) => U): U;
|
|
592
|
+
|
|
593
|
+
(): DocState<T>;
|
|
594
|
+
|
|
595
|
+
set(patch: DocPatch<T>): void;
|
|
596
|
+
|
|
597
|
+
bind(): () => void;
|
|
598
|
+
|
|
599
|
+
unbind(): void;
|
|
600
|
+
}
|
|
601
|
+
interface CreateDocStoreOptions {
|
|
602
|
+
|
|
603
|
+
bind?: boolean;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
declare function createDocStore<T = Record<string, unknown>>(doc: WorkbenchDocSource | null, options?: CreateDocStoreOptions): DocStore<T>;
|
|
607
|
+
|
|
601
608
|
interface UseSessionDocResult<T> {
|
|
602
609
|
|
|
603
610
|
snapshot: T | null;
|
|
@@ -608,6 +615,11 @@ interface UseSessionDocResult<T> {
|
|
|
608
615
|
}
|
|
609
616
|
|
|
610
617
|
declare function useSessionDoc<T = Record<string, unknown>>(session: WorkbenchSession | null, key: string): UseSessionDocResult<T>;
|
|
618
|
+
declare function useSessionDoc<T = Record<string, unknown>, U = unknown>(session: WorkbenchSession | null, key: string, selector: (state: DocState<T>) => U): U;
|
|
619
|
+
|
|
620
|
+
type DocHost = Pick<WorkbenchSession, 'doc'>;
|
|
621
|
+
|
|
622
|
+
declare function useDocStore<T = Record<string, unknown>>(session: DocHost | null, key: string): DocStore<T>;
|
|
611
623
|
|
|
612
624
|
declare const DEFAULT_LOG_CAP = 200;
|
|
613
625
|
|
|
@@ -698,6 +710,7 @@ interface UrunEventSpineProps {
|
|
|
698
710
|
declare function UrunEventSpine({ session, trackNames, docKeys, cap, className, }: UrunEventSpineProps): react_jsx_runtime.JSX.Element;
|
|
699
711
|
|
|
700
712
|
declare function useSessionPhase(session: WorkbenchSession | null): SessionPhase | null;
|
|
713
|
+
|
|
701
714
|
interface UrunSessionStatusProps {
|
|
702
715
|
session: WorkbenchSession | null;
|
|
703
716
|
className?: string;
|
|
@@ -710,9 +723,37 @@ interface UrunSessionGateProps {
|
|
|
710
723
|
children: ReactNode;
|
|
711
724
|
|
|
712
725
|
fallback?: (phase: SessionPhase | null) => ReactNode;
|
|
726
|
+
|
|
727
|
+
onStartOver?: () => void;
|
|
728
|
+
className?: string;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
declare function UrunSessionGate({ session, children, fallback, onStartOver, className, }: UrunSessionGateProps): react_jsx_runtime.JSX.Element;
|
|
732
|
+
|
|
733
|
+
interface SessionWake {
|
|
734
|
+
|
|
735
|
+
waking: boolean;
|
|
736
|
+
|
|
737
|
+
phase: SessionPhase | null;
|
|
738
|
+
|
|
739
|
+
state?: RuntimeAvailability['state'];
|
|
740
|
+
|
|
741
|
+
reason?: string;
|
|
742
|
+
|
|
743
|
+
since?: number;
|
|
744
|
+
|
|
745
|
+
seconds: number;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
declare function useSessionWake(session: WorkbenchSession | null): SessionWake;
|
|
749
|
+
|
|
750
|
+
interface UrunSessionWakingProps {
|
|
751
|
+
session: WorkbenchSession | null;
|
|
752
|
+
|
|
753
|
+
render?: (wake: SessionWake) => ReactNode;
|
|
713
754
|
className?: string;
|
|
714
755
|
}
|
|
715
756
|
|
|
716
|
-
declare function
|
|
757
|
+
declare function UrunSessionWaking({ session, render, className }: UrunSessionWakingProps): react_jsx_runtime.JSX.Element | null;
|
|
717
758
|
|
|
718
|
-
export { type ChatMessage, type ChatRole, ComponentRenderer, DEFAULT_CAMERA_CONSTRAINTS, DEFAULT_LOG_CAP, DEFAULT_VOICE_CONSTRAINTS, DocPatchForm, ImageFrame, ImageFrameSchema, type JsonObjectParse, MetricsPanel, MetricsPanelSchema, ProgressCard, ProgressCardSchema, type ReactApp, type ReactSession, type ReactSessionDocument, type ReactSessionStream, type RegisteredComponent, type RequestCapableSession, type RequestStream, type SessionRequestOptions, type SpineEntry, StatusBadge, StatusBadgeSchema, type StreamMessageEntry, TextStream, TextStreamSchema, type UrunAccessToken, type UrunAccessTokenProvider, UrunAudio, type UrunAudioHandle, type UrunAudioLevel, type UrunAudioProps, type UrunAudioSessionSource, type UrunAudioStreamSource, type UrunAuthContextValue, UrunAuthProvider, type UrunAuthProviderProps, UrunCamera, type UrunCameraFacing, type UrunCameraHandle, type UrunCameraProps, type UrunCameraSessionSource, type UrunCameraStreamSource, UrunControlSender, type UrunControlSenderProps, UrunDocPanel, type UrunDocPanelProps, UrunErrorBoundary, UrunEventSpine, type UrunEventSpineProps, UrunJwtProvider, UrunProvider, UrunSessionGate, type UrunSessionGateProps, UrunSessionStatus, type UrunSessionStatusProps,
|
|
759
|
+
export { type ChatMessage, type ChatRole, ComponentRenderer, type CreateDocStoreOptions, DEFAULT_CAMERA_CONSTRAINTS, DEFAULT_LOG_CAP, DEFAULT_VOICE_CONSTRAINTS, type DeepPartial, type DocPatch, DocPatchForm, type DocState, type DocStore, ImageFrame, ImageFrameSchema, type JsonObjectParse, MetricsPanel, MetricsPanelSchema, ProgressCard, ProgressCardSchema, type ReactApp, type ReactSession, type ReactSessionDocument, type ReactSessionStream, type RegisteredComponent, type RequestCapableSession, type RequestStream, type SessionRequestOptions, type SessionWake, type SpineEntry, StatusBadge, StatusBadgeSchema, type StreamMessageEntry, TextStream, TextStreamSchema, type UrunAccessToken, type UrunAccessTokenProvider, UrunAudio, type UrunAudioHandle, type UrunAudioLevel, type UrunAudioProps, type UrunAudioSessionSource, type UrunAudioStreamSource, type UrunAuthContextValue, type UrunAuthMode, UrunAuthProvider, type UrunAuthProviderProps, UrunCamera, type UrunCameraFacing, type UrunCameraHandle, type UrunCameraProps, type UrunCameraSessionSource, type UrunCameraStreamSource, UrunControlSender, type UrunControlSenderProps, UrunDocPanel, type UrunDocPanelProps, UrunErrorBoundary, UrunEventSpine, type UrunEventSpineProps, UrunJwtProvider, UrunProvider, UrunSessionGate, type UrunSessionGateProps, UrunSessionStatus, type UrunSessionStatusProps, UrunSessionWaking, type UrunSessionWakingProps, UrunStreamTail, type UrunStreamTailProps, UrunVoice, type UrunVoiceHandle, type UrunVoiceProps, type UrunVoiceSessionSource, type UrunVoiceStreamSource, type UseChatOptions, type UseChatResult, type UseCompletionOptions, type UseCompletionResult, type UseRequestOptions, type UseRequestResult, type UseSessionDocResult, type UseStreamMessagesOptions, type UseUrunAudioLevelOptions, type WorkbenchDocSource, type WorkbenchSession, type WorkbenchStreamSource, authMode, createDocStore, formatPayload, getUrunAudioContext, parseJsonObject, pushCapped, registerComponent, resumeUrunAudioContext, urunPublicEnv, useApp, useChat, useCompletion, useDocStore, useImageFrame, useMetricsPanel, useProgressCard, useRequest, useSessionDoc, useSessionPhase, useSessionTrack, useSessionWake, useStatusBadge, useStreamMessages, useTextStream, useUrunAudioLevel, useUrunAuth, usesWorkOSAuth };
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,2 @@
|
|
|
1
|
-
"use strict";var mt=Object.create;var Ue=Object.defineProperty;var ft=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,vt=Object.prototype.hasOwnProperty;var St=(e,r)=>{for(var t in r)Ue(e,t,{get:r[t],enumerable:!0})},mr=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of gt(r))!vt.call(e,o)&&o!==t&&Ue(e,o,{get:()=>r[o],enumerable:!(n=ft(r,o))||n.enumerable});return e};var yt=(e,r,t)=>(t=e!=null?mt(ht(e)):{},mr(r||!e||!e.__esModule?Ue(t,"default",{value:e,enumerable:!0}):t,e)),bt=e=>mr(Ue({},"__esModule",{value:!0}),e);var qt={};St(qt,{ComponentRenderer:()=>Nr,DEFAULT_CAMERA_CONSTRAINTS:()=>dr,DEFAULT_LOG_CAP:()=>re,DEFAULT_VOICE_CONSTRAINTS:()=>cr,DocPatchForm:()=>Re,ImageFrame:()=>jr,ImageFrameSchema:()=>Dr,MetricsPanel:()=>Br,MetricsPanelSchema:()=>Fr,ProgressCard:()=>Lr,ProgressCardSchema:()=>_r,StatusBadge:()=>Ir,StatusBadgeSchema:()=>Or,TextStream:()=>Vr,TextStreamSchema:()=>qr,UrunAudio:()=>Oe,UrunAuthProvider:()=>Ze,UrunCamera:()=>rt,UrunControlSender:()=>it,UrunDocPanel:()=>st,UrunErrorBoundary:()=>ue,UrunEventSpine:()=>ut,UrunJwtProvider:()=>Sr,UrunProvider:()=>br,UrunSessionGate:()=>lt,UrunSessionStatus:()=>ct,UrunStreamTail:()=>ot,UrunVideo:()=>Gr,UrunVoice:()=>Yr,authMode:()=>ve,formatPayload:()=>ge,getUrunAudioContext:()=>Te,parseJsonObject:()=>je,pushCapped:()=>Z,registerComponent:()=>Ar,resumeUrunAudioContext:()=>Le,urunPublicEnv:()=>X,useApp:()=>xr,useChat:()=>Er,useCompletion:()=>Pr,useImageFrame:()=>sr,useMetricsPanel:()=>ar,useProgressCard:()=>tr,useRequest:()=>Cr,useSessionDoc:()=>De,useSessionPhase:()=>We,useSessionTrack:()=>nt,useStatusBadge:()=>nr,useStreamMessages:()=>Be,useTextStream:()=>or,useUrunAudioLevel:()=>tt,useUrunAuth:()=>we,usesWorkOSAuth:()=>hr});module.exports=bt(qt);var le=require("react");var fr=require("react"),he=require("react/jsx-runtime"),ue=class extends fr.Component{constructor(r){super(r),this.state={error:null}}static getDerivedStateFromError(r){return{error:r}}componentDidCatch(r,t){console.error("[urun] Error caught by UrunErrorBoundary:",r,t)}render(){if(this.state.error){let{fallback:r}=this.props;return typeof r=="function"?r(this.state.error):r||(0,he.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,he.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,he.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var gr=require("react"),Ee=(0,gr.createContext)(null);function ne(e){return e&&e.trim()?e.trim():void 0}function X(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return ne(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return ne(typeof process<"u"?process.env?.[e]:void 0)}}function ve(){let e=X("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||X("VERCEL_ENV")==="production"?"workos":X("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function hr(){return ve()==="workos"}var ce=require("react"),yr=require("react/jsx-runtime"),vr=(0,ce.createContext)(null);function Ze({getAccessToken:e,children:r}){let t=(0,ce.useMemo)(()=>({getAccessToken:e}),[e]);return(0,yr.jsx)(vr.Provider,{value:t,children:r})}var Sr=Ze;function we(){return(0,ce.useContext)(vr)}var Ae=require("react/jsx-runtime");function br({baseUrl:e,orgId:r,appId:t,jwt:n,authProvider:o,fallback:a,children:i}){let[d,u]=(0,le.useState)(),c=we(),h=X("NEXT_PUBLIC_SESSION_TOKEN")??X("NEXT_PUBLIC_URUN_JWT"),l=ve(),f=l==="workos"&&!n,R=n??(l==="jwt"?h:void 0)??d,x=o??X("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),T=f&&!R,b=(0,le.useMemo)(()=>({appId:t,baseUrl:e,orgId:r,jwt:R,getAccessToken:f?c?.getAccessToken:void 0,authProvider:x}),[t,c,e,x,R,r,f]);return(0,le.useEffect)(()=>{if(!f||!c)return;let g=!1,v=c;async function S(){try{let k=await v.getAccessToken();g||u(k??void 0)}catch{g||u(void 0)}}S();let U=window.setInterval(()=>{S()},6e4);return()=>{g=!0,window.clearInterval(U)}},[c,f]),(0,Ae.jsx)(ue,{fallback:a,children:T?(0,Ae.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,Ae.jsx)(Ee.Provider,{value:b,children:i})})}var G=require("react"),kr=require("@urun-sh/core");function kt(e,r){return`${e}:${JSON.stringify(r??{})}`}var Ye=class{constructor(r,t){this._doc=r;this._notify=t;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(r,t){return this._doc.get(r,t)}set(r){this._doc.set(r),this._notify()}on(r,t){return this._doc.on(r,n=>t(n))}get synced(){return this._doc.synced}onSynced(r){return this._doc.onSynced(()=>{r(),this._notify()})}text(r){let t=this._doc.text(r),n=this._notify;return{append(o){t.append(o),n()},toString:()=>t.toString(),get length(){return t.length},on:(o,a)=>t.on(o,i=>{a(i),n()})}}dispose(){this._unsubscribeChange()}},Qe=class{constructor(r,t){this._stream=r;this._notify=t;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(r){return this._stream.attach(r)}attachVideo(r){return this._stream.attachVideo(r)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(r){return this._stream.seek(r)}chunks(r){return this._stream.chunks(r)}onSeeked(r){return this._stream.onSeeked(r)}on(r,t){return this._stream.on(r,t)}messages(){return this._stream.messages()}emit(r,t){return this._stream.emit(r,t)}dispose(){this._unsubscribeTrack()}},er=class{constructor(r,t){this._session=r;this._notify=t;this._unsubscribePhase=this._session.onPhase(()=>this._notify())}_session;_notify;_docs=new Map;_streams=new Map;_unsubscribePhase;_disposed=!1;get disposed(){return this._disposed}get id(){return this._session.id}get phase(){return this._session.phase}get status(){return this._session.status}onPhase(r){return this._session.onPhase(r)}whenLive(r){return this._session.whenLive(r)}request(r,t){return this._session.request(r,t)}requestStream(r,t){return this._session.requestStream(r,t)}complete(r,t){return this._session.complete(r,t)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}doc(r){let t=this._docs.get(r);return t||(t=new Ye(this._session.doc(r),this._notify),this._docs.set(r,t)),t}stream(r){let t=this._streams.get(r);return t||(t=new Qe(this._session.stream(r),this._notify),this._streams.set(r,t)),t}disconnect(){this._disposed=!0;for(let r of this._docs.values())r.dispose();for(let r of this._streams.values())r.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._session.disconnect(),this._notify()}};function xr(){let e=(0,G.useContext)(Ee);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,r]=(0,G.useReducer)(o=>o+1,0),t=(0,G.useRef)(new Map),n=(0,G.useMemo)(()=>(0,kr.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider]);return(0,G.useMemo)(()=>new Proxy({},{get(o,a){if(typeof a=="string")return i=>{let d=kt(a,i),u=t.current.get(d);if(u&&!u.disposed)return u;let c=new er(n[a](i),r);return t.current.set(d,c),c}}}),[n])}var q=require("react");function de(e){let r=e;if(!r||typeof r.request!="function"||typeof r.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 r}function xt(e){return e instanceof Error?e:new Error(String(e))}function Cr(e,r){let t=(0,q.useMemo)(()=>de(e),[e]),[n,o]=(0,q.useState)(void 0),[a,i]=(0,q.useState)(null),[d,u]=(0,q.useState)(!1),c=(0,q.useRef)(r);c.current=r;let h=(0,q.useRef)(0),l=(0,q.useRef)(null),f=(0,q.useRef)(!0);(0,q.useEffect)(()=>(f.current=!0,()=>{f.current=!1,l.current?.abort()}),[]);let R=(0,q.useCallback)(async b=>{l.current?.abort();let g=new AbortController;l.current=g;let v=++h.current,S=()=>f.current&&h.current===v;S()&&(u(!0),i(null));try{let U=await t.request(b,{...c.current,signal:g.signal});return S()&&(o(U),u(!1),c.current?.onSuccess?.(U)),U}catch(U){let k=xt(U);throw S()&&(i(k),u(!1),c.current?.onError?.(k)),k}},[t]),x=(0,q.useCallback)(b=>{R(b).catch(()=>{})},[R]),T=(0,q.useCallback)(()=>{h.current++,l.current?.abort(),l.current=null,o(void 0),i(null),u(!1)},[]);return{mutate:x,mutateAsync:R,data:n,error:a,isPending:d,reset:T}}var V=require("react");function Tr(e){return e instanceof Error?e:new Error(String(e))}var Ct=e=>typeof e=="string"?e:String(e);function Pr(e,r){let t=(0,V.useMemo)(()=>de(e),[e]),[n,o]=(0,V.useState)(""),[a,i]=(0,V.useState)(!1),[d,u]=(0,V.useState)(null),c=(0,V.useRef)(r);c.current=r;let h=(0,V.useRef)(0),l=(0,V.useRef)(null),f=(0,V.useRef)(!0);(0,V.useEffect)(()=>(f.current=!0,()=>{f.current=!1,l.current?.cancel(),l.current=null}),[]);let R=(0,V.useCallback)(()=>{h.current++,l.current?.cancel(),l.current=null,f.current&&i(!1)},[]),x=(0,V.useCallback)(async T=>{l.current?.cancel();let b=++h.current,g=()=>f.current&&h.current===b,v=c.current,S=v?.parseChunk??Ct,U=v?.buildPayload??(m=>({prompt:m}));g()&&(o(""),u(null),i(!0));let{parseChunk:k,buildPayload:z,onFinish:N,onError:s,...p}=v??{},y="",C;try{C=t.requestStream(U(T),p),l.current=C}catch(m){let w=Tr(m);g()&&(u(w),i(!1),v?.onError?.(w));return}try{for await(let m of C){if(h.current!==b)break;y+=S(m),g()&&o(y)}g()&&(i(!1),v?.onFinish?.(y))}catch(m){let w=Tr(m);g()&&(u(w),i(!1),v?.onError?.(w))}finally{l.current===C&&(l.current=null)}},[t]);return{completion:n,complete:x,stop:R,isStreaming:a,error:d}}var L=require("react");function Rr(e){return e instanceof Error?e:new Error(String(e))}var Tt=e=>typeof e=="string"?e:String(e),Ur=0;function rr(e){return Ur+=1,`${e}-${Ur}`}function Er(e,r){let t=(0,L.useMemo)(()=>de(e),[e]),[n,o]=(0,L.useState)(()=>(r?.initialMessages??[]).map(S=>({id:S.id??rr("msg"),role:S.role,content:S.content}))),[a,i]=(0,L.useState)(""),[d,u]=(0,L.useState)(!1),[c,h]=(0,L.useState)(null),l=(0,L.useRef)(r);l.current=r;let f=(0,L.useRef)(n);f.current=n;let R=(0,L.useRef)(a);R.current=a;let x=(0,L.useRef)(0),T=(0,L.useRef)(null),b=(0,L.useRef)(!0);(0,L.useEffect)(()=>(b.current=!0,()=>{b.current=!1,T.current?.cancel(),T.current=null}),[]);let g=(0,L.useCallback)(()=>{x.current++,T.current?.cancel(),T.current=null,b.current&&u(!1)},[]),v=(0,L.useCallback)(async S=>{let U=S===void 0,k=(U?R.current:S)??"";if(!k.trim())return;T.current?.cancel();let N=++x.current,s=()=>b.current&&x.current===N,p=l.current,y=p?.parseChunk??Tt,C={id:rr("msg"),role:"user",content:k},m={id:rr("msg"),role:"assistant",content:""},w=[...f.current,C].map(_=>({role:_.role,content:_.content})),P=[...f.current,C,m];f.current=P,o(P),U&&i(""),h(null),u(!0);let J=p?.buildPayload??(_=>({messages:_})),{initialMessages:Je,parseChunk:Xe,buildPayload:Ge,onFinish:Ke,onError:dt,...M}=p??{},D=_=>{o(H=>H.map(F=>F.id===m.id?{...F,content:_}:F))},ee="",j;try{j=t.requestStream(J(w),M),T.current=j}catch(_){let H=Rr(_);s()&&(h(H),u(!1),p?.onError?.(H));return}try{for await(let _ of j){if(x.current!==N)break;ee+=y(_),s()&&D(ee)}s()&&(u(!1),p?.onFinish?.({...m,content:ee}))}catch(_){let H=Rr(_);s()&&(h(H),u(!1),p?.onError?.(H))}finally{T.current===j&&(T.current=null)}},[t]);return{messages:n,input:a,setInput:i,sendMessage:v,stop:g,isStreaming:d,error:c}}var wr=new Map;function Ar(e,r,t){if(!t||typeof t.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);wr.set(e,{component:r,schema:t})}function Mr(e,r){let t=wr.get(e);if(!t)return{error:`Unknown component: "${e}"`};let n=t.schema.safeParse(r);return n.success?{Component:t.component,validatedProps:n.data}:{error:`Validation failed for "${e}": ${n.error.message}`}}var oe=require("react/jsx-runtime");function Nr({name:e,props:r,fallback:t}){let n=Mr(e,r);if(n.error)return console.warn(`[urun] ComponentRenderer: ${n.error}`),t?(0,oe.jsx)(oe.Fragment,{children:t}):(0,oe.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,oe.jsx)("span",{className:"urun-component-error-text",children:n.error})});let o=n.Component;return(0,oe.jsx)(o,{...n.validatedProps})}var pe=require("zod"),se=require("react/jsx-runtime"),_r=pe.z.object({step:pe.z.number().min(0),total:pe.z.number().min(1),label:pe.z.string().optional(),variant:pe.z.enum(["default","success","error"]).default("default")});function tr(e){let{step:r,total:t,label:n,variant:o="default"}=e,a=Math.min(r/t*100,100),i=r>=t;return{step:r,total:t,label:n,variant:o,percentage:a,isComplete:i}}function Lr(e){let{step:r,total:t,label:n,variant:o,percentage:a}=tr(e);return(0,se.jsxs)("div",{className:"urun-progress-card","data-variant":o,children:[n&&(0,se.jsx)("div",{className:"urun-progress-label",children:n}),(0,se.jsx)("div",{className:"urun-progress-bar",children:(0,se.jsx)("div",{className:"urun-progress-fill",style:{width:`${a}%`}})}),(0,se.jsxs)("div",{className:"urun-progress-text",children:[r,"/",t]})]})}var Me=require("zod"),Se=require("react/jsx-runtime"),Or=Me.z.object({state:Me.z.enum(["thinking","generating","idle","error"]),message:Me.z.string().optional()}),Pt={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function nr(e){let{state:r,message:t}=e,n=r==="thinking"||r==="generating",o=t??Pt[r]??r;return{state:r,message:o,isActive:n}}function Ir(e){let{state:r,message:t,isActive:n}=nr(e);return(0,Se.jsxs)("span",{className:"urun-status-badge","data-state":r,children:[(0,Se.jsx)("span",{className:`urun-status-indicator${n?" urun-status-pulse":""}`}),(0,Se.jsx)("span",{className:"urun-status-message",children:t})]})}var ye=require("react"),Ne=require("zod"),be=require("react/jsx-runtime"),qr=Ne.z.object({text:Ne.z.string(),streaming:Ne.z.boolean().default(!1)});function or(e){let{text:r,streaming:t=!1}=e,n=r.length===0;return{text:r,streaming:t,isEmpty:n}}function Vr(e){let{text:r,streaming:t}=or(e),n=(0,ye.useRef)(null),o=(0,ye.useRef)(0);return(0,ye.useEffect)(()=>{let a=n.current;a&&r.length!==o.current&&(a.textContent=r,o.current=r.length)},[r]),(0,be.jsxs)("div",{className:"urun-text-stream",children:[(0,be.jsx)("span",{ref:n,className:"urun-text-content"}),t&&(0,be.jsx)("span",{className:"urun-text-cursor"})]})}var ke=require("zod"),xe=require("react/jsx-runtime"),Dr=ke.z.object({src:ke.z.string().url(),alt:ke.z.string().optional(),caption:ke.z.string().optional()});function sr(e){let{src:r,alt:t,caption:n}=e;return{src:r,alt:t??"",caption:n}}function jr(e){let{src:r,alt:t,caption:n}=sr(e);return(0,xe.jsxs)("figure",{className:"urun-image-frame",children:[(0,xe.jsx)("img",{className:"urun-image",src:r,alt:t}),n&&(0,xe.jsx)("figcaption",{className:"urun-image-caption",children:n})]})}var K=require("zod"),me=require("react/jsx-runtime"),Fr=K.z.object({metrics:K.z.array(K.z.object({label:K.z.string(),value:K.z.union([K.z.string(),K.z.number()]),unit:K.z.string().optional()}))});function ar(e){return{metrics:e.metrics.map(t=>({...t,displayValue:t.unit?`${t.value} ${t.unit}`:String(t.value)}))}}function Br(e){let{metrics:r}=ar(e);return(0,me.jsx)("div",{className:"urun-metrics-panel",children:r.map((t,n)=>(0,me.jsxs)("div",{className:"urun-metric-card",children:[(0,me.jsx)("div",{className:"urun-metric-label",children:t.label}),(0,me.jsx)("div",{className:"urun-metric-value",children:t.displayValue})]},n))})}var O=require("react"),Jr=yt(require("video.js")),vn=require("video.js/dist/video-js.css");var fe=require("react");var Ce=require("react"),Rt=require("@urun-sh/core/internal");var Ut=require("react/jsx-runtime"),zr=(0,Ce.createContext)(null);function Hr(e){let r=(0,fe.useContext)(zr);if(!r)throw new Error("useTrack must be used within <SessionProvider> or <UrunProvider>");let[t,n]=(0,fe.useState)(null);return(0,fe.useEffect)(()=>{let o=r.getState()._transport;if(!o)return;let a=o.getTrackByName?.bind(o),i=a?.(e);i&&i.readyState!=="ended"&&n(i);let d=o.on("track",u=>{let c=a?.(e);c&&c.id!==u.id||(n(u),u.addEventListener("ended",()=>{n(null)}))});return()=>{d()}},[e,r]),t}var $=require("react/jsx-runtime");function $r(e){e.posterImage?.hide?.()}var Et=`
|
|
2
|
-
[data-urun-video]{width:100%;height:100%}
|
|
3
|
-
[data-urun-video] .video-js,[data-urun-video] .vjs-tech{width:100%;height:100%}
|
|
4
|
-
[data-urun-video] .vjs-tech{object-fit:contain}
|
|
5
|
-
.urun-video-live.vjs-has-started .vjs-poster,
|
|
6
|
-
.urun-video-live.vjs-has-started .vjs-loading-spinner,
|
|
7
|
-
.urun-video-live.vjs-has-started .vjs-big-play-button{display:none !important}
|
|
8
|
-
.urun-video-live .vjs-poster{background-color:transparent}
|
|
9
|
-
`,Wr="urun-video-critical-css";function wt(){if(typeof document>"u"||document.getElementById(Wr))return;let e=document.createElement("style");e.id=Wr,e.textContent=Et,document.head.appendChild(e)}var At=["playToggle","volumePanel","fullscreenToggle"],Mt=["playToggle","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","remainingTimeDisplay","fullscreenToggle"],Xr=(0,O.forwardRef)(function(r,t){let{track:n,stream:o,src:a,type:i="video/mp4",className:d,videoClassName:u,poster:c,controls:h=!0,autoPlay:l=!0,muted:f=!0,onVideoElement:R,onPlayerReady:x,children:T}=r,b=typeof a=="string"&&a.length>0,g=!b,v=(0,O.useRef)(null),S=(0,O.useRef)(null),[U,k]=(0,O.useState)(!1),z=(0,O.useCallback)(s=>{v.current=s,typeof t=="function"?t(s):t&&(t.current=s),R?.(s)},[t,R]);(0,O.useImperativeHandle)(t,()=>v.current,[]);let N=(0,O.useCallback)(()=>{let s=v.current;if(!s||!s.srcObject&&!s.src)return;f&&(s.muted=!0,s.defaultMuted=!0),s.setAttribute("playsinline",""),s.setAttribute("webkit-playsinline","");let p=s.play();p&&typeof p.then=="function"&&p.then(()=>k(!1)).catch(y=>{(y instanceof Error?y.name:String(y))!=="AbortError"&&k(!0)})},[f]);return(0,O.useEffect)(()=>{if(typeof document>"u")return;let s=v.current;if(!s)return;wt(),f&&(s.muted=!0,s.defaultMuted=!0,s.setAttribute("muted","")),s.autoplay=l,s.setAttribute("playsinline",""),s.setAttribute("webkit-playsinline","");let p=(0,Jr.default)(s,{controls:h,autoplay:l,muted:f,playsinline:!0,preload:"auto",fluid:!1,bigPlayButton:!0,poster:c,userActions:{click:!0,doubleClick:!1,hotkeys:!1},controlBar:{children:g?At:Mt}});g&&p.addClass("urun-video-live");let y=()=>k(!1),C=()=>{p.hasStarted(!0),$r(p),y()},m=()=>{g&&N()};return s.addEventListener("playing",C),s.addEventListener("loadedmetadata",m),g&&s.addEventListener("pause",m),S.current=p,x?.(p),()=>{s.removeEventListener("playing",C),s.removeEventListener("loadedmetadata",m),s.removeEventListener("pause",m),x?.(null),S.current&&(S.current.dispose(),S.current=null)}},[g]),(0,O.useEffect)(()=>{if(!b)return;let s=S.current;if(!s)return;let p=s.tech?.(!0)?.el?.();p&&(p.srcObject=null),s.src({src:a,type:i}),l&&N()},[b,a,i,l,N]),(0,O.useEffect)(()=>{if(!g)return;let s=S.current;if(!s)return;let p=n??null,y=o??null;!y&&p&&(y=new MediaStream([p]));let C=s.tech?.(!0)?.el?.()??v.current;if(!C)return;if(!y){C.srcObject=null,k(!1);return}C.srcObject=y,N();let m=y.getVideoTracks()[0]??p??null,w=()=>{s.hasStarted(!0),$r(s),N()},P=()=>{C.srcObject=null,k(!1)};return m&&(m.addEventListener("unmute",w),m.addEventListener("ended",P),m.muted||w()),()=>{m&&(m.removeEventListener("unmute",w),m.removeEventListener("ended",P))}},[g,n,o,N]),(0,$.jsxs)("div",{className:d,style:{position:"relative",width:"100%",height:"100%"},"data-urun-video":"","data-urun-video-mode":g?"live":"vod",children:[(0,$.jsx)("video",{ref:z,className:["video-js","vjs-default-skin",u].filter(Boolean).join(" "),playsInline:!0}),U&&(0,$.jsx)("button",{type:"button",onClick:N,"aria-label":"Tap to play",style:{position:"absolute",inset:0,zIndex:30,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.6)",border:0,cursor:"pointer",color:"#fff"},children:(0,$.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8,borderRadius:999,border:"1px solid rgba(255,255,255,0.2)",background:"rgba(255,255,255,0.1)",padding:"10px 20px",fontSize:14,fontWeight:500},children:[(0,$.jsx)("svg",{viewBox:"0 0 24 24",fill:"currentColor",width:16,height:16,"aria-hidden":!0,children:(0,$.jsx)("path",{d:"M8 5v14l11-7z"})}),"Tap to play"]})}),T]})}),Nt=(0,O.forwardRef)(function({name:r,...t},n){let o=Hr(r);return(0,$.jsx)(Xr,{ref:n,...t,track:o})}),Gr=(0,O.forwardRef)(function(r,t){return!!r.name&&!r.track&&!r.stream&&!(typeof r.src=="string"&&r.src)?(0,$.jsx)(Nt,{ref:t,...r,name:r.name}):(0,$.jsx)(Xr,{ref:t,...r})});var A=require("react");var _e=null;function _t(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function Te(){if(_e)return _e;let e=_t();return e?(_e=new e,_e):null}function Le(){let e=Te();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var Zr=require("react/jsx-runtime"),Lt=1e3,Kr=200;function ir(...e){console.debug("[urun-audio]",...e)}var Oe=(0,A.forwardRef)(function(r,t){let{session:n,stream:o="audio",track:a,controls:i=!1,className:d,onTrack:u,onUnlockChange:c,onAudioElement:h}=r,l=(0,A.useRef)(null),f=(0,A.useRef)(null),R=(0,A.useRef)(null),x=(0,A.useRef)(null),T=(0,A.useRef)(u);T.current=u;let b=(0,A.useRef)(c);b.current=c;let g=(0,A.useCallback)(s=>{R.current!==s&&(R.current=s,b.current?.(s))},[]),v=(0,A.useCallback)(()=>{if(typeof MediaStream>"u")return null;f.current||(f.current=new MediaStream);let s=l.current;return s&&s.srcObject!==f.current&&(s.srcObject=f.current),f.current},[]),S=(0,A.useCallback)(s=>{let p=l.current;if(!p)return;let y=p.play();!y||typeof y.then!="function"||y.then(()=>{p.muted||g(!0)}).catch(C=>{let m=C instanceof Error?C.name:String(C);if(m==="AbortError"){ir(`play() aborted (${s}); retrying in ${Kr}ms`),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{x.current=null,S(`${s}:retry`)},Kr);return}if(m==="NotAllowedError"){ir(`play() blocked pending a user gesture (${s})`),g(!1);return}ir(`play() failed (${s})`,C)})},[g]),U=(0,A.useCallback)(s=>{let p=v();if(p){for(let y of p.getAudioTracks())y!==s&&p.removeTrack(y);s&&!p.getAudioTracks().includes(s)&&p.addTrack(s),s&&S("track-attach"),T.current?.(s)}},[v,S]),k=(0,A.useCallback)(()=>{let s=l.current;s&&(v(),s.muted=!1,S("gesture"),Le(),g(!0))},[v,S,g]);(0,A.useImperativeHandle)(t,()=>({unlock:k,get unlocked(){return R.current===!0},get element(){return l.current}}),[k]);let z=(0,A.useCallback)(s=>{l.current=s,s&&(s.setAttribute("playsinline",""),s.setAttribute("webkit-playsinline",""),v()),h?.(s)},[v,h]),N=a!==void 0;return(0,A.useEffect)(()=>{if(N){U(a??null);return}if(!n)return;let s=n.stream(o),p=()=>{let P=f.current;return P?P.getAudioTracks()[0]??null:null},y=P=>{if(P!==p()&&(U(P),P)){let J=()=>{p()===P&&U(null)};P.addEventListener("ended",J)}},C=s.track;C&&C.readyState==="live"&&y(C);let m=s.on("track",P=>{P&&P.readyState!=="live"||y(P)}),w=setInterval(()=>{let P=s.track;P&&P.readyState==="live"&&y(P)},Lt);return()=>{m(),clearInterval(w)}},[n,o,N,a,U]),(0,A.useEffect)(()=>()=>{x.current&&clearTimeout(x.current)},[]),(0,Zr.jsx)("audio",{ref:z,className:d,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})});var I=require("react"),ur=require("@urun-sh/core");var Qr=require("react/jsx-runtime"),cr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Ot(...e){console.debug("[urun-voice]",...e)}var Yr=(0,I.forwardRef)(function(r,t){let{session:n,stream:o="audio",constraints:a=cr,connectTimeoutMs:i,attempts:d=3,retryDelayMs:u=1500,onActiveChange:c,onError:h,onMicStream:l,onTrack:f,onUnlockChange:R}=r,x=(0,I.useRef)(null),T=(0,I.useRef)(null),b=(0,I.useRef)(!1),g=(0,I.useRef)(c);g.current=c;let v=(0,I.useRef)(h);v.current=h;let S=(0,I.useRef)(l);S.current=l;let U=(0,I.useCallback)(s=>{b.current!==s&&(b.current=s,g.current?.(s))},[]),k=(0,I.useCallback)(()=>{let s=T.current;if(s){for(let p of s.getTracks())p.stop();T.current=null,S.current?.(null)}},[]),z=(0,I.useCallback)(async()=>{k(),U(!1),await n.stream(o).detach().catch(()=>{})},[n,o,k,U]),N=(0,I.useCallback)(async()=>{x.current?.unlock();let s;try{s=await navigator.mediaDevices.getUserMedia({audio:a,video:!1})}catch(m){let w=(0,ur.sessionFailureFromMediaError)(m,n.status);throw v.current?.(w),w}k(),T.current=s,S.current?.(s);let p=s.getAudioTracks()[0];if(!p){k();let m=(0,ur.sessionFailureFromMediaError)(Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"}),n.status);throw v.current?.(m),m}n.connect?.();let y;for(let m=1;m<=d;m++)try{await n.whenLive(i!==void 0?{timeout:i}:void 0),await n.stream(o).attach(p),U(!0);return}catch(w){y=w,Ot(`start attempt ${m}/${d} failed`,w),m<d&&await new Promise(P=>setTimeout(P,u))}k(),U(!1);let C=y instanceof Error?y:new Error(String(y??"voice start failed"));throw v.current?.(C),C},[n,o,a,i,d,u,k,U]);return(0,I.useImperativeHandle)(t,()=>({start:N,stop:z,unlock:()=>x.current?.unlock(),get active(){return b.current},get micStream(){return T.current},get audio(){return x.current}}),[N,z]),(0,I.useEffect)(()=>k,[k]),(0,Qr.jsx)(Oe,{ref:x,session:n,stream:o,onTrack:f,onUnlockChange:R})});var lr=require("@urun-sh/core"),E=require("react"),Ie=require("react/jsx-runtime"),dr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function et(...e){console.debug("[urun-camera]",...e)}var rt=(0,E.forwardRef)(function(r,t){let{session:n,stream:o="video",constraints:a,facingMode:i="environment",mirror:d="auto",connectTimeoutMs:u,preview:c=!0,className:h,videoClassName:l,onActiveChange:f,onError:R,onStream:x,onTrack:T,children:b}=r,g=(0,E.useRef)(null),v=(0,E.useRef)(null),S=(0,E.useRef)(null),U=(0,E.useRef)(!1),k=(0,E.useRef)(i),[z,N]=(0,E.useState)(i),s=(0,E.useRef)(f);s.current=f;let p=(0,E.useRef)(R);p.current=R;let y=(0,E.useRef)(x);y.current=x;let C=(0,E.useRef)(T);C.current=T;let m=(0,E.useCallback)(M=>{U.current!==M&&(U.current=M,s.current?.(M))},[]),w=(0,E.useCallback)(M=>{let D=g.current;D&&(D.muted=!0,D.srcObject=M,M&&D.play()?.catch?.(ee=>et("preview play() failed",ee)))},[]),P=(0,E.useCallback)(()=>{S.current?.(),S.current=null;let M=v.current;if(M){for(let D of M.getTracks())D.stop();v.current=null,y.current?.(null),C.current?.(null)}w(null)},[w]),J=(0,E.useCallback)(async M=>{let D=v.current,ee=S.current,j;try{j=await navigator.mediaDevices.getUserMedia({video:{...dr,...a,facingMode:M},audio:!1})}catch(F){let te=(0,lr.sessionFailureFromMediaError)(F,n.status);throw p.current?.(te),te}let _=j.getVideoTracks()[0];if(!_){for(let te of j.getTracks())te.stop();let F=(0,lr.sessionFailureFromMediaError)(Object.assign(new Error("no camera video track"),{name:"NotFoundError"}),n.status);throw p.current?.(F),F}v.current=j,k.current=M,N(M),w(j),y.current?.(j);let H=()=>{v.current===j&&(et("camera track ended (device removed or permission revoked)"),P(),m(!1))};_.addEventListener("ended",H),S.current=()=>_.removeEventListener("ended",H);try{n.connect?.(),await n.whenLive(u!==void 0?{timeout:u}:void 0),await n.stream(o).attachVideo(_)}catch(F){_.removeEventListener("ended",H);for(let pt of j.getTracks())pt.stop();v.current===j&&(v.current=D,S.current=ee,w(D),y.current?.(D));let te=F instanceof Error?F:new Error(String(F));throw p.current?.(te),te}if(D&&D!==j){ee?.();for(let F of D.getTracks())F.stop()}C.current?.(_),m(!0)},[n,o,a,u,w,P,m]),Je=(0,E.useCallback)(M=>J(M?.facingMode??k.current),[J]),Xe=(0,E.useCallback)(async M=>{U.current&&k.current===M||await J(M)},[J]),Ge=(0,E.useCallback)(()=>J(k.current==="environment"?"user":"environment"),[J]),Ke=(0,E.useCallback)(async()=>{P(),m(!1),await n.stream(o).detachVideo().catch(()=>{})},[n,o,P,m]);return(0,E.useImperativeHandle)(t,()=>({start:Je,stop:Ke,flip:Ge,setFacingMode:Xe,get active(){return U.current},get facingMode(){return k.current},get stream(){return v.current},get element(){return g.current}}),[Je,Ke,Ge,Xe]),(0,E.useEffect)(()=>P,[P]),c?(0,Ie.jsxs)("div",{className:h,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":z,children:[(0,Ie.jsx)("video",{ref:g,className:l,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...(d==="auto"?z==="user":d)?{transform:"scaleX(-1)"}:{}}}),b]}):null});var qe=require("react");var pr={level:0,speaking:!1};function tt(e,r={}){let{fftSize:t=512,intervalMs:n=100,speakingThreshold:o=.02}=r,[a,i]=(0,qe.useState)(pr);return(0,qe.useEffect)(()=>{if(!e){i(pr);return}let d=Te();if(!d||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,h;try{c=d.createMediaStreamSource(u),h=d.createAnalyser(),h.fftSize=t,c.connect(h)}catch{return}let l=new Uint8Array(h.fftSize),R=setInterval(()=>{h.getByteTimeDomainData(l);let x=0;for(let b=0;b<l.length;b++){let g=(l[b]-128)/128;x+=g*g}let T=Math.sqrt(x/l.length);i(b=>{let g=T>o;return Math.abs(b.level-T)<.005&&b.speaking===g?b:{level:T,speaking:g}})},n);return()=>{clearInterval(R),c.disconnect(),i(pr)}},[e,t,n,o]),a}var Ve=require("react");function nt(e,r){let[t,n]=(0,Ve.useState)(null);return(0,Ve.useEffect)(()=>{if(!e||!r){n(null);return}let o=e.stream(r);return n(o.track),o.on("track",n)},[e,r]),t}var ae=require("react");function De(e,r){let[t,n]=(0,ae.useState)(null),[o,a]=(0,ae.useState)(!1);(0,ae.useEffect)(()=>{if(!e||!r){n(null),a(!1);return}let d=e.doc(r);n(d.get()??{}),a(d.synced);let u=d.on("change",h=>n(h)),c=d.onSynced(()=>a(!0));return()=>{u(),c()}},[e,r]);let i=(0,ae.useCallback)(d=>{e&&r&&e.doc(r).set(d)},[e,r]);return{snapshot:t,synced:o,set:i}}var Fe=require("react");var re=200;function Z(e,r,t=200){let n=[...e,r];return n.length>t?n.slice(n.length-t):n}function ge(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function je(e){let r=e.trim();if(!r)return{ok:!1,error:"Enter a JSON object."};let t;try{t=JSON.parse(r)}catch(n){return{ok:!1,error:n instanceof Error?n.message:"Invalid JSON."}}return t===null||typeof t!="object"||Array.isArray(t)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:t}}function Be(e,r,t={}){let n=t.cap??200,[o,a]=(0,Fe.useState)([]);return(0,Fe.useEffect)(()=>{if(a([]),!e||!r)return;let i=!0,d=e.stream(r).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await d.next();if(!i||u.done)break;a(c=>Z(c,{at:Date.now(),payload:u.value},n))}})(),()=>{i=!1,d.return?.()}},[e,r,n]),o}var W=require("react/jsx-runtime");function ot({session:e,name:r,cap:t,className:n}){let o=Be(e,r,{cap:t});return(0,W.jsxs)("div",{className:["urun-stream-tail",n].filter(Boolean).join(" "),children:[(0,W.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,W.jsx)("code",{children:r}),(0,W.jsxs)("span",{className:"urun-stream-tail-count",children:[o.length," messages"]})]}),(0,W.jsx)("div",{className:"urun-stream-tail-log",children:o.length===0?(0,W.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,W.jsx)("code",{children:r})," messages\u2026"]}):o.map((a,i)=>(0,W.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,W.jsx)("span",{className:"urun-stream-tail-time",children:new Date(a.at).toLocaleTimeString()})," ",ge(a.payload)]},`${a.at}-${i}`))})]})}var Pe=require("react");var B=require("react/jsx-runtime");function Re({placeholder:e,buttonLabel:r,disabled:t,onApply:n}){let[o,a]=(0,Pe.useState)(""),[i,d]=(0,Pe.useState)(null),u=(0,Pe.useCallback)(()=>{let c=je(o);if(!c.ok){d(c.error);return}d(null),n(c.value,o.trim()),a("")},[o,n]);return(0,B.jsxs)("div",{className:"urun-doc-patch",children:[(0,B.jsx)("textarea",{className:"urun-doc-patch-input",value:o,onChange:c=>a(c.target.value),placeholder:e,rows:3}),(0,B.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,B.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:t||!o.trim(),onClick:u,children:r}),i?(0,B.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function st({session:e,docKey:r,editable:t=!0,patchPlaceholder:n='{"desired": {"prompt": {"text": "a sunset"}}}',className:o}){let{snapshot:a,synced:i,set:d}=De(e,r);return(0,B.jsxs)("div",{className:["urun-doc-panel",o].filter(Boolean).join(" "),children:[(0,B.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,B.jsx)("code",{children:r}),(0,B.jsx)("span",{className:"urun-doc-panel-synced","data-synced":i?"true":"false",children:i?"synced":"syncing\u2026"})]}),(0,B.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(a??{},null,2)}),t?(0,B.jsx)(Re,{placeholder:n,buttonLabel:"Apply patch",disabled:!e,onApply:u=>d(u)}):null]})}var ze=require("react");var Y=require("react/jsx-runtime");function at(e,r=600){return e.length>r?`${e.slice(0,r)}\u2026`:e}function it({session:e,docKey:r="control",cap:t=200,className:n}){let[o,a]=(0,ze.useState)([]);return(0,ze.useEffect)(()=>(a([]),e?e.doc(r).on("change",d=>{a(u=>Z(u,{at:Date.now(),direction:"in",text:at(ge(d))},t))}):void 0),[e,r,t]),(0,Y.jsxs)("div",{className:["urun-control-sender",n].filter(Boolean).join(" "),children:[(0,Y.jsx)(Re,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${r}`,disabled:!e,onApply:(i,d)=>{e?.doc(r).set(i),a(u=>Z(u,{at:Date.now(),direction:"out",text:at(d)},t))}}),(0,Y.jsx)("div",{className:"urun-control-sender-log",children:o.length===0?(0,Y.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...o].reverse().map((i,d)=>(0,Y.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,Y.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,Y.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${d}`))})]})}var He=require("react");var ie=require("react/jsx-runtime");function ut({session:e,trackNames:r=["video","audio"],docKeys:t=["control"],cap:n=200,className:o}){let[a,i]=(0,He.useState)([]),d=r.join(","),u=t.join(",");return(0,He.useEffect)(()=>{if(i([]),!e)return;let c=(l,f)=>i(R=>Z(R,{at:Date.now(),kind:l,text:f},n)),h=[];h.push(e.onPhase(l=>c("phase",`phase \u2192 ${l.name}`)));for(let l of r){let f=e.stream(l);h.push(f.on("track",R=>c("track",`${l}: ${R?"track arrived":"track ended"}`)))}for(let l of t){let f=e.doc(l);h.push(f.on("change",()=>c("doc",`${l} changed`)))}return()=>h.forEach(l=>l())},[e,d,u,n]),(0,ie.jsx)("div",{className:["urun-event-spine",o].filter(Boolean).join(" "),children:a.length===0?(0,ie.jsx)("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...a].reverse().map((c,h)=>(0,ie.jsxs)("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[(0,ie.jsx)("span",{className:"urun-event-spine-kind",children:c.kind})," ",(0,ie.jsx)("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${h}`))})}var $e=require("react"),Q=require("react/jsx-runtime"),It={idle:"idle",queued:"queued",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended"};function We(e){let[r,t]=(0,$e.useState)(e?.phase??null);return(0,$e.useEffect)(()=>{if(!e){t(null);return}return e.onPhase(t)},[e]),r}function ct({session:e,className:r}){let t=We(e),n=t?.name??"idle",o=t?.name==="queued"&&t.queue?`pos ${t.queue.position} / depth ${t.queue.depth}`:t?.name==="error"&&t.error?t.error.reason:null;return(0,Q.jsxs)("span",{className:["urun-session-status",r].filter(Boolean).join(" "),"data-phase":n,children:[(0,Q.jsx)("span",{className:"urun-session-status-dot","data-phase":n}),(0,Q.jsx)("span",{className:"urun-session-status-label",children:It[n]}),o?(0,Q.jsx)("span",{className:"urun-session-status-detail",children:o}):null]})}function lt({session:e,children:r,fallback:t,className:n}){let o=We(e);if(o?.name==="live")return(0,Q.jsx)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:r});let a=t?t(o):(0,Q.jsx)("span",{className:"urun-session-gate-fallback",children:o?.name==="error"?`Session ${o.error?.reason??"failed"}.`:o?.name==="ended"?"Session ended.":"Waiting for a live session\u2026"});return(0,Q.jsx)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:a})}0&&(module.exports={ComponentRenderer,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,ProgressCard,ProgressCardSchema,StatusBadge,StatusBadgeSchema,TextStream,TextStreamSchema,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunJwtProvider,UrunProvider,UrunSessionGate,UrunSessionStatus,UrunStreamTail,UrunVideo,UrunVoice,authMode,formatPayload,getUrunAudioContext,parseJsonObject,pushCapped,registerComponent,resumeUrunAudioContext,urunPublicEnv,useApp,useChat,useCompletion,useImageFrame,useMetricsPanel,useProgressCard,useRequest,useSessionDoc,useSessionPhase,useSessionTrack,useStatusBadge,useStreamMessages,useTextStream,useUrunAudioLevel,useUrunAuth,usesWorkOSAuth});
|
|
1
|
+
"use client"
|
|
2
|
+
"use strict";var er=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var ht=Object.getOwnPropertyNames;var vt=Object.prototype.hasOwnProperty;var kt=(e,r)=>{for(var t in r)er(e,t,{get:r[t],enumerable:!0})},yt=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of ht(r))!vt.call(e,o)&&o!==t&&er(e,o,{get:()=>r[o],enumerable:!(n=St(r,o))||n.enumerable});return e};var bt=e=>yt(er({},"__esModule",{value:!0}),e);var _t={};kt(_t,{ComponentRenderer:()=>Or,DEFAULT_CAMERA_CONSTRAINTS:()=>gr,DEFAULT_LOG_CAP:()=>Q,DEFAULT_VOICE_CONSTRAINTS:()=>mr,DocPatchForm:()=>we,ImageFrame:()=>Hr,ImageFrameSchema:()=>Vr,MetricsPanel:()=>jr,MetricsPanelSchema:()=>$r,ProgressCard:()=>qr,ProgressCardSchema:()=>Ir,StatusBadge:()=>Wr,StatusBadgeSchema:()=>Lr,TextStream:()=>Br,TextStreamSchema:()=>Fr,UrunAudio:()=>Oe,UrunAuthProvider:()=>rr,UrunCamera:()=>Yr,UrunControlSender:()=>ut,UrunDocPanel:()=>at,UrunErrorBoundary:()=>ie,UrunEventSpine:()=>ct,UrunJwtProvider:()=>br,UrunProvider:()=>Cr,UrunSessionGate:()=>mt,UrunSessionStatus:()=>pt,UrunSessionWaking:()=>Xe,UrunStreamTail:()=>st,UrunVoice:()=>Gr,authMode:()=>ve,createDocStore:()=>We,describeSessionPhase:()=>Ke.describeSessionPhase,formatPayload:()=>fe,getUrunAudioContext:()=>Ue,isWakingPhase:()=>Ke.isWakingPhase,parseJsonObject:()=>Be,pushCapped:()=>K,registerComponent:()=>Nr,resumeUrunAudioContext:()=>Re,urunPublicEnv:()=>z,useApp:()=>Rr,useChat:()=>_r,useCompletion:()=>wr,useDocStore:()=>me,useImageFrame:()=>cr,useMetricsPanel:()=>lr,useProgressCard:()=>ar,useRequest:()=>xr,useSessionDoc:()=>ot,useSessionPhase:()=>ee,useSessionTrack:()=>et,useSessionWake:()=>ze,useStatusBadge:()=>ir,useStreamMessages:()=>He,useTextStream:()=>ur,useUrunAudioLevel:()=>Qr,useUrunAuth:()=>Ee,usesWorkOSAuth:()=>kr});module.exports=bt(_t);var ce=require("react");var hr=require("react"),he=require("react/jsx-runtime"),ie=class extends hr.Component{constructor(r){super(r),this.state={error:null}}static getDerivedStateFromError(r){return{error:r}}componentDidCatch(r,t){console.error("[urun] Error caught by UrunErrorBoundary:",r,t)}render(){if(this.state.error){let{fallback:r}=this.props;return typeof r=="function"?r(this.state.error):r||(0,he.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,he.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,he.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var vr=require("react"),Ae=(0,vr.createContext)(null);function ne(e){return e&&e.trim()?e.trim():void 0}function z(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return ne(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return ne(typeof process<"u"?process.env?.[e]:void 0)}}function ve(){let e=z("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||z("VERCEL_ENV")==="production"?"workos":z("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function kr(){return ve()==="workos"}var ue=require("react"),Tr=require("react/jsx-runtime"),yr=(0,ue.createContext)(null);function rr({getAccessToken:e,children:r}){let t=(0,ue.useMemo)(()=>({getAccessToken:e}),[e]);return(0,Tr.jsx)(yr.Provider,{value:t,children:r})}var br=rr;function Ee(){return(0,ue.useContext)(yr)}var _e=require("react/jsx-runtime");function Cr({baseUrl:e,orgId:r,appId:t,jwt:n,authProvider:o,fallback:s,children:a}){let[u,c]=(0,ce.useState)(),i=Ee(),S=z("NEXT_PUBLIC_SESSION_TOKEN")??z("NEXT_PUBLIC_URUN_JWT"),l=ve(),m=l==="workos"&&!n,x=n??(l==="jwt"?S:void 0)??u,C=o??z("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),b=m&&!x,T=(0,ce.useMemo)(()=>({appId:t,baseUrl:e,orgId:r,jwt:x,getAccessToken:m?i?.getAccessToken:void 0,authProvider:C}),[t,i,e,C,x,r,m]);return(0,ce.useEffect)(()=>{if(!m||!i)return;let k=!1,h=i;async function v(){try{let U=await h.getAccessToken();k||c(U??void 0)}catch{k||c(void 0)}}v();let P=window.setInterval(()=>{v()},6e4);return()=>{k=!0,window.clearInterval(P)}},[i,m]),(0,_e.jsx)(ie,{fallback:s,children:b?(0,_e.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,_e.jsx)(Ae.Provider,{value:T,children:a})})}var X=require("react"),Ur=require("@urun-sh/core");function Tt(e,r){return`${e}:${JSON.stringify(r??{})}`}var tr=class{constructor(r,t){this._doc=r;this._notify=t;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(r,t){return this._doc.get(r,t)}set(r){this._doc.set(r),this._notify()}on(r,t){return this._doc.on(r,n=>t(n))}get synced(){return this._doc.synced}onSynced(r){return this._doc.onSynced(()=>{r(),this._notify()})}text(r){let t=this._doc.text(r),n=this._notify;return{append(o){t.append(o),n()},toString:()=>t.toString(),get length(){return t.length},on:(o,s)=>t.on(o,a=>{s(a),n()})}}dispose(){this._unsubscribeChange()}},nr=class{constructor(r,t){this._stream=r;this._notify=t;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(r){return this._stream.attach(r)}attachVideo(r){return this._stream.attachVideo(r)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(r){return this._stream.seek(r)}chunks(r){return this._stream.chunks(r)}onSeeked(r){return this._stream.onSeeked(r)}on(r,t){return this._stream.on(r,t)}messages(){return this._stream.messages()}emit(r,t){return this._stream.emit(r,t)}dispose(){this._unsubscribeTrack()}},or=class{constructor(r,t){this._session=r;this._notify=t;this._unsubscribePhase=this._session.onPhase(()=>this._notify())}_session;_notify;_docs=new Map;_streams=new Map;_unsubscribePhase;_disposed=!1;get disposed(){return this._disposed}get id(){return this._session.id}get phase(){return this._session.phase}get status(){return this._session.status}onPhase(r){return this._session.onPhase(r)}whenLive(r){return this._session.whenLive(r)}recover(){this._session.recover()}onRecovery(r){return this._session.onRecovery(r)}request(r,t){return this._session.request(r,t)}requestStream(r,t){return this._session.requestStream(r,t)}complete(r,t){return this._session.complete(r,t)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}doc(r){let t=this._docs.get(r);return t||(t=new tr(this._session.doc(r),this._notify),this._docs.set(r,t)),t}stream(r){let t=this._streams.get(r);return t||(t=new nr(this._session.stream(r),this._notify),this._streams.set(r,t)),t}disconnect(){this._disposed=!0;for(let r of this._docs.values())r.dispose();for(let r of this._streams.values())r.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._session.disconnect(),this._notify()}};function Rr(){let e=(0,X.useContext)(Ae);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,r]=(0,X.useReducer)(o=>o+1,0),t=(0,X.useRef)(new Map),n=(0,X.useMemo)(()=>(0,Ur.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider]);return(0,X.useMemo)(()=>new Proxy({},{get(o,s){if(typeof s=="string")return a=>{let u=Tt(s,a),c=t.current.get(u);if(c&&!c.disposed)return c;let i=new or(n[s](a),r);return t.current.set(u,i),i}}}),[n])}var O=require("react");function le(e){let r=e;if(!r||typeof r.request!="function"||typeof r.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 r}function Ct(e){return e instanceof Error?e:new Error(String(e))}function xr(e,r){let t=(0,O.useMemo)(()=>le(e),[e]),[n,o]=(0,O.useState)(void 0),[s,a]=(0,O.useState)(null),[u,c]=(0,O.useState)(!1),i=(0,O.useRef)(r);i.current=r;let S=(0,O.useRef)(0),l=(0,O.useRef)(null),m=(0,O.useRef)(!0);(0,O.useEffect)(()=>(m.current=!0,()=>{m.current=!1,l.current?.abort()}),[]);let x=(0,O.useCallback)(async T=>{l.current?.abort();let k=new AbortController;l.current=k;let h=++S.current,v=()=>m.current&&S.current===h;v()&&(c(!0),a(null));try{let P=await t.request(T,{...i.current,signal:k.signal});return v()&&(o(P),c(!1),i.current?.onSuccess?.(P)),P}catch(P){let U=Ct(P);throw v()&&(a(U),c(!1),i.current?.onError?.(U)),U}},[t]),C=(0,O.useCallback)(T=>{x(T).catch(()=>{})},[x]),b=(0,O.useCallback)(()=>{S.current++,l.current?.abort(),l.current=null,o(void 0),a(null),c(!1)},[]);return{mutate:C,mutateAsync:x,data:n,error:s,isPending:u,reset:b}}var q=require("react");function Pr(e){return e instanceof Error?e:new Error(String(e))}var Ut=e=>typeof e=="string"?e:String(e);function wr(e,r){let t=(0,q.useMemo)(()=>le(e),[e]),[n,o]=(0,q.useState)(""),[s,a]=(0,q.useState)(!1),[u,c]=(0,q.useState)(null),i=(0,q.useRef)(r);i.current=r;let S=(0,q.useRef)(0),l=(0,q.useRef)(null),m=(0,q.useRef)(!0);(0,q.useEffect)(()=>(m.current=!0,()=>{m.current=!1,l.current?.cancel(),l.current=null}),[]);let x=(0,q.useCallback)(()=>{S.current++,l.current?.cancel(),l.current=null,m.current&&a(!1)},[]),C=(0,q.useCallback)(async b=>{l.current?.cancel();let T=++S.current,k=()=>m.current&&S.current===T,h=i.current,v=h?.parseChunk??Ut,P=h?.buildPayload??(y=>({prompt:y}));k()&&(o(""),c(null),a(!0));let{parseChunk:U,buildPayload:J,onFinish:V,onError:d,...R}=h??{},p="",f;try{f=t.requestStream(P(b),R),l.current=f}catch(y){let _=Pr(y);k()&&(c(_),a(!1),h?.onError?.(_));return}try{for await(let y of f){if(S.current!==T)break;p+=v(y),k()&&o(p)}k()&&(a(!1),h?.onFinish?.(p))}catch(y){let _=Pr(y);k()&&(c(_),a(!1),h?.onError?.(_))}finally{l.current===f&&(l.current=null)}},[t]);return{completion:n,complete:C,stop:x,isStreaming:s,error:u}}var D=require("react");function Ar(e){return e instanceof Error?e:new Error(String(e))}var Rt=e=>typeof e=="string"?e:String(e),Er=0;function sr(e){return Er+=1,`${e}-${Er}`}function _r(e,r){let t=(0,D.useMemo)(()=>le(e),[e]),[n,o]=(0,D.useState)(()=>(r?.initialMessages??[]).map(v=>({id:v.id??sr("msg"),role:v.role,content:v.content}))),[s,a]=(0,D.useState)(""),[u,c]=(0,D.useState)(!1),[i,S]=(0,D.useState)(null),l=(0,D.useRef)(r);l.current=r;let m=(0,D.useRef)(n);m.current=n;let x=(0,D.useRef)(s);x.current=s;let C=(0,D.useRef)(0),b=(0,D.useRef)(null),T=(0,D.useRef)(!0);(0,D.useEffect)(()=>(T.current=!0,()=>{T.current=!1,b.current?.cancel(),b.current=null}),[]);let k=(0,D.useCallback)(()=>{C.current++,b.current?.cancel(),b.current=null,T.current&&c(!1)},[]),h=(0,D.useCallback)(async v=>{let P=v===void 0,U=(P?x.current:v)??"";if(!U.trim())return;b.current?.cancel();let V=++C.current,d=()=>T.current&&C.current===V,R=l.current,p=R?.parseChunk??Rt,f={id:sr("msg"),role:"user",content:U},y={id:sr("msg"),role:"assistant",content:""},_=[...m.current,f].map(N=>({role:N.role,content:N.content})),g=[...m.current,f,y];m.current=g,o(g),P&&a(""),S(null),c(!0);let I=R?.buildPayload??(N=>({messages:N})),{initialMessages:Se,parseChunk:Ze,buildPayload:Ye,onFinish:Qe,onError:ft,...M}=R??{},L=N=>{o(H=>H.map(F=>F.id===y.id?{...F,content:N}:F))},Y="",W;try{W=t.requestStream(I(_),M),b.current=W}catch(N){let H=Ar(N);d()&&(S(H),c(!1),R?.onError?.(H));return}try{for await(let N of W){if(C.current!==V)break;Y+=p(N),d()&&L(Y)}d()&&(c(!1),R?.onFinish?.({...y,content:Y}))}catch(N){let H=Ar(N);d()&&(S(H),c(!1),R?.onError?.(H))}finally{b.current===W&&(b.current=null)}},[t]);return{messages:n,input:s,setInput:a,sendMessage:h,stop:k,isStreaming:u,error:i}}var Mr=new Map;function Nr(e,r,t){if(!t||typeof t.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Mr.set(e,{component:r,schema:t})}function Dr(e,r){let t=Mr.get(e);if(!t)return{error:`Unknown component: "${e}"`};let n=t.schema.safeParse(r);return n.success?{Component:t.component,validatedProps:n.data}:{error:`Validation failed for "${e}": ${n.error.message}`}}var oe=require("react/jsx-runtime");function Or({name:e,props:r,fallback:t}){let n=Dr(e,r);if(n.error)return console.warn(`[urun] ComponentRenderer: ${n.error}`),t?(0,oe.jsx)(oe.Fragment,{children:t}):(0,oe.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,oe.jsx)("span",{className:"urun-component-error-text",children:n.error})});let o=n.Component;return(0,oe.jsx)(o,{...n.validatedProps})}var de=require("zod"),se=require("react/jsx-runtime"),Ir=de.z.object({step:de.z.number().min(0),total:de.z.number().min(1),label:de.z.string().optional(),variant:de.z.enum(["default","success","error"]).default("default")});function ar(e){let{step:r,total:t,label:n,variant:o="default"}=e,s=Math.min(r/t*100,100),a=r>=t;return{step:r,total:t,label:n,variant:o,percentage:s,isComplete:a}}function qr(e){let{step:r,total:t,label:n,variant:o,percentage:s}=ar(e);return(0,se.jsxs)("div",{className:"urun-progress-card","data-variant":o,children:[n&&(0,se.jsx)("div",{className:"urun-progress-label",children:n}),(0,se.jsx)("div",{className:"urun-progress-bar",children:(0,se.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,se.jsxs)("div",{className:"urun-progress-text",children:[r,"/",t]})]})}var Me=require("zod"),ke=require("react/jsx-runtime"),Lr=Me.z.object({state:Me.z.enum(["thinking","generating","idle","error"]),message:Me.z.string().optional()}),xt={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function ir(e){let{state:r,message:t}=e,n=r==="thinking"||r==="generating",o=t??xt[r]??r;return{state:r,message:o,isActive:n}}function Wr(e){let{state:r,message:t,isActive:n}=ir(e);return(0,ke.jsxs)("span",{className:"urun-status-badge","data-state":r,children:[(0,ke.jsx)("span",{className:`urun-status-indicator${n?" urun-status-pulse":""}`}),(0,ke.jsx)("span",{className:"urun-status-message",children:t})]})}var ye=require("react"),Ne=require("zod"),be=require("react/jsx-runtime"),Fr=Ne.z.object({text:Ne.z.string(),streaming:Ne.z.boolean().default(!1)});function ur(e){let{text:r,streaming:t=!1}=e,n=r.length===0;return{text:r,streaming:t,isEmpty:n}}function Br(e){let{text:r,streaming:t}=ur(e),n=(0,ye.useRef)(null),o=(0,ye.useRef)(0);return(0,ye.useEffect)(()=>{let s=n.current;s&&r.length!==o.current&&(s.textContent=r,o.current=r.length)},[r]),(0,be.jsxs)("div",{className:"urun-text-stream",children:[(0,be.jsx)("span",{ref:n,className:"urun-text-content"}),t&&(0,be.jsx)("span",{className:"urun-text-cursor"})]})}var Te=require("zod"),Ce=require("react/jsx-runtime"),Vr=Te.z.object({src:Te.z.string().url(),alt:Te.z.string().optional(),caption:Te.z.string().optional()});function cr(e){let{src:r,alt:t,caption:n}=e;return{src:r,alt:t??"",caption:n}}function Hr(e){let{src:r,alt:t,caption:n}=cr(e);return(0,Ce.jsxs)("figure",{className:"urun-image-frame",children:[(0,Ce.jsx)("img",{className:"urun-image",src:r,alt:t}),n&&(0,Ce.jsx)("figcaption",{className:"urun-image-caption",children:n})]})}var G=require("zod"),pe=require("react/jsx-runtime"),$r=G.z.object({metrics:G.z.array(G.z.object({label:G.z.string(),value:G.z.union([G.z.string(),G.z.number()]),unit:G.z.string().optional()}))});function lr(e){return{metrics:e.metrics.map(t=>({...t,displayValue:t.unit?`${t.value} ${t.unit}`:String(t.value)}))}}function jr(e){let{metrics:r}=lr(e);return(0,pe.jsx)("div",{className:"urun-metrics-panel",children:r.map((t,n)=>(0,pe.jsxs)("div",{className:"urun-metric-card",children:[(0,pe.jsx)("div",{className:"urun-metric-label",children:t.label}),(0,pe.jsx)("div",{className:"urun-metric-value",children:t.displayValue})]},n))})}var A=require("react"),zr=require("@urun-sh/core");var De=null;function Pt(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function Ue(){if(De)return De;let e=Pt();return e?(De=new e,De):null}function Re(){let e=Ue();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var Xr=require("react/jsx-runtime"),wt=1e3,Jr=200;function dr(...e){console.debug("[urun-audio]",...e)}var Oe=(0,A.forwardRef)(function(r,t){let{session:n,stream:o="audio",track:s,controls:a=!1,className:u,onTrack:c,onUnlockChange:i,onAudioElement:S}=r,l=(0,A.useRef)(null),m=(0,A.useRef)(null),x=(0,A.useRef)(null),C=(0,A.useRef)(null),b=(0,A.useRef)(c);b.current=c;let T=(0,A.useRef)(i);T.current=i;let k=(0,A.useCallback)(d=>{x.current!==d&&(x.current=d,T.current?.(d))},[]),h=(0,A.useCallback)(()=>{if(typeof MediaStream>"u")return null;m.current||(m.current=new MediaStream);let d=l.current;return d&&d.srcObject!==m.current&&(d.srcObject=m.current),m.current},[]),v=(0,A.useCallback)(d=>{let R=l.current;if(!R)return;let p=R.play();!p||typeof p.then!="function"||p.then(()=>{R.muted||k(!0)}).catch(f=>{let y=f instanceof Error?f.name:String(f);if(y==="AbortError"){dr(`play() aborted (${d}); retrying in ${Jr}ms`),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>{C.current=null,v(`${d}:retry`)},Jr);return}if(y==="NotAllowedError"){dr(`play() blocked pending a user gesture (${d})`),k(!1);return}dr(`play() failed (${d})`,f)})},[k]),P=(0,A.useCallback)(d=>{let R=h();if(R){for(let p of R.getAudioTracks())p!==d&&R.removeTrack(p);d&&!R.getAudioTracks().includes(d)&&R.addTrack(d),d&&v("track-attach"),b.current?.(d)}},[h,v]),U=(0,A.useCallback)(()=>{let d=l.current;d&&(h(),d.muted=!1,v("gesture"),Re(),k(!0))},[h,v,k]);(0,A.useImperativeHandle)(t,()=>({unlock:U,get unlocked(){return x.current===!0},get element(){return l.current}}),[U]);let J=(0,A.useCallback)(d=>{l.current=d,d&&(d.setAttribute("playsinline",""),d.setAttribute("webkit-playsinline",""),h()),S?.(d)},[h,S]),V=s!==void 0;return(0,A.useEffect)(()=>{if(V){P(s??null);return}if(!n)return;let d=n.stream(o),R=()=>{let g=m.current;return g?g.getAudioTracks()[0]??null:null},p=g=>{if(g!==R()&&(P(g),g)){let I=()=>{R()===g&&P(null)};g.addEventListener("ended",I)}},f=d.track;f&&f.readyState==="live"&&p(f);let y=d.on("track",g=>{g&&g.readyState!=="live"||p(g)}),_=setInterval(()=>{let g=d.track;g&&g.readyState==="live"&&p(g)},wt);return()=>{y(),clearInterval(_)}},[n,o,V,s,P]),(0,A.useEffect)(()=>(0,zr.observePageLifecycle)(()=>{Re(),x.current===!0&&v("foreground")}),[v]),(0,A.useEffect)(()=>()=>{C.current&&clearTimeout(C.current)},[]),(0,Xr.jsx)("audio",{ref:J,className:u,autoPlay:!0,playsInline:!0,controls:a,"data-urun-audio":""})});var E=require("react"),xe=require("@urun-sh/core");var Kr=require("react/jsx-runtime"),mr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function pr(...e){console.debug("[urun-voice]",...e)}var Gr=(0,E.forwardRef)(function(r,t){let{session:n,stream:o="audio",constraints:s=mr,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:i,onError:S,onMicStream:l,onTrack:m,onUnlockChange:x}=r,C=(0,E.useRef)(null),b=(0,E.useRef)(null),T=(0,E.useRef)(!1),k=(0,E.useRef)(i);k.current=i;let h=(0,E.useRef)(S);h.current=S;let v=(0,E.useRef)(l);v.current=l;let P=(0,E.useCallback)(p=>{T.current!==p&&(T.current=p,k.current?.(p))},[]),U=(0,E.useCallback)(()=>{let p=b.current;if(p){for(let f of p.getTracks())f.stop();b.current=null,v.current?.(null)}},[]),J=(0,E.useCallback)(async()=>{U(),P(!1),await n.stream(o).detach().catch(()=>{})},[n,o,U,P]),V=(0,E.useCallback)(async()=>{C.current?.unlock();let p;try{p=await navigator.mediaDevices.getUserMedia({audio:s,video:!1})}catch(g){let I=(0,xe.sessionFailureFromMediaError)(g,n.status);throw h.current?.(I),I}U(),b.current=p,v.current?.(p);let f=p.getAudioTracks()[0];if(!f){U();let g=(0,xe.sessionFailureFromMediaError)(Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"}),n.status);throw h.current?.(g),g}n.connect?.();let y;for(let g=1;g<=u;g++)try{await n.whenLive(a!==void 0?{timeout:a}:void 0),await n.stream(o).attach(f),P(!0);return}catch(I){y=I,pr(`start attempt ${g}/${u} failed`,I),g<u&&await new Promise(Se=>setTimeout(Se,c))}U(),P(!1);let _=y instanceof Error?y:new Error(String(y??"voice start failed"));throw h.current?.(_),_},[n,o,s,a,u,c,U,P]);(0,E.useImperativeHandle)(t,()=>({start:V,stop:J,unlock:()=>C.current?.unlock(),get active(){return T.current},get micStream(){return b.current},get audio(){return C.current}}),[V,J]);let d=(0,E.useRef)(!1),R=(0,E.useCallback)(async()=>{if(!T.current||d.current)return;let p=b.current?.getAudioTracks()[0]??null;if(p&&p.readyState==="live"){try{await n.stream(o).attach(p)}catch(f){pr("foreground mic re-assert failed (will retry on next pass)",f)}return}d.current=!0;try{let f=await navigator.mediaDevices.getUserMedia({audio:s,video:!1}),y=f.getAudioTracks()[0];if(!y){for(let _ of f.getTracks())_.stop();throw new Error("no microphone audio track after foreground re-acquire")}U(),b.current=f,v.current?.(f),await n.stream(o).attach(y)}catch(f){let y=f instanceof Error?f:new Error(String(f));pr("foreground mic re-acquire failed",y),h.current?.(y)}finally{d.current=!1}},[n,o,s,U]);return(0,E.useEffect)(()=>{let p=()=>{R()};return typeof n.onRecovery=="function"?n.onRecovery(p):(0,xe.observePageLifecycle)(p)},[n,R]),(0,E.useEffect)(()=>U,[U]),(0,Kr.jsx)(Oe,{ref:C,session:n,stream:o,onTrack:m,onUnlockChange:x})});var fr=require("@urun-sh/core"),w=require("react"),Ie=require("react/jsx-runtime"),gr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Zr(...e){console.debug("[urun-camera]",...e)}var Yr=(0,w.forwardRef)(function(r,t){let{session:n,stream:o="video",constraints:s,facingMode:a="environment",mirror:u="auto",connectTimeoutMs:c,preview:i=!0,className:S,videoClassName:l,onActiveChange:m,onError:x,onStream:C,onTrack:b,children:T}=r,k=(0,w.useRef)(null),h=(0,w.useRef)(null),v=(0,w.useRef)(null),P=(0,w.useRef)(!1),U=(0,w.useRef)(a),[J,V]=(0,w.useState)(a),d=(0,w.useRef)(m);d.current=m;let R=(0,w.useRef)(x);R.current=x;let p=(0,w.useRef)(C);p.current=C;let f=(0,w.useRef)(b);f.current=b;let y=(0,w.useCallback)(M=>{P.current!==M&&(P.current=M,d.current?.(M))},[]),_=(0,w.useCallback)(M=>{let L=k.current;L&&(L.muted=!0,L.srcObject=M,M&&L.play()?.catch?.(Y=>Zr("preview play() failed",Y)))},[]),g=(0,w.useCallback)(()=>{v.current?.(),v.current=null;let M=h.current;if(M){for(let L of M.getTracks())L.stop();h.current=null,p.current?.(null),f.current?.(null)}_(null)},[_]),I=(0,w.useCallback)(async M=>{let L=h.current,Y=v.current,W;try{W=await navigator.mediaDevices.getUserMedia({video:{...gr,...s,facingMode:M},audio:!1})}catch(F){let te=(0,fr.sessionFailureFromMediaError)(F,n.status);throw R.current?.(te),te}let N=W.getVideoTracks()[0];if(!N){for(let te of W.getTracks())te.stop();let F=(0,fr.sessionFailureFromMediaError)(Object.assign(new Error("no camera video track"),{name:"NotFoundError"}),n.status);throw R.current?.(F),F}h.current=W,U.current=M,V(M),_(W),p.current?.(W);let H=()=>{h.current===W&&(Zr("camera track ended (device removed or permission revoked)"),g(),y(!1))};N.addEventListener("ended",H),v.current=()=>N.removeEventListener("ended",H);try{n.connect?.(),await n.whenLive(c!==void 0?{timeout:c}:void 0),await n.stream(o).attachVideo(N)}catch(F){N.removeEventListener("ended",H);for(let gt of W.getTracks())gt.stop();h.current===W&&(h.current=L,v.current=Y,_(L),p.current?.(L));let te=F instanceof Error?F:new Error(String(F));throw R.current?.(te),te}if(L&&L!==W){Y?.();for(let F of L.getTracks())F.stop()}f.current?.(N),y(!0)},[n,o,s,c,_,g,y]),Se=(0,w.useCallback)(M=>I(M?.facingMode??U.current),[I]),Ze=(0,w.useCallback)(async M=>{P.current&&U.current===M||await I(M)},[I]),Ye=(0,w.useCallback)(()=>I(U.current==="environment"?"user":"environment"),[I]),Qe=(0,w.useCallback)(async()=>{g(),y(!1),await n.stream(o).detachVideo().catch(()=>{})},[n,o,g,y]);return(0,w.useImperativeHandle)(t,()=>({start:Se,stop:Qe,flip:Ye,setFacingMode:Ze,get active(){return P.current},get facingMode(){return U.current},get stream(){return h.current},get element(){return k.current}}),[Se,Qe,Ye,Ze]),(0,w.useEffect)(()=>g,[g]),i?(0,Ie.jsxs)("div",{className:S,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":J,children:[(0,Ie.jsx)("video",{ref:k,className:l,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...(u==="auto"?J==="user":u)?{transform:"scaleX(-1)"}:{}}}),T]}):null});var qe=require("react");var Sr={level:0,speaking:!1};function Qr(e,r={}){let{fftSize:t=512,intervalMs:n=100,speakingThreshold:o=.02}=r,[s,a]=(0,qe.useState)(Sr);return(0,qe.useEffect)(()=>{if(!e){a(Sr);return}let u=Ue();if(!u||typeof MediaStream>"u")return;let c;e instanceof MediaStream?c=e:(c=new MediaStream,c.addTrack(e));let i,S;try{i=u.createMediaStreamSource(c),S=u.createAnalyser(),S.fftSize=t,i.connect(S)}catch{return}let l=new Uint8Array(S.fftSize),x=setInterval(()=>{S.getByteTimeDomainData(l);let C=0;for(let T=0;T<l.length;T++){let k=(l[T]-128)/128;C+=k*k}let b=Math.sqrt(C/l.length);a(T=>{let k=b>o;return Math.abs(T.level-b)<.005&&T.speaking===k?T:{level:b,speaking:k}})},n);return()=>{clearInterval(x),i.disconnect(),a(Sr)}},[e,t,n,o]),s}var Le=require("react");function et(e,r){let[t,n]=(0,Le.useState)(null);return(0,Le.useEffect)(()=>{if(!e||!r){n(null);return}let o=e.stream(r);return n(o.track),o.on("track",n)},[e,r]),t}var nt=require("react");var Fe=require("react");var rt=require("zustand/vanilla"),tt=require("zustand"),At=()=>{};function We(e,r={}){let t=i=>{e?.set(i)},n=()=>e?e.get()??{}:{},o=(0,rt.createStore)(()=>({doc:n(),synced:e?e.synced:!1,set:t})),s=null,a=()=>{if(s){for(let i of s)i();s=null}},u=()=>e?(s||(o.setState({doc:n(),synced:e.synced}),s=[e.on("change",i=>o.setState({doc:i})),e.onSynced(()=>o.setState({synced:!0}))]),a):At,c=(i=>(0,tt.useStore)(o,i));return Object.assign(c,{getState:o.getState,getInitialState:o.getInitialState,subscribe:o.subscribe,set:t,bind:u,unbind:a}),r.bind!==!1&&u(),c}function me(e,r){let t=(0,Fe.useMemo)(()=>We(e&&r?e.doc(r):null,{bind:!1}),[e,r]);return(0,Fe.useEffect)(()=>t.bind(),[t]),t}function ot(e,r,t){let o=me(e,r)(t??(u=>u)),s=(0,nt.useCallback)(u=>{e&&r&&e.doc(r).set(u)},[e,r]);if(t)return o;let a=o;return{snapshot:e&&r?a.doc:null,synced:a.synced,set:s}}var Ve=require("react");var Q=200;function K(e,r,t=200){let n=[...e,r];return n.length>t?n.slice(n.length-t):n}function fe(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Be(e){let r=e.trim();if(!r)return{ok:!1,error:"Enter a JSON object."};let t;try{t=JSON.parse(r)}catch(n){return{ok:!1,error:n instanceof Error?n.message:"Invalid JSON."}}return t===null||typeof t!="object"||Array.isArray(t)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:t}}function He(e,r,t={}){let n=t.cap??200,[o,s]=(0,Ve.useState)([]);return(0,Ve.useEffect)(()=>{if(s([]),!e||!r)return;let a=!0,u=e.stream(r).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await u.next();if(!a||c.done)break;s(i=>K(i,{at:Date.now(),payload:c.value},n))}})(),()=>{a=!1,u.return?.()}},[e,r,n]),o}var $=require("react/jsx-runtime");function st({session:e,name:r,cap:t,className:n}){let o=He(e,r,{cap:t});return(0,$.jsxs)("div",{className:["urun-stream-tail",n].filter(Boolean).join(" "),children:[(0,$.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,$.jsx)("code",{children:r}),(0,$.jsxs)("span",{className:"urun-stream-tail-count",children:[o.length," messages"]})]}),(0,$.jsx)("div",{className:"urun-stream-tail-log",children:o.length===0?(0,$.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,$.jsx)("code",{children:r})," messages\u2026"]}):o.map((s,a)=>(0,$.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,$.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",fe(s.payload)]},`${s.at}-${a}`))})]})}var Pe=require("react");var B=require("react/jsx-runtime");function we({placeholder:e,buttonLabel:r,disabled:t,onApply:n}){let[o,s]=(0,Pe.useState)(""),[a,u]=(0,Pe.useState)(null),c=(0,Pe.useCallback)(()=>{let i=Be(o);if(!i.ok){u(i.error);return}u(null),n(i.value,o.trim()),s("")},[o,n]);return(0,B.jsxs)("div",{className:"urun-doc-patch",children:[(0,B.jsx)("textarea",{className:"urun-doc-patch-input",value:o,onChange:i=>s(i.target.value),placeholder:e,rows:3}),(0,B.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,B.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:t||!o.trim(),onClick:c,children:r}),a?(0,B.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:a}):null]})]})}function at({session:e,docKey:r,editable:t=!0,patchPlaceholder:n='{"desired": {"prompt": {"text": "a sunset"}}}',className:o}){let s=me(e,r),a=s(i=>i.doc),u=s(i=>i.synced),c=s(i=>i.set);return(0,B.jsxs)("div",{className:["urun-doc-panel",o].filter(Boolean).join(" "),children:[(0,B.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,B.jsx)("code",{children:r}),(0,B.jsx)("span",{className:"urun-doc-panel-synced","data-synced":u?"true":"false",children:u?"synced":"syncing\u2026"})]}),(0,B.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(a??{},null,2)}),t?(0,B.jsx)(we,{placeholder:n,buttonLabel:"Apply patch",disabled:!e,onApply:i=>c(i)}):null]})}var $e=require("react");var Z=require("react/jsx-runtime");function it(e,r=600){return e.length>r?`${e.slice(0,r)}\u2026`:e}function ut({session:e,docKey:r="control",cap:t=200,className:n}){let[o,s]=(0,$e.useState)([]);return(0,$e.useEffect)(()=>(s([]),e?e.doc(r).on("change",u=>{s(c=>K(c,{at:Date.now(),direction:"in",text:it(fe(u))},t))}):void 0),[e,r,t]),(0,Z.jsxs)("div",{className:["urun-control-sender",n].filter(Boolean).join(" "),children:[(0,Z.jsx)(we,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${r}`,disabled:!e,onApply:(a,u)=>{e?.doc(r).set(a),s(c=>K(c,{at:Date.now(),direction:"out",text:it(u)},t))}}),(0,Z.jsx)("div",{className:"urun-control-sender-log",children:o.length===0?(0,Z.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...o].reverse().map((a,u)=>(0,Z.jsxs)("div",{className:"urun-control-sender-line","data-direction":a.direction,children:[(0,Z.jsx)("span",{className:"urun-control-sender-dir",children:a.direction==="out"?"sent":"change"})," ",(0,Z.jsx)("span",{className:"urun-control-sender-time",children:new Date(a.at).toLocaleTimeString()})," ",a.text]},`${a.at}-${u}`))})]})}var je=require("react");var ae=require("react/jsx-runtime");function ct({session:e,trackNames:r=["video","audio"],docKeys:t=["control"],cap:n=200,className:o}){let[s,a]=(0,je.useState)([]),u=r.join(","),c=t.join(",");return(0,je.useEffect)(()=>{if(a([]),!e)return;let i=(l,m)=>a(x=>K(x,{at:Date.now(),kind:l,text:m},n)),S=[];S.push(e.onPhase(l=>i("phase",`phase \u2192 ${l.name}`)));for(let l of r){let m=e.stream(l);S.push(m.on("track",x=>i("track",`${l}: ${x?"track arrived":"track ended"}`)))}for(let l of t){let m=e.doc(l);S.push(m.on("change",()=>i("doc",`${l} changed`)))}return()=>S.forEach(l=>l())},[e,u,c,n]),(0,ae.jsx)("div",{className:["urun-event-spine",o].filter(Boolean).join(" "),children:s.length===0?(0,ae.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((i,S)=>(0,ae.jsxs)("div",{className:"urun-event-spine-line","data-kind":i.kind,children:[(0,ae.jsx)("span",{className:"urun-event-spine-kind",children:i.kind})," ",(0,ae.jsx)("span",{className:"urun-event-spine-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${S}`))})}var Ge=require("@urun-sh/core");var Je=require("react");function ee(e){let[r,t]=(0,Je.useState)(e?.phase??null);return(0,Je.useEffect)(()=>{if(!e){t(null);return}return e.onPhase(t)},[e]),r}var dt=require("@urun-sh/core");var ge=require("react"),lt=require("@urun-sh/core");function ze(e){let r=ee(e),t=(0,lt.isWakingPhase)(r?.name),n=(0,ge.useRef)(void 0);t?n.current??=Date.now():n.current=void 0;let o=t?r?.wakingSince??n.current:void 0,s=()=>o!==void 0?Math.max(0,Math.floor((Date.now()-o)/1e3)):0,[a,u]=(0,ge.useState)(s);return(0,ge.useEffect)(()=>{if(o===void 0){u(0);return}u(Math.max(0,Math.floor((Date.now()-o)/1e3)));let c=setInterval(()=>{u(Math.max(0,Math.floor((Date.now()-o)/1e3)))},1e3);return()=>clearInterval(c)},[o]),{waking:t,phase:r,state:t?r?.runtime?.state:void 0,reason:t?r?.runtime?.reason:void 0,since:o,seconds:t?a:0}}var re=require("react/jsx-runtime");function Xe({session:e,render:r,className:t}){let n=ze(e);return!n.waking||!n.phase?null:(0,re.jsx)("span",{className:["urun-session-waking",t].filter(Boolean).join(" "),"data-phase":n.phase.name,"data-runtime-state":n.state,children:r?r(n):(0,re.jsxs)(re.Fragment,{children:[(0,re.jsx)("span",{className:"urun-session-waking-label",children:(0,dt.describeSessionPhase)(n.phase)})," ",(0,re.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",n.seconds,"s)"]})]})})}var j=require("react/jsx-runtime"),Et={idle:"idle",queued:"queued",unavailable:"unavailable",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended"};function pt({session:e,className:r}){let t=ee(e),n=t?.name??"idle",o=t?.name==="queued"&&t.queue?`pos ${t.queue.position} / depth ${t.queue.depth}`:t?.name==="error"&&t.error?t.error.reason:t?.runtime?.reason??null;return(0,j.jsxs)("span",{className:["urun-session-status",r].filter(Boolean).join(" "),"data-phase":n,children:[(0,j.jsx)("span",{className:"urun-session-status-dot","data-phase":n}),(0,j.jsx)("span",{className:"urun-session-status-label",children:Et[n]}),o?(0,j.jsx)("span",{className:"urun-session-status-detail",children:o}):null]})}function mt({session:e,children:r,fallback:t,onStartOver:n,className:o}){let s=ee(e);if(s?.name==="live")return(0,j.jsx)("div",{className:["urun-session-gate",o].filter(Boolean).join(" "),children:r});let a=t?t(s):(0,j.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&(0,Ge.isWakingPhase)(s.name)?(0,j.jsx)(Xe,{session:e}):s&&s.name!=="idle"?(0,Ge.describeSessionPhase)(s):"Waiting for a live session\u2026"}),u=n!==void 0&&(s?.name==="error"||s?.name==="ended");return(0,j.jsxs)("div",{className:["urun-session-gate",o].filter(Boolean).join(" "),children:[a,u?(0,j.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:n,children:"Start over"}):null]})}var Ke=require("@urun-sh/core");0&&(module.exports={ComponentRenderer,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,ProgressCard,ProgressCardSchema,StatusBadge,StatusBadgeSchema,TextStream,TextStreamSchema,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunJwtProvider,UrunProvider,UrunSessionGate,UrunSessionStatus,UrunSessionWaking,UrunStreamTail,UrunVoice,authMode,createDocStore,describeSessionPhase,formatPayload,getUrunAudioContext,isWakingPhase,parseJsonObject,pushCapped,registerComponent,resumeUrunAudioContext,urunPublicEnv,useApp,useChat,useCompletion,useDocStore,useImageFrame,useMetricsPanel,useProgressCard,useRequest,useSessionDoc,useSessionPhase,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useTextStream,useUrunAudioLevel,useUrunAuth,usesWorkOSAuth});
|
package/dist/index.mjs
CHANGED
|
@@ -1,9 +1,2 @@
|
|
|
1
|
-
import{a as Q,b as xe,c as Nr}from"./chunk-SSZO4I6Y.mjs";import{a as _r,b as Or,c as Ce}from"./chunk-QAEWAWV4.mjs";import{useEffect as Vr,useMemo as jr,useState as Dr}from"react";import{Component as Lr}from"react";import{jsx as We,jsxs as Ir}from"react/jsx-runtime";var ee=class extends Lr{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error("[urun] Error caught by UrunErrorBoundary:",e,t)}render(){if(this.state.error){let{fallback:e}=this.props;return typeof e=="function"?e(this.state.error):e||Ir("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[We("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),We("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as qr}from"react";var se=qr(null);import{jsx as Te}from"react/jsx-runtime";function Fr({baseUrl:r,orgId:e,appId:t,jwt:n,authProvider:s,fallback:a,children:i}){let[d,u]=Dr(),c=Ce(),h=Q("NEXT_PUBLIC_SESSION_TOKEN")??Q("NEXT_PUBLIC_URUN_JWT"),l=xe(),f=l==="workos"&&!n,P=n??(l==="jwt"?h:void 0)??d,x=s??Q("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),T=f&&!P,y=jr(()=>({appId:t,baseUrl:r,orgId:e,jwt:P,getAccessToken:f?c?.getAccessToken:void 0,authProvider:x}),[t,c,r,x,P,e,f]);return Vr(()=>{if(!f||!c)return;let g=!1,v=c;async function S(){try{let k=await v.getAccessToken();g||u(k??void 0)}catch{g||u(void 0)}}S();let w=window.setInterval(()=>{S()},6e4);return()=>{g=!0,window.clearInterval(w)}},[c,f]),Te(ee,{fallback:a,children:T?Te("div",{role:"status","aria-live":"polite",children:"Signing in..."}):Te(se.Provider,{value:y,children:i})})}import{useContext as zr,useMemo as Je,useReducer as Br,useRef as Hr}from"react";import{App as $r}from"@urun-sh/core";function Wr(r,e){return`${r}:${JSON.stringify(e??{})}`}var Re=class{constructor(e,t){this._doc=e;this._notify=t;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(e,t){return this._doc.get(e,t)}set(e){this._doc.set(e),this._notify()}on(e,t){return this._doc.on(e,n=>t(n))}get synced(){return this._doc.synced}onSynced(e){return this._doc.onSynced(()=>{e(),this._notify()})}text(e){let t=this._doc.text(e),n=this._notify;return{append(s){t.append(s),n()},toString:()=>t.toString(),get length(){return t.length},on:(s,a)=>t.on(s,i=>{a(i),n()})}}dispose(){this._unsubscribeChange()}},Pe=class{constructor(e,t){this._stream=e;this._notify=t;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(e){return this._stream.attach(e)}attachVideo(e){return this._stream.attachVideo(e)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(e){return this._stream.seek(e)}chunks(e){return this._stream.chunks(e)}onSeeked(e){return this._stream.onSeeked(e)}on(e,t){return this._stream.on(e,t)}messages(){return this._stream.messages()}emit(e,t){return this._stream.emit(e,t)}dispose(){this._unsubscribeTrack()}},we=class{constructor(e,t){this._session=e;this._notify=t;this._unsubscribePhase=this._session.onPhase(()=>this._notify())}_session;_notify;_docs=new Map;_streams=new Map;_unsubscribePhase;_disposed=!1;get disposed(){return this._disposed}get id(){return this._session.id}get phase(){return this._session.phase}get status(){return this._session.status}onPhase(e){return this._session.onPhase(e)}whenLive(e){return this._session.whenLive(e)}request(e,t){return this._session.request(e,t)}requestStream(e,t){return this._session.requestStream(e,t)}complete(e,t){return this._session.complete(e,t)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}doc(e){let t=this._docs.get(e);return t||(t=new Re(this._session.doc(e),this._notify),this._docs.set(e,t)),t}stream(e){let t=this._streams.get(e);return t||(t=new Pe(this._session.stream(e),this._notify),this._streams.set(e,t)),t}disconnect(){this._disposed=!0;for(let e of this._docs.values())e.dispose();for(let e of this._streams.values())e.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._session.disconnect(),this._notify()}};function Jr(){let r=zr(se);if(!r)throw new Error("useApp must be used within <UrunProvider>");if(!r.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,e]=Br(s=>s+1,0),t=Hr(new Map),n=Je(()=>$r(r.appId,{baseUrl:r.baseUrl,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}),[r.appId,r.baseUrl,r.orgId,r.jwt,r.getAccessToken,r.authProvider]);return Je(()=>new Proxy({},{get(s,a){if(typeof a=="string")return i=>{let d=Wr(a,i),u=t.current.get(d);if(u&&!u.disposed)return u;let c=new we(n[a](i),e);return t.current.set(d,c),c}}}),[n])}import{useCallback as Ue,useEffect as Gr,useMemo as Xr,useRef as ae,useState as Ee}from"react";function J(r){let e=r;if(!e||typeof e.request!="function"||typeof e.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 e}function Zr(r){return r instanceof Error?r:new Error(String(r))}function Kr(r,e){let t=Xr(()=>J(r),[r]),[n,s]=Ee(void 0),[a,i]=Ee(null),[d,u]=Ee(!1),c=ae(e);c.current=e;let h=ae(0),l=ae(null),f=ae(!0);Gr(()=>(f.current=!0,()=>{f.current=!1,l.current?.abort()}),[]);let P=Ue(async y=>{l.current?.abort();let g=new AbortController;l.current=g;let v=++h.current,S=()=>f.current&&h.current===v;S()&&(u(!0),i(null));try{let w=await t.request(y,{...c.current,signal:g.signal});return S()&&(s(w),u(!1),c.current?.onSuccess?.(w)),w}catch(w){let k=Zr(w);throw S()&&(i(k),u(!1),c.current?.onError?.(k)),k}},[t]),x=Ue(y=>{P(y).catch(()=>{})},[P]),T=Ue(()=>{h.current++,l.current?.abort(),l.current=null,s(void 0),i(null),u(!1)},[]);return{mutate:x,mutateAsync:P,data:n,error:a,isPending:d,reset:T}}import{useCallback as Ge,useEffect as Yr,useMemo as Qr,useRef as ie,useState as Ae}from"react";function Xe(r){return r instanceof Error?r:new Error(String(r))}var et=r=>typeof r=="string"?r:String(r);function rt(r,e){let t=Qr(()=>J(r),[r]),[n,s]=Ae(""),[a,i]=Ae(!1),[d,u]=Ae(null),c=ie(e);c.current=e;let h=ie(0),l=ie(null),f=ie(!0);Yr(()=>(f.current=!0,()=>{f.current=!1,l.current?.cancel(),l.current=null}),[]);let P=Ge(()=>{h.current++,l.current?.cancel(),l.current=null,f.current&&i(!1)},[]),x=Ge(async T=>{l.current?.cancel();let y=++h.current,g=()=>f.current&&h.current===y,v=c.current,S=v?.parseChunk??et,w=v?.buildPayload??(m=>({prompt:m}));g()&&(s(""),u(null),i(!0));let{parseChunk:k,buildPayload:L,onFinish:A,onError:o,...p}=v??{},b="",C;try{C=t.requestStream(w(T),p),l.current=C}catch(m){let U=Xe(m);g()&&(u(U),i(!1),v?.onError?.(U));return}try{for await(let m of C){if(h.current!==y)break;b+=S(m),g()&&s(b)}g()&&(i(!1),v?.onFinish?.(b))}catch(m){let U=Xe(m);g()&&(u(U),i(!1),v?.onError?.(U))}finally{l.current===C&&(l.current=null)}},[t]);return{completion:n,complete:x,stop:P,isStreaming:a,error:d}}import{useCallback as Ze,useEffect as tt,useMemo as nt,useRef as G,useState as ue}from"react";function Ke(r){return r instanceof Error?r:new Error(String(r))}var ot=r=>typeof r=="string"?r:String(r),Ye=0;function Me(r){return Ye+=1,`${r}-${Ye}`}function st(r,e){let t=nt(()=>J(r),[r]),[n,s]=ue(()=>(e?.initialMessages??[]).map(S=>({id:S.id??Me("msg"),role:S.role,content:S.content}))),[a,i]=ue(""),[d,u]=ue(!1),[c,h]=ue(null),l=G(e);l.current=e;let f=G(n);f.current=n;let P=G(a);P.current=a;let x=G(0),T=G(null),y=G(!0);tt(()=>(y.current=!0,()=>{y.current=!1,T.current?.cancel(),T.current=null}),[]);let g=Ze(()=>{x.current++,T.current?.cancel(),T.current=null,y.current&&u(!1)},[]),v=Ze(async S=>{let w=S===void 0,k=(w?P.current:S)??"";if(!k.trim())return;T.current?.cancel();let A=++x.current,o=()=>y.current&&x.current===A,p=l.current,b=p?.parseChunk??ot,C={id:Me("msg"),role:"user",content:k},m={id:Me("msg"),role:"assistant",content:""},U=[...f.current,C].map(M=>({role:M.role,content:M.content})),R=[...f.current,C,m];f.current=R,s(R),w&&i(""),h(null),u(!0);let q=p?.buildPayload??(M=>({messages:M})),{initialMessages:Se,parseChunk:be,buildPayload:ye,onFinish:ke,onError:Ar,...E}=p??{},N=M=>{s(I=>I.map(O=>O.id===m.id?{...O,content:M}:O))},j="",_;try{_=t.requestStream(q(U),E),T.current=_}catch(M){let I=Ke(M);o()&&(h(I),u(!1),p?.onError?.(I));return}try{for await(let M of _){if(x.current!==A)break;j+=b(M),o()&&N(j)}o()&&(u(!1),p?.onFinish?.({...m,content:j}))}catch(M){let I=Ke(M);o()&&(h(I),u(!1),p?.onError?.(I))}finally{T.current===_&&(T.current=null)}},[t]);return{messages:n,input:a,setInput:i,sendMessage:v,stop:g,isStreaming:d,error:c}}var Qe=new Map;function at(r,e,t){if(!t||typeof t.safeParse!="function")throw new Error(`registerComponent("${r}"): schema must be a valid Zod schema`);Qe.set(r,{component:e,schema:t})}function er(r,e){let t=Qe.get(r);if(!t)return{error:`Unknown component: "${r}"`};let n=t.schema.safeParse(e);return n.success?{Component:t.component,validatedProps:n.data}:{error:`Validation failed for "${r}": ${n.error.message}`}}import{Fragment as ut,jsx as ce}from"react/jsx-runtime";function it({name:r,props:e,fallback:t}){let n=er(r,e);if(n.error)return console.warn(`[urun] ComponentRenderer: ${n.error}`),t?ce(ut,{children:t}):ce("div",{className:"urun-component-error",role:"alert",children:ce("span",{className:"urun-component-error-text",children:n.error})});let s=n.Component;return ce(s,{...n.validatedProps})}import{z as re}from"zod";import{jsx as Ne,jsxs as rr}from"react/jsx-runtime";var ct=re.object({step:re.number().min(0),total:re.number().min(1),label:re.string().optional(),variant:re.enum(["default","success","error"]).default("default")});function tr(r){let{step:e,total:t,label:n,variant:s="default"}=r,a=Math.min(e/t*100,100),i=e>=t;return{step:e,total:t,label:n,variant:s,percentage:a,isComplete:i}}function lt(r){let{step:e,total:t,label:n,variant:s,percentage:a}=tr(r);return rr("div",{className:"urun-progress-card","data-variant":s,children:[n&&Ne("div",{className:"urun-progress-label",children:n}),Ne("div",{className:"urun-progress-bar",children:Ne("div",{className:"urun-progress-fill",style:{width:`${a}%`}})}),rr("div",{className:"urun-progress-text",children:[e,"/",t]})]})}import{z as _e}from"zod";import{jsx as nr,jsxs as ft}from"react/jsx-runtime";var dt=_e.object({state:_e.enum(["thinking","generating","idle","error"]),message:_e.string().optional()}),pt={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function or(r){let{state:e,message:t}=r,n=e==="thinking"||e==="generating",s=t??pt[e]??e;return{state:e,message:s,isActive:n}}function mt(r){let{state:e,message:t,isActive:n}=or(r);return ft("span",{className:"urun-status-badge","data-state":e,children:[nr("span",{className:`urun-status-indicator${n?" urun-status-pulse":""}`}),nr("span",{className:"urun-status-message",children:t})]})}import{useRef as sr,useEffect as gt}from"react";import{z as Oe}from"zod";import{jsx as ar,jsxs as St}from"react/jsx-runtime";var ht=Oe.object({text:Oe.string(),streaming:Oe.boolean().default(!1)});function ir(r){let{text:e,streaming:t=!1}=r,n=e.length===0;return{text:e,streaming:t,isEmpty:n}}function vt(r){let{text:e,streaming:t}=ir(r),n=sr(null),s=sr(0);return gt(()=>{let a=n.current;a&&e.length!==s.current&&(a.textContent=e,s.current=e.length)},[e]),St("div",{className:"urun-text-stream",children:[ar("span",{ref:n,className:"urun-text-content"}),t&&ar("span",{className:"urun-text-cursor"})]})}import{z as le}from"zod";import{jsx as ur,jsxs as kt}from"react/jsx-runtime";var bt=le.object({src:le.string().url(),alt:le.string().optional(),caption:le.string().optional()});function cr(r){let{src:e,alt:t,caption:n}=r;return{src:e,alt:t??"",caption:n}}function yt(r){let{src:e,alt:t,caption:n}=cr(r);return kt("figure",{className:"urun-image-frame",children:[ur("img",{className:"urun-image",src:e,alt:t}),n&&ur("figcaption",{className:"urun-image-caption",children:n})]})}import{z as D}from"zod";import{jsx as Le,jsxs as Tt}from"react/jsx-runtime";var xt=D.object({metrics:D.array(D.object({label:D.string(),value:D.union([D.string(),D.number()]),unit:D.string().optional()}))});function lr(r){return{metrics:r.metrics.map(t=>({...t,displayValue:t.unit?`${t.value} ${t.unit}`:String(t.value)}))}}function Ct(r){let{metrics:e}=lr(r);return Le("div",{className:"urun-metrics-panel",children:e.map((t,n)=>Tt("div",{className:"urun-metric-card",children:[Le("div",{className:"urun-metric-label",children:t.label}),Le("div",{className:"urun-metric-value",children:t.displayValue})]},n))})}import{forwardRef as qe,useCallback as mr,useEffect as Ie,useImperativeHandle as Et,useRef as fr,useState as At}from"react";import Mt from"video.js";import"video.js/dist/video-js.css";import{useContext as Pt,useState as wt,useEffect as Ut}from"react";import{createContext as Rt,useState as Ro,useEffect as Po,useRef as wo}from"react";import{TransportSession as Eo}from"@urun-sh/core/internal";import{jsx as Mo}from"react/jsx-runtime";var dr=Rt(null);function pr(r){let e=Pt(dr);if(!e)throw new Error("useTrack must be used within <SessionProvider> or <UrunProvider>");let[t,n]=wt(null);return Ut(()=>{let s=e.getState()._transport;if(!s)return;let a=s.getTrackByName?.bind(s),i=a?.(r);i&&i.readyState!=="ended"&&n(i);let d=s.on("track",u=>{let c=a?.(r);c&&c.id!==u.id||(n(u),u.addEventListener("ended",()=>{n(null)}))});return()=>{d()}},[r,e]),t}import{jsx as H,jsxs as vr}from"react/jsx-runtime";function gr(r){r.posterImage?.hide?.()}var Nt=`
|
|
2
|
-
[data-urun-video]{width:100%;height:100%}
|
|
3
|
-
[data-urun-video] .video-js,[data-urun-video] .vjs-tech{width:100%;height:100%}
|
|
4
|
-
[data-urun-video] .vjs-tech{object-fit:contain}
|
|
5
|
-
.urun-video-live.vjs-has-started .vjs-poster,
|
|
6
|
-
.urun-video-live.vjs-has-started .vjs-loading-spinner,
|
|
7
|
-
.urun-video-live.vjs-has-started .vjs-big-play-button{display:none !important}
|
|
8
|
-
.urun-video-live .vjs-poster{background-color:transparent}
|
|
9
|
-
`,hr="urun-video-critical-css";function _t(){if(typeof document>"u"||document.getElementById(hr))return;let r=document.createElement("style");r.id=hr,r.textContent=Nt,document.head.appendChild(r)}var Ot=["playToggle","volumePanel","fullscreenToggle"],Lt=["playToggle","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","remainingTimeDisplay","fullscreenToggle"],Sr=qe(function(e,t){let{track:n,stream:s,src:a,type:i="video/mp4",className:d,videoClassName:u,poster:c,controls:h=!0,autoPlay:l=!0,muted:f=!0,onVideoElement:P,onPlayerReady:x,children:T}=e,y=typeof a=="string"&&a.length>0,g=!y,v=fr(null),S=fr(null),[w,k]=At(!1),L=mr(o=>{v.current=o,typeof t=="function"?t(o):t&&(t.current=o),P?.(o)},[t,P]);Et(t,()=>v.current,[]);let A=mr(()=>{let o=v.current;if(!o||!o.srcObject&&!o.src)return;f&&(o.muted=!0,o.defaultMuted=!0),o.setAttribute("playsinline",""),o.setAttribute("webkit-playsinline","");let p=o.play();p&&typeof p.then=="function"&&p.then(()=>k(!1)).catch(b=>{(b instanceof Error?b.name:String(b))!=="AbortError"&&k(!0)})},[f]);return Ie(()=>{if(typeof document>"u")return;let o=v.current;if(!o)return;_t(),f&&(o.muted=!0,o.defaultMuted=!0,o.setAttribute("muted","")),o.autoplay=l,o.setAttribute("playsinline",""),o.setAttribute("webkit-playsinline","");let p=Mt(o,{controls:h,autoplay:l,muted:f,playsinline:!0,preload:"auto",fluid:!1,bigPlayButton:!0,poster:c,userActions:{click:!0,doubleClick:!1,hotkeys:!1},controlBar:{children:g?Ot:Lt}});g&&p.addClass("urun-video-live");let b=()=>k(!1),C=()=>{p.hasStarted(!0),gr(p),b()},m=()=>{g&&A()};return o.addEventListener("playing",C),o.addEventListener("loadedmetadata",m),g&&o.addEventListener("pause",m),S.current=p,x?.(p),()=>{o.removeEventListener("playing",C),o.removeEventListener("loadedmetadata",m),o.removeEventListener("pause",m),x?.(null),S.current&&(S.current.dispose(),S.current=null)}},[g]),Ie(()=>{if(!y)return;let o=S.current;if(!o)return;let p=o.tech?.(!0)?.el?.();p&&(p.srcObject=null),o.src({src:a,type:i}),l&&A()},[y,a,i,l,A]),Ie(()=>{if(!g)return;let o=S.current;if(!o)return;let p=n??null,b=s??null;!b&&p&&(b=new MediaStream([p]));let C=o.tech?.(!0)?.el?.()??v.current;if(!C)return;if(!b){C.srcObject=null,k(!1);return}C.srcObject=b,A();let m=b.getVideoTracks()[0]??p??null,U=()=>{o.hasStarted(!0),gr(o),A()},R=()=>{C.srcObject=null,k(!1)};return m&&(m.addEventListener("unmute",U),m.addEventListener("ended",R),m.muted||U()),()=>{m&&(m.removeEventListener("unmute",U),m.removeEventListener("ended",R))}},[g,n,s,A]),vr("div",{className:d,style:{position:"relative",width:"100%",height:"100%"},"data-urun-video":"","data-urun-video-mode":g?"live":"vod",children:[H("video",{ref:L,className:["video-js","vjs-default-skin",u].filter(Boolean).join(" "),playsInline:!0}),w&&H("button",{type:"button",onClick:A,"aria-label":"Tap to play",style:{position:"absolute",inset:0,zIndex:30,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.6)",border:0,cursor:"pointer",color:"#fff"},children:vr("span",{style:{display:"inline-flex",alignItems:"center",gap:8,borderRadius:999,border:"1px solid rgba(255,255,255,0.2)",background:"rgba(255,255,255,0.1)",padding:"10px 20px",fontSize:14,fontWeight:500},children:[H("svg",{viewBox:"0 0 24 24",fill:"currentColor",width:16,height:16,"aria-hidden":!0,children:H("path",{d:"M8 5v14l11-7z"})}),"Tap to play"]})}),T]})}),It=qe(function({name:e,...t},n){let s=pr(e);return H(Sr,{ref:n,...t,track:s})}),qt=qe(function(e,t){return!!e.name&&!e.track&&!e.stream&&!(typeof e.src=="string"&&e.src)?H(It,{ref:t,...e,name:e.name}):H(Sr,{ref:t,...e})});import{forwardRef as jt,useCallback as X,useEffect as br,useImperativeHandle as Dt,useRef as Z}from"react";var de=null;function Vt(){if(typeof window>"u")return null;let r=window;return r.AudioContext??r.webkitAudioContext??null}function pe(){if(de)return de;let r=Vt();return r?(de=new r,de):null}function Ve(){let r=pe();r&&r.state==="suspended"&&r.resume().catch(()=>{})}import{jsx as zt}from"react/jsx-runtime";var Ft=1e3,yr=200;function je(...r){console.debug("[urun-audio]",...r)}var De=jt(function(e,t){let{session:n,stream:s="audio",track:a,controls:i=!1,className:d,onTrack:u,onUnlockChange:c,onAudioElement:h}=e,l=Z(null),f=Z(null),P=Z(null),x=Z(null),T=Z(u);T.current=u;let y=Z(c);y.current=c;let g=X(o=>{P.current!==o&&(P.current=o,y.current?.(o))},[]),v=X(()=>{if(typeof MediaStream>"u")return null;f.current||(f.current=new MediaStream);let o=l.current;return o&&o.srcObject!==f.current&&(o.srcObject=f.current),f.current},[]),S=X(o=>{let p=l.current;if(!p)return;let b=p.play();!b||typeof b.then!="function"||b.then(()=>{p.muted||g(!0)}).catch(C=>{let m=C instanceof Error?C.name:String(C);if(m==="AbortError"){je(`play() aborted (${o}); retrying in ${yr}ms`),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{x.current=null,S(`${o}:retry`)},yr);return}if(m==="NotAllowedError"){je(`play() blocked pending a user gesture (${o})`),g(!1);return}je(`play() failed (${o})`,C)})},[g]),w=X(o=>{let p=v();if(p){for(let b of p.getAudioTracks())b!==o&&p.removeTrack(b);o&&!p.getAudioTracks().includes(o)&&p.addTrack(o),o&&S("track-attach"),T.current?.(o)}},[v,S]),k=X(()=>{let o=l.current;o&&(v(),o.muted=!1,S("gesture"),Ve(),g(!0))},[v,S,g]);Dt(t,()=>({unlock:k,get unlocked(){return P.current===!0},get element(){return l.current}}),[k]);let L=X(o=>{l.current=o,o&&(o.setAttribute("playsinline",""),o.setAttribute("webkit-playsinline",""),v()),h?.(o)},[v,h]),A=a!==void 0;return br(()=>{if(A){w(a??null);return}if(!n)return;let o=n.stream(s),p=()=>{let R=f.current;return R?R.getAudioTracks()[0]??null:null},b=R=>{if(R!==p()&&(w(R),R)){let q=()=>{p()===R&&w(null)};R.addEventListener("ended",q)}},C=o.track;C&&C.readyState==="live"&&b(C);let m=o.on("track",R=>{R&&R.readyState!=="live"||b(R)}),U=setInterval(()=>{let R=o.track;R&&R.readyState==="live"&&b(R)},Ft);return()=>{m(),clearInterval(U)}},[n,s,A,a,w]),br(()=>()=>{x.current&&clearTimeout(x.current)},[]),zt("audio",{ref:L,className:d,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})});import{forwardRef as Bt,useCallback as me,useEffect as Ht,useImperativeHandle as $t,useRef as K}from"react";import{sessionFailureFromMediaError as kr}from"@urun-sh/core";import{jsx as Gt}from"react/jsx-runtime";var xr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Wt(...r){console.debug("[urun-voice]",...r)}var Jt=Bt(function(e,t){let{session:n,stream:s="audio",constraints:a=xr,connectTimeoutMs:i,attempts:d=3,retryDelayMs:u=1500,onActiveChange:c,onError:h,onMicStream:l,onTrack:f,onUnlockChange:P}=e,x=K(null),T=K(null),y=K(!1),g=K(c);g.current=c;let v=K(h);v.current=h;let S=K(l);S.current=l;let w=me(o=>{y.current!==o&&(y.current=o,g.current?.(o))},[]),k=me(()=>{let o=T.current;if(o){for(let p of o.getTracks())p.stop();T.current=null,S.current?.(null)}},[]),L=me(async()=>{k(),w(!1),await n.stream(s).detach().catch(()=>{})},[n,s,k,w]),A=me(async()=>{x.current?.unlock();let o;try{o=await navigator.mediaDevices.getUserMedia({audio:a,video:!1})}catch(m){let U=kr(m,n.status);throw v.current?.(U),U}k(),T.current=o,S.current?.(o);let p=o.getAudioTracks()[0];if(!p){k();let m=kr(Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"}),n.status);throw v.current?.(m),m}n.connect?.();let b;for(let m=1;m<=d;m++)try{await n.whenLive(i!==void 0?{timeout:i}:void 0),await n.stream(s).attach(p),w(!0);return}catch(U){b=U,Wt(`start attempt ${m}/${d} failed`,U),m<d&&await new Promise(R=>setTimeout(R,u))}k(),w(!1);let C=b instanceof Error?b:new Error(String(b??"voice start failed"));throw v.current?.(C),C},[n,s,a,i,d,u,k,w]);return $t(t,()=>({start:A,stop:L,unlock:()=>x.current?.unlock(),get active(){return y.current},get micStream(){return T.current},get audio(){return x.current}}),[A,L]),Ht(()=>k,[k]),Gt(De,{ref:x,session:n,stream:s,onTrack:f,onUnlockChange:P})});import{sessionFailureFromMediaError as Cr}from"@urun-sh/core";import{forwardRef as Xt,useCallback as F,useEffect as Zt,useImperativeHandle as Kt,useRef as V,useState as Yt}from"react";import{jsx as en,jsxs as rn}from"react/jsx-runtime";var Rr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Tr(...r){console.debug("[urun-camera]",...r)}var Qt=Xt(function(e,t){let{session:n,stream:s="video",constraints:a,facingMode:i="environment",mirror:d="auto",connectTimeoutMs:u,preview:c=!0,className:h,videoClassName:l,onActiveChange:f,onError:P,onStream:x,onTrack:T,children:y}=e,g=V(null),v=V(null),S=V(null),w=V(!1),k=V(i),[L,A]=Yt(i),o=V(f);o.current=f;let p=V(P);p.current=P;let b=V(x);b.current=x;let C=V(T);C.current=T;let m=F(E=>{w.current!==E&&(w.current=E,o.current?.(E))},[]),U=F(E=>{let N=g.current;N&&(N.muted=!0,N.srcObject=E,E&&N.play()?.catch?.(j=>Tr("preview play() failed",j)))},[]),R=F(()=>{S.current?.(),S.current=null;let E=v.current;if(E){for(let N of E.getTracks())N.stop();v.current=null,b.current?.(null),C.current?.(null)}U(null)},[U]),q=F(async E=>{let N=v.current,j=S.current,_;try{_=await navigator.mediaDevices.getUserMedia({video:{...Rr,...a,facingMode:E},audio:!1})}catch(O){let B=Cr(O,n.status);throw p.current?.(B),B}let M=_.getVideoTracks()[0];if(!M){for(let B of _.getTracks())B.stop();let O=Cr(Object.assign(new Error("no camera video track"),{name:"NotFoundError"}),n.status);throw p.current?.(O),O}v.current=_,k.current=E,A(E),U(_),b.current?.(_);let I=()=>{v.current===_&&(Tr("camera track ended (device removed or permission revoked)"),R(),m(!1))};M.addEventListener("ended",I),S.current=()=>M.removeEventListener("ended",I);try{n.connect?.(),await n.whenLive(u!==void 0?{timeout:u}:void 0),await n.stream(s).attachVideo(M)}catch(O){M.removeEventListener("ended",I);for(let Mr of _.getTracks())Mr.stop();v.current===_&&(v.current=N,S.current=j,U(N),b.current?.(N));let B=O instanceof Error?O:new Error(String(O));throw p.current?.(B),B}if(N&&N!==_){j?.();for(let O of N.getTracks())O.stop()}C.current?.(M),m(!0)},[n,s,a,u,U,R,m]),Se=F(E=>q(E?.facingMode??k.current),[q]),be=F(async E=>{w.current&&k.current===E||await q(E)},[q]),ye=F(()=>q(k.current==="environment"?"user":"environment"),[q]),ke=F(async()=>{R(),m(!1),await n.stream(s).detachVideo().catch(()=>{})},[n,s,R,m]);return Kt(t,()=>({start:Se,stop:ke,flip:ye,setFacingMode:be,get active(){return w.current},get facingMode(){return k.current},get stream(){return v.current},get element(){return g.current}}),[Se,ke,ye,be]),Zt(()=>R,[R]),c?rn("div",{className:h,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":L,children:[en("video",{ref:g,className:l,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...(d==="auto"?L==="user":d)?{transform:"scaleX(-1)"}:{}}}),y]}):null});import{useEffect as tn,useState as nn}from"react";var Fe={level:0,speaking:!1};function on(r,e={}){let{fftSize:t=512,intervalMs:n=100,speakingThreshold:s=.02}=e,[a,i]=nn(Fe);return tn(()=>{if(!r){i(Fe);return}let d=pe();if(!d||typeof MediaStream>"u")return;let u;r instanceof MediaStream?u=r:(u=new MediaStream,u.addTrack(r));let c,h;try{c=d.createMediaStreamSource(u),h=d.createAnalyser(),h.fftSize=t,c.connect(h)}catch{return}let l=new Uint8Array(h.fftSize),P=setInterval(()=>{h.getByteTimeDomainData(l);let x=0;for(let y=0;y<l.length;y++){let g=(l[y]-128)/128;x+=g*g}let T=Math.sqrt(x/l.length);i(y=>{let g=T>s;return Math.abs(y.level-T)<.005&&y.speaking===g?y:{level:T,speaking:g}})},n);return()=>{clearInterval(P),c.disconnect(),i(Fe)}},[r,t,n,s]),a}import{useEffect as sn,useState as an}from"react";function un(r,e){let[t,n]=an(null);return sn(()=>{if(!r||!e){n(null);return}let s=r.stream(e);return n(s.track),s.on("track",n)},[r,e]),t}import{useCallback as cn,useEffect as ln,useState as Pr}from"react";function ze(r,e){let[t,n]=Pr(null),[s,a]=Pr(!1);ln(()=>{if(!r||!e){n(null),a(!1);return}let d=r.doc(e);n(d.get()??{}),a(d.synced);let u=d.on("change",h=>n(h)),c=d.onSynced(()=>a(!0));return()=>{u(),c()}},[r,e]);let i=cn(d=>{r&&e&&r.doc(e).set(d)},[r,e]);return{snapshot:t,synced:s,set:i}}import{useEffect as dn,useState as pn}from"react";var $=200;function z(r,e,t=200){let n=[...r,e];return n.length>t?n.slice(n.length-t):n}function te(r){if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}}function Be(r){let e=r.trim();if(!e)return{ok:!1,error:"Enter a JSON object."};let t;try{t=JSON.parse(e)}catch(n){return{ok:!1,error:n instanceof Error?n.message:"Invalid JSON."}}return t===null||typeof t!="object"||Array.isArray(t)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:t}}function He(r,e,t={}){let n=t.cap??200,[s,a]=pn([]);return dn(()=>{if(a([]),!r||!e)return;let i=!0,d=r.stream(e).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await d.next();if(!i||u.done)break;a(c=>z(c,{at:Date.now(),payload:u.value},n))}})(),()=>{i=!1,d.return?.()}},[r,e,n]),s}import{jsx as fe,jsxs as ne}from"react/jsx-runtime";function mn({session:r,name:e,cap:t,className:n}){let s=He(r,e,{cap:t});return ne("div",{className:["urun-stream-tail",n].filter(Boolean).join(" "),children:[ne("div",{className:"urun-stream-tail-meta",children:[fe("code",{children:e}),ne("span",{className:"urun-stream-tail-count",children:[s.length," messages"]})]}),fe("div",{className:"urun-stream-tail-log",children:s.length===0?ne("span",{className:"urun-stream-tail-empty",children:["Waiting for ",fe("code",{children:e})," messages\u2026"]}):s.map((a,i)=>ne("div",{className:"urun-stream-tail-line",children:[fe("span",{className:"urun-stream-tail-time",children:new Date(a.at).toLocaleTimeString()})," ",te(a.payload)]},`${a.at}-${i}`))})]})}import{useCallback as fn,useState as wr}from"react";import{jsx as W,jsxs as ge}from"react/jsx-runtime";function he({placeholder:r,buttonLabel:e,disabled:t,onApply:n}){let[s,a]=wr(""),[i,d]=wr(null),u=fn(()=>{let c=Be(s);if(!c.ok){d(c.error);return}d(null),n(c.value,s.trim()),a("")},[s,n]);return ge("div",{className:"urun-doc-patch",children:[W("textarea",{className:"urun-doc-patch-input",value:s,onChange:c=>a(c.target.value),placeholder:r,rows:3}),ge("div",{className:"urun-doc-patch-actions",children:[W("button",{type:"button",className:"urun-doc-patch-button",disabled:t||!s.trim(),onClick:u,children:e}),i?W("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function gn({session:r,docKey:e,editable:t=!0,patchPlaceholder:n='{"desired": {"prompt": {"text": "a sunset"}}}',className:s}){let{snapshot:a,synced:i,set:d}=ze(r,e);return ge("div",{className:["urun-doc-panel",s].filter(Boolean).join(" "),children:[ge("div",{className:"urun-doc-panel-meta",children:[W("code",{children:e}),W("span",{className:"urun-doc-panel-synced","data-synced":i?"true":"false",children:i?"synced":"syncing\u2026"})]}),W("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(a??{},null,2)}),t?W(he,{placeholder:n,buttonLabel:"Apply patch",disabled:!r,onApply:u=>d(u)}):null]})}import{useEffect as hn,useState as vn}from"react";import{jsx as oe,jsxs as Er}from"react/jsx-runtime";function Ur(r,e=600){return r.length>e?`${r.slice(0,e)}\u2026`:r}function Sn({session:r,docKey:e="control",cap:t=200,className:n}){let[s,a]=vn([]);return hn(()=>(a([]),r?r.doc(e).on("change",d=>{a(u=>z(u,{at:Date.now(),direction:"in",text:Ur(te(d))},t))}):void 0),[r,e,t]),Er("div",{className:["urun-control-sender",n].filter(Boolean).join(" "),children:[oe(he,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${e}`,disabled:!r,onApply:(i,d)=>{r?.doc(e).set(i),a(u=>z(u,{at:Date.now(),direction:"out",text:Ur(d)},t))}}),oe("div",{className:"urun-control-sender-log",children:s.length===0?oe("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...s].reverse().map((i,d)=>Er("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[oe("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",oe("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${d}`))})]})}import{useEffect as bn,useState as yn}from"react";import{jsx as ve,jsxs as xn}from"react/jsx-runtime";function kn({session:r,trackNames:e=["video","audio"],docKeys:t=["control"],cap:n=200,className:s}){let[a,i]=yn([]),d=e.join(","),u=t.join(",");return bn(()=>{if(i([]),!r)return;let c=(l,f)=>i(P=>z(P,{at:Date.now(),kind:l,text:f},n)),h=[];h.push(r.onPhase(l=>c("phase",`phase \u2192 ${l.name}`)));for(let l of e){let f=r.stream(l);h.push(f.on("track",P=>c("track",`${l}: ${P?"track arrived":"track ended"}`)))}for(let l of t){let f=r.doc(l);h.push(f.on("change",()=>c("doc",`${l} changed`)))}return()=>h.forEach(l=>l())},[r,d,u,n]),ve("div",{className:["urun-event-spine",s].filter(Boolean).join(" "),children:a.length===0?ve("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...a].reverse().map((c,h)=>xn("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[ve("span",{className:"urun-event-spine-kind",children:c.kind})," ",ve("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${h}`))})}import{useEffect as Cn,useState as Tn}from"react";import{jsx as Y,jsxs as Un}from"react/jsx-runtime";var Rn={idle:"idle",queued:"queued",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended"};function $e(r){let[e,t]=Tn(r?.phase??null);return Cn(()=>{if(!r){t(null);return}return r.onPhase(t)},[r]),e}function Pn({session:r,className:e}){let t=$e(r),n=t?.name??"idle",s=t?.name==="queued"&&t.queue?`pos ${t.queue.position} / depth ${t.queue.depth}`:t?.name==="error"&&t.error?t.error.reason:null;return Un("span",{className:["urun-session-status",e].filter(Boolean).join(" "),"data-phase":n,children:[Y("span",{className:"urun-session-status-dot","data-phase":n}),Y("span",{className:"urun-session-status-label",children:Rn[n]}),s?Y("span",{className:"urun-session-status-detail",children:s}):null]})}function wn({session:r,children:e,fallback:t,className:n}){let s=$e(r);if(s?.name==="live")return Y("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:e});let a=t?t(s):Y("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":"Waiting for a live session\u2026"});return Y("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:a})}export{it as ComponentRenderer,Rr as DEFAULT_CAMERA_CONSTRAINTS,$ as DEFAULT_LOG_CAP,xr as DEFAULT_VOICE_CONSTRAINTS,he as DocPatchForm,yt as ImageFrame,bt as ImageFrameSchema,Ct as MetricsPanel,xt as MetricsPanelSchema,lt as ProgressCard,ct as ProgressCardSchema,mt as StatusBadge,dt as StatusBadgeSchema,vt as TextStream,ht as TextStreamSchema,De as UrunAudio,_r as UrunAuthProvider,Qt as UrunCamera,Sn as UrunControlSender,gn as UrunDocPanel,ee as UrunErrorBoundary,kn as UrunEventSpine,Or as UrunJwtProvider,Fr as UrunProvider,wn as UrunSessionGate,Pn as UrunSessionStatus,mn as UrunStreamTail,qt as UrunVideo,Jt as UrunVoice,xe as authMode,te as formatPayload,pe as getUrunAudioContext,Be as parseJsonObject,z as pushCapped,at as registerComponent,Ve as resumeUrunAudioContext,Q as urunPublicEnv,Jr as useApp,st as useChat,rt as useCompletion,cr as useImageFrame,lr as useMetricsPanel,tr as useProgressCard,Kr as useRequest,ze as useSessionDoc,$e as useSessionPhase,un as useSessionTrack,or as useStatusBadge,He as useStreamMessages,ir as useTextStream,on as useUrunAudioLevel,Ce as useUrunAuth,Nr as usesWorkOSAuth};
|
|
1
|
+
"use client"
|
|
2
|
+
import{a as Er,b as Ar,c as xe}from"./chunk-WF2OBDSX.mjs";import{useEffect as Or,useMemo as Ir,useState as qr}from"react";import{Component as _r}from"react";import{jsx as Ge,jsxs as Mr}from"react/jsx-runtime";var te=class extends _r{constructor(r){super(r),this.state={error:null}}static getDerivedStateFromError(r){return{error:r}}componentDidCatch(r,t){console.error("[urun] Error caught by UrunErrorBoundary:",r,t)}render(){if(this.state.error){let{fallback:r}=this.props;return typeof r=="function"?r(this.state.error):r||Mr("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:[Ge("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),Ge("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as Nr}from"react";var ce=Nr(null);function j(e){return e&&e.trim()?e.trim():void 0}function F(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return j(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return j(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return j(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return j(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return j(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return j(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return j(typeof process<"u"?process.env?.[e]:void 0)}}function le(){let e=F("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||F("VERCEL_ENV")==="production"?"workos":F("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Dr(){return le()==="workos"}import{jsx as Pe}from"react/jsx-runtime";function Lr({baseUrl:e,orgId:r,appId:t,jwt:n,authProvider:o,fallback:s,children:a}){let[u,c]=qr(),i=xe(),S=F("NEXT_PUBLIC_SESSION_TOKEN")??F("NEXT_PUBLIC_URUN_JWT"),l=le(),m=l==="workos"&&!n,x=n??(l==="jwt"?S:void 0)??u,C=o??F("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),b=m&&!x,T=Ir(()=>({appId:t,baseUrl:e,orgId:r,jwt:x,getAccessToken:m?i?.getAccessToken:void 0,authProvider:C}),[t,i,e,C,x,r,m]);return Or(()=>{if(!m||!i)return;let k=!1,h=i;async function v(){try{let R=await h.getAccessToken();k||c(R??void 0)}catch{k||c(void 0)}}v();let P=window.setInterval(()=>{v()},6e4);return()=>{k=!0,window.clearInterval(P)}},[i,m]),Pe(te,{fallback:s,children:b?Pe("div",{role:"status","aria-live":"polite",children:"Signing in..."}):Pe(ce.Provider,{value:T,children:a})})}import{useContext as Wr,useMemo as Ke,useReducer as Fr,useRef as Br}from"react";import{App as Vr}from"@urun-sh/core";function Hr(e,r){return`${e}:${JSON.stringify(r??{})}`}var we=class{constructor(r,t){this._doc=r;this._notify=t;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(r,t){return this._doc.get(r,t)}set(r){this._doc.set(r),this._notify()}on(r,t){return this._doc.on(r,n=>t(n))}get synced(){return this._doc.synced}onSynced(r){return this._doc.onSynced(()=>{r(),this._notify()})}text(r){let t=this._doc.text(r),n=this._notify;return{append(o){t.append(o),n()},toString:()=>t.toString(),get length(){return t.length},on:(o,s)=>t.on(o,a=>{s(a),n()})}}dispose(){this._unsubscribeChange()}},Ee=class{constructor(r,t){this._stream=r;this._notify=t;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(r){return this._stream.attach(r)}attachVideo(r){return this._stream.attachVideo(r)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(r){return this._stream.seek(r)}chunks(r){return this._stream.chunks(r)}onSeeked(r){return this._stream.onSeeked(r)}on(r,t){return this._stream.on(r,t)}messages(){return this._stream.messages()}emit(r,t){return this._stream.emit(r,t)}dispose(){this._unsubscribeTrack()}},Ae=class{constructor(r,t){this._session=r;this._notify=t;this._unsubscribePhase=this._session.onPhase(()=>this._notify())}_session;_notify;_docs=new Map;_streams=new Map;_unsubscribePhase;_disposed=!1;get disposed(){return this._disposed}get id(){return this._session.id}get phase(){return this._session.phase}get status(){return this._session.status}onPhase(r){return this._session.onPhase(r)}whenLive(r){return this._session.whenLive(r)}recover(){this._session.recover()}onRecovery(r){return this._session.onRecovery(r)}request(r,t){return this._session.request(r,t)}requestStream(r,t){return this._session.requestStream(r,t)}complete(r,t){return this._session.complete(r,t)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}doc(r){let t=this._docs.get(r);return t||(t=new we(this._session.doc(r),this._notify),this._docs.set(r,t)),t}stream(r){let t=this._streams.get(r);return t||(t=new Ee(this._session.stream(r),this._notify),this._streams.set(r,t)),t}disconnect(){this._disposed=!0;for(let r of this._docs.values())r.dispose();for(let r of this._streams.values())r.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._session.disconnect(),this._notify()}};function $r(){let e=Wr(ce);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,r]=Fr(o=>o+1,0),t=Br(new Map),n=Ke(()=>Vr(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider]);return Ke(()=>new Proxy({},{get(o,s){if(typeof s=="string")return a=>{let u=Hr(s,a),c=t.current.get(u);if(c&&!c.disposed)return c;let i=new Ae(n[s](a),r);return t.current.set(u,i),i}}}),[n])}import{useCallback as _e,useEffect as jr,useMemo as Jr,useRef as de,useState as Me}from"react";function Z(e){let r=e;if(!r||typeof r.request!="function"||typeof r.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 r}function zr(e){return e instanceof Error?e:new Error(String(e))}function Xr(e,r){let t=Jr(()=>Z(e),[e]),[n,o]=Me(void 0),[s,a]=Me(null),[u,c]=Me(!1),i=de(r);i.current=r;let S=de(0),l=de(null),m=de(!0);jr(()=>(m.current=!0,()=>{m.current=!1,l.current?.abort()}),[]);let x=_e(async T=>{l.current?.abort();let k=new AbortController;l.current=k;let h=++S.current,v=()=>m.current&&S.current===h;v()&&(c(!0),a(null));try{let P=await t.request(T,{...i.current,signal:k.signal});return v()&&(o(P),c(!1),i.current?.onSuccess?.(P)),P}catch(P){let R=zr(P);throw v()&&(a(R),c(!1),i.current?.onError?.(R)),R}},[t]),C=_e(T=>{x(T).catch(()=>{})},[x]),b=_e(()=>{S.current++,l.current?.abort(),l.current=null,o(void 0),a(null),c(!1)},[]);return{mutate:C,mutateAsync:x,data:n,error:s,isPending:u,reset:b}}import{useCallback as Ze,useEffect as Gr,useMemo as Kr,useRef as pe,useState as Ne}from"react";function Ye(e){return e instanceof Error?e:new Error(String(e))}var Zr=e=>typeof e=="string"?e:String(e);function Yr(e,r){let t=Kr(()=>Z(e),[e]),[n,o]=Ne(""),[s,a]=Ne(!1),[u,c]=Ne(null),i=pe(r);i.current=r;let S=pe(0),l=pe(null),m=pe(!0);Gr(()=>(m.current=!0,()=>{m.current=!1,l.current?.cancel(),l.current=null}),[]);let x=Ze(()=>{S.current++,l.current?.cancel(),l.current=null,m.current&&a(!1)},[]),C=Ze(async b=>{l.current?.cancel();let T=++S.current,k=()=>m.current&&S.current===T,h=i.current,v=h?.parseChunk??Zr,P=h?.buildPayload??(y=>({prompt:y}));k()&&(o(""),c(null),a(!0));let{parseChunk:R,buildPayload:q,onFinish:O,onError:d,...U}=h??{},p="",f;try{f=t.requestStream(P(b),U),l.current=f}catch(y){let w=Ye(y);k()&&(c(w),a(!1),h?.onError?.(w));return}try{for await(let y of f){if(S.current!==T)break;p+=v(y),k()&&o(p)}k()&&(a(!1),h?.onFinish?.(p))}catch(y){let w=Ye(y);k()&&(c(w),a(!1),h?.onError?.(w))}finally{l.current===f&&(l.current=null)}},[t]);return{completion:n,complete:C,stop:x,isStreaming:s,error:u}}import{useCallback as Qe,useEffect as Qr,useMemo as et,useRef as Y,useState as me}from"react";function er(e){return e instanceof Error?e:new Error(String(e))}var rt=e=>typeof e=="string"?e:String(e),rr=0;function De(e){return rr+=1,`${e}-${rr}`}function tt(e,r){let t=et(()=>Z(e),[e]),[n,o]=me(()=>(r?.initialMessages??[]).map(v=>({id:v.id??De("msg"),role:v.role,content:v.content}))),[s,a]=me(""),[u,c]=me(!1),[i,S]=me(null),l=Y(r);l.current=r;let m=Y(n);m.current=n;let x=Y(s);x.current=s;let C=Y(0),b=Y(null),T=Y(!0);Qr(()=>(T.current=!0,()=>{T.current=!1,b.current?.cancel(),b.current=null}),[]);let k=Qe(()=>{C.current++,b.current?.cancel(),b.current=null,T.current&&c(!1)},[]),h=Qe(async v=>{let P=v===void 0,R=(P?x.current:v)??"";if(!R.trim())return;b.current?.cancel();let O=++C.current,d=()=>T.current&&C.current===O,U=l.current,p=U?.parseChunk??rt,f={id:De("msg"),role:"user",content:R},y={id:De("msg"),role:"assistant",content:""},w=[...m.current,f].map(A=>({role:A.role,content:A.content})),g=[...m.current,f,y];m.current=g,o(g),P&&a(""),S(null),c(!0);let _=U?.buildPayload??(A=>({messages:A})),{initialMessages:re,parseChunk:Ce,buildPayload:Re,onFinish:Ue,onError:Pr,...E}=U??{},M=A=>{o(I=>I.map(D=>D.id===y.id?{...D,content:A}:D))},W="",N;try{N=t.requestStream(_(w),E),b.current=N}catch(A){let I=er(A);d()&&(S(I),c(!1),U?.onError?.(I));return}try{for await(let A of N){if(C.current!==O)break;W+=p(A),d()&&M(W)}d()&&(c(!1),U?.onFinish?.({...y,content:W}))}catch(A){let I=er(A);d()&&(S(I),c(!1),U?.onError?.(I))}finally{b.current===N&&(b.current=null)}},[t]);return{messages:n,input:s,setInput:a,sendMessage:h,stop:k,isStreaming:u,error:i}}var tr=new Map;function nt(e,r,t){if(!t||typeof t.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);tr.set(e,{component:r,schema:t})}function nr(e,r){let t=tr.get(e);if(!t)return{error:`Unknown component: "${e}"`};let n=t.schema.safeParse(r);return n.success?{Component:t.component,validatedProps:n.data}:{error:`Validation failed for "${e}": ${n.error.message}`}}import{Fragment as st,jsx as fe}from"react/jsx-runtime";function ot({name:e,props:r,fallback:t}){let n=nr(e,r);if(n.error)return console.warn(`[urun] ComponentRenderer: ${n.error}`),t?fe(st,{children:t}):fe("div",{className:"urun-component-error",role:"alert",children:fe("span",{className:"urun-component-error-text",children:n.error})});let o=n.Component;return fe(o,{...n.validatedProps})}import{z as ne}from"zod";import{jsx as Oe,jsxs as or}from"react/jsx-runtime";var at=ne.object({step:ne.number().min(0),total:ne.number().min(1),label:ne.string().optional(),variant:ne.enum(["default","success","error"]).default("default")});function sr(e){let{step:r,total:t,label:n,variant:o="default"}=e,s=Math.min(r/t*100,100),a=r>=t;return{step:r,total:t,label:n,variant:o,percentage:s,isComplete:a}}function it(e){let{step:r,total:t,label:n,variant:o,percentage:s}=sr(e);return or("div",{className:"urun-progress-card","data-variant":o,children:[n&&Oe("div",{className:"urun-progress-label",children:n}),Oe("div",{className:"urun-progress-bar",children:Oe("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),or("div",{className:"urun-progress-text",children:[r,"/",t]})]})}import{z as Ie}from"zod";import{jsx as ar,jsxs as dt}from"react/jsx-runtime";var ut=Ie.object({state:Ie.enum(["thinking","generating","idle","error"]),message:Ie.string().optional()}),ct={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function ir(e){let{state:r,message:t}=e,n=r==="thinking"||r==="generating",o=t??ct[r]??r;return{state:r,message:o,isActive:n}}function lt(e){let{state:r,message:t,isActive:n}=ir(e);return dt("span",{className:"urun-status-badge","data-state":r,children:[ar("span",{className:`urun-status-indicator${n?" urun-status-pulse":""}`}),ar("span",{className:"urun-status-message",children:t})]})}import{useRef as ur,useEffect as pt}from"react";import{z as qe}from"zod";import{jsx as cr,jsxs as gt}from"react/jsx-runtime";var mt=qe.object({text:qe.string(),streaming:qe.boolean().default(!1)});function lr(e){let{text:r,streaming:t=!1}=e,n=r.length===0;return{text:r,streaming:t,isEmpty:n}}function ft(e){let{text:r,streaming:t}=lr(e),n=ur(null),o=ur(0);return pt(()=>{let s=n.current;s&&r.length!==o.current&&(s.textContent=r,o.current=r.length)},[r]),gt("div",{className:"urun-text-stream",children:[cr("span",{ref:n,className:"urun-text-content"}),t&&cr("span",{className:"urun-text-cursor"})]})}import{z as ge}from"zod";import{jsx as dr,jsxs as vt}from"react/jsx-runtime";var St=ge.object({src:ge.string().url(),alt:ge.string().optional(),caption:ge.string().optional()});function pr(e){let{src:r,alt:t,caption:n}=e;return{src:r,alt:t??"",caption:n}}function ht(e){let{src:r,alt:t,caption:n}=pr(e);return vt("figure",{className:"urun-image-frame",children:[dr("img",{className:"urun-image",src:r,alt:t}),n&&dr("figcaption",{className:"urun-image-caption",children:n})]})}import{z as B}from"zod";import{jsx as Le,jsxs as bt}from"react/jsx-runtime";var kt=B.object({metrics:B.array(B.object({label:B.string(),value:B.union([B.string(),B.number()]),unit:B.string().optional()}))});function mr(e){return{metrics:e.metrics.map(t=>({...t,displayValue:t.unit?`${t.value} ${t.unit}`:String(t.value)}))}}function yt(e){let{metrics:r}=mr(e);return Le("div",{className:"urun-metrics-panel",children:r.map((t,n)=>bt("div",{className:"urun-metric-card",children:[Le("div",{className:"urun-metric-label",children:t.label}),Le("div",{className:"urun-metric-value",children:t.displayValue})]},n))})}import{forwardRef as Ct,useCallback as Q,useEffect as We,useImperativeHandle as Rt,useRef as ee}from"react";import{observePageLifecycle as Ut}from"@urun-sh/core";var Se=null;function Tt(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function he(){if(Se)return Se;let e=Tt();return e?(Se=new e,Se):null}function ve(){let e=he();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{jsx as Pt}from"react/jsx-runtime";var xt=1e3,fr=200;function Fe(...e){console.debug("[urun-audio]",...e)}var Be=Ct(function(r,t){let{session:n,stream:o="audio",track:s,controls:a=!1,className:u,onTrack:c,onUnlockChange:i,onAudioElement:S}=r,l=ee(null),m=ee(null),x=ee(null),C=ee(null),b=ee(c);b.current=c;let T=ee(i);T.current=i;let k=Q(d=>{x.current!==d&&(x.current=d,T.current?.(d))},[]),h=Q(()=>{if(typeof MediaStream>"u")return null;m.current||(m.current=new MediaStream);let d=l.current;return d&&d.srcObject!==m.current&&(d.srcObject=m.current),m.current},[]),v=Q(d=>{let U=l.current;if(!U)return;let p=U.play();!p||typeof p.then!="function"||p.then(()=>{U.muted||k(!0)}).catch(f=>{let y=f instanceof Error?f.name:String(f);if(y==="AbortError"){Fe(`play() aborted (${d}); retrying in ${fr}ms`),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>{C.current=null,v(`${d}:retry`)},fr);return}if(y==="NotAllowedError"){Fe(`play() blocked pending a user gesture (${d})`),k(!1);return}Fe(`play() failed (${d})`,f)})},[k]),P=Q(d=>{let U=h();if(U){for(let p of U.getAudioTracks())p!==d&&U.removeTrack(p);d&&!U.getAudioTracks().includes(d)&&U.addTrack(d),d&&v("track-attach"),b.current?.(d)}},[h,v]),R=Q(()=>{let d=l.current;d&&(h(),d.muted=!1,v("gesture"),ve(),k(!0))},[h,v,k]);Rt(t,()=>({unlock:R,get unlocked(){return x.current===!0},get element(){return l.current}}),[R]);let q=Q(d=>{l.current=d,d&&(d.setAttribute("playsinline",""),d.setAttribute("webkit-playsinline",""),h()),S?.(d)},[h,S]),O=s!==void 0;return We(()=>{if(O){P(s??null);return}if(!n)return;let d=n.stream(o),U=()=>{let g=m.current;return g?g.getAudioTracks()[0]??null:null},p=g=>{if(g!==U()&&(P(g),g)){let _=()=>{U()===g&&P(null)};g.addEventListener("ended",_)}},f=d.track;f&&f.readyState==="live"&&p(f);let y=d.on("track",g=>{g&&g.readyState!=="live"||p(g)}),w=setInterval(()=>{let g=d.track;g&&g.readyState==="live"&&p(g)},xt);return()=>{y(),clearInterval(w)}},[n,o,O,s,P]),We(()=>Ut(()=>{ve(),x.current===!0&&v("foreground")}),[v]),We(()=>()=>{C.current&&clearTimeout(C.current)},[]),Pt("audio",{ref:q,className:u,autoPlay:!0,playsInline:!0,controls:a,"data-urun-audio":""})});import{forwardRef as wt,useCallback as oe,useEffect as gr,useImperativeHandle as Et,useRef as J}from"react";import{observePageLifecycle as At,sessionFailureFromMediaError as Sr}from"@urun-sh/core";import{jsx as Mt}from"react/jsx-runtime";var hr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Ve(...e){console.debug("[urun-voice]",...e)}var _t=wt(function(r,t){let{session:n,stream:o="audio",constraints:s=hr,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:i,onError:S,onMicStream:l,onTrack:m,onUnlockChange:x}=r,C=J(null),b=J(null),T=J(!1),k=J(i);k.current=i;let h=J(S);h.current=S;let v=J(l);v.current=l;let P=oe(p=>{T.current!==p&&(T.current=p,k.current?.(p))},[]),R=oe(()=>{let p=b.current;if(p){for(let f of p.getTracks())f.stop();b.current=null,v.current?.(null)}},[]),q=oe(async()=>{R(),P(!1),await n.stream(o).detach().catch(()=>{})},[n,o,R,P]),O=oe(async()=>{C.current?.unlock();let p;try{p=await navigator.mediaDevices.getUserMedia({audio:s,video:!1})}catch(g){let _=Sr(g,n.status);throw h.current?.(_),_}R(),b.current=p,v.current?.(p);let f=p.getAudioTracks()[0];if(!f){R();let g=Sr(Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"}),n.status);throw h.current?.(g),g}n.connect?.();let y;for(let g=1;g<=u;g++)try{await n.whenLive(a!==void 0?{timeout:a}:void 0),await n.stream(o).attach(f),P(!0);return}catch(_){y=_,Ve(`start attempt ${g}/${u} failed`,_),g<u&&await new Promise(re=>setTimeout(re,c))}R(),P(!1);let w=y instanceof Error?y:new Error(String(y??"voice start failed"));throw h.current?.(w),w},[n,o,s,a,u,c,R,P]);Et(t,()=>({start:O,stop:q,unlock:()=>C.current?.unlock(),get active(){return T.current},get micStream(){return b.current},get audio(){return C.current}}),[O,q]);let d=J(!1),U=oe(async()=>{if(!T.current||d.current)return;let p=b.current?.getAudioTracks()[0]??null;if(p&&p.readyState==="live"){try{await n.stream(o).attach(p)}catch(f){Ve("foreground mic re-assert failed (will retry on next pass)",f)}return}d.current=!0;try{let f=await navigator.mediaDevices.getUserMedia({audio:s,video:!1}),y=f.getAudioTracks()[0];if(!y){for(let w of f.getTracks())w.stop();throw new Error("no microphone audio track after foreground re-acquire")}R(),b.current=f,v.current?.(f),await n.stream(o).attach(y)}catch(f){let y=f instanceof Error?f:new Error(String(f));Ve("foreground mic re-acquire failed",y),h.current?.(y)}finally{d.current=!1}},[n,o,s,R]);return gr(()=>{let p=()=>{U()};return typeof n.onRecovery=="function"?n.onRecovery(p):At(p)},[n,U]),gr(()=>R,[R]),Mt(Be,{ref:C,session:n,stream:o,onTrack:m,onUnlockChange:x})});import{sessionFailureFromMediaError as vr}from"@urun-sh/core";import{forwardRef as Nt,useCallback as V,useEffect as Dt,useImperativeHandle as Ot,useRef as L,useState as It}from"react";import{jsx as Lt,jsxs as Wt}from"react/jsx-runtime";var yr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function kr(...e){console.debug("[urun-camera]",...e)}var qt=Nt(function(r,t){let{session:n,stream:o="video",constraints:s,facingMode:a="environment",mirror:u="auto",connectTimeoutMs:c,preview:i=!0,className:S,videoClassName:l,onActiveChange:m,onError:x,onStream:C,onTrack:b,children:T}=r,k=L(null),h=L(null),v=L(null),P=L(!1),R=L(a),[q,O]=It(a),d=L(m);d.current=m;let U=L(x);U.current=x;let p=L(C);p.current=C;let f=L(b);f.current=b;let y=V(E=>{P.current!==E&&(P.current=E,d.current?.(E))},[]),w=V(E=>{let M=k.current;M&&(M.muted=!0,M.srcObject=E,E&&M.play()?.catch?.(W=>kr("preview play() failed",W)))},[]),g=V(()=>{v.current?.(),v.current=null;let E=h.current;if(E){for(let M of E.getTracks())M.stop();h.current=null,p.current?.(null),f.current?.(null)}w(null)},[w]),_=V(async E=>{let M=h.current,W=v.current,N;try{N=await navigator.mediaDevices.getUserMedia({video:{...yr,...s,facingMode:E},audio:!1})}catch(D){let $=vr(D,n.status);throw U.current?.($),$}let A=N.getVideoTracks()[0];if(!A){for(let $ of N.getTracks())$.stop();let D=vr(Object.assign(new Error("no camera video track"),{name:"NotFoundError"}),n.status);throw U.current?.(D),D}h.current=N,R.current=E,O(E),w(N),p.current?.(N);let I=()=>{h.current===N&&(kr("camera track ended (device removed or permission revoked)"),g(),y(!1))};A.addEventListener("ended",I),v.current=()=>A.removeEventListener("ended",I);try{n.connect?.(),await n.whenLive(c!==void 0?{timeout:c}:void 0),await n.stream(o).attachVideo(A)}catch(D){A.removeEventListener("ended",I);for(let wr of N.getTracks())wr.stop();h.current===N&&(h.current=M,v.current=W,w(M),p.current?.(M));let $=D instanceof Error?D:new Error(String(D));throw U.current?.($),$}if(M&&M!==N){W?.();for(let D of M.getTracks())D.stop()}f.current?.(A),y(!0)},[n,o,s,c,w,g,y]),re=V(E=>_(E?.facingMode??R.current),[_]),Ce=V(async E=>{P.current&&R.current===E||await _(E)},[_]),Re=V(()=>_(R.current==="environment"?"user":"environment"),[_]),Ue=V(async()=>{g(),y(!1),await n.stream(o).detachVideo().catch(()=>{})},[n,o,g,y]);return Ot(t,()=>({start:re,stop:Ue,flip:Re,setFacingMode:Ce,get active(){return P.current},get facingMode(){return R.current},get stream(){return h.current},get element(){return k.current}}),[re,Ue,Re,Ce]),Dt(()=>g,[g]),i?Wt("div",{className:S,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":q,children:[Lt("video",{ref:k,className:l,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...(u==="auto"?q==="user":u)?{transform:"scaleX(-1)"}:{}}}),T]}):null});import{useEffect as Ft,useState as Bt}from"react";var He={level:0,speaking:!1};function Vt(e,r={}){let{fftSize:t=512,intervalMs:n=100,speakingThreshold:o=.02}=r,[s,a]=Bt(He);return Ft(()=>{if(!e){a(He);return}let u=he();if(!u||typeof MediaStream>"u")return;let c;e instanceof MediaStream?c=e:(c=new MediaStream,c.addTrack(e));let i,S;try{i=u.createMediaStreamSource(c),S=u.createAnalyser(),S.fftSize=t,i.connect(S)}catch{return}let l=new Uint8Array(S.fftSize),x=setInterval(()=>{S.getByteTimeDomainData(l);let C=0;for(let T=0;T<l.length;T++){let k=(l[T]-128)/128;C+=k*k}let b=Math.sqrt(C/l.length);a(T=>{let k=b>o;return Math.abs(T.level-b)<.005&&T.speaking===k?T:{level:b,speaking:k}})},n);return()=>{clearInterval(x),i.disconnect(),a(He)}},[e,t,n,o]),s}import{useEffect as Ht,useState as $t}from"react";function jt(e,r){let[t,n]=$t(null);return Ht(()=>{if(!e||!r){n(null);return}let o=e.stream(r);return n(o.track),o.on("track",n)},[e,r]),t}import{useCallback as Zt}from"react";import{useEffect as Gt,useMemo as Kt}from"react";import{createStore as Jt}from"zustand/vanilla";import{useStore as zt}from"zustand";var Xt=()=>{};function $e(e,r={}){let t=i=>{e?.set(i)},n=()=>e?e.get()??{}:{},o=Jt(()=>({doc:n(),synced:e?e.synced:!1,set:t})),s=null,a=()=>{if(s){for(let i of s)i();s=null}},u=()=>e?(s||(o.setState({doc:n(),synced:e.synced}),s=[e.on("change",i=>o.setState({doc:i})),e.onSynced(()=>o.setState({synced:!0}))]),a):Xt,c=(i=>zt(o,i));return Object.assign(c,{getState:o.getState,getInitialState:o.getInitialState,subscribe:o.subscribe,set:t,bind:u,unbind:a}),r.bind!==!1&&u(),c}function se(e,r){let t=Kt(()=>$e(e&&r?e.doc(r):null,{bind:!1}),[e,r]);return Gt(()=>t.bind(),[t]),t}function Yt(e,r,t){let o=se(e,r)(t??(u=>u)),s=Zt(u=>{e&&r&&e.doc(r).set(u)},[e,r]);if(t)return o;let a=o;return{snapshot:e&&r?a.doc:null,synced:a.synced,set:s}}import{useEffect as Qt,useState as en}from"react";var z=200;function H(e,r,t=200){let n=[...e,r];return n.length>t?n.slice(n.length-t):n}function ae(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function je(e){let r=e.trim();if(!r)return{ok:!1,error:"Enter a JSON object."};let t;try{t=JSON.parse(r)}catch(n){return{ok:!1,error:n instanceof Error?n.message:"Invalid JSON."}}return t===null||typeof t!="object"||Array.isArray(t)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:t}}function Je(e,r,t={}){let n=t.cap??200,[o,s]=en([]);return Qt(()=>{if(s([]),!e||!r)return;let a=!0,u=e.stream(r).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await u.next();if(!a||c.done)break;s(i=>H(i,{at:Date.now(),payload:c.value},n))}})(),()=>{a=!1,u.return?.()}},[e,r,n]),o}import{jsx as ke,jsxs as ie}from"react/jsx-runtime";function rn({session:e,name:r,cap:t,className:n}){let o=Je(e,r,{cap:t});return ie("div",{className:["urun-stream-tail",n].filter(Boolean).join(" "),children:[ie("div",{className:"urun-stream-tail-meta",children:[ke("code",{children:r}),ie("span",{className:"urun-stream-tail-count",children:[o.length," messages"]})]}),ke("div",{className:"urun-stream-tail-log",children:o.length===0?ie("span",{className:"urun-stream-tail-empty",children:["Waiting for ",ke("code",{children:r})," messages\u2026"]}):o.map((s,a)=>ie("div",{className:"urun-stream-tail-line",children:[ke("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",ae(s.payload)]},`${s.at}-${a}`))})]})}import{useCallback as tn,useState as br}from"react";import{jsx as X,jsxs as ye}from"react/jsx-runtime";function be({placeholder:e,buttonLabel:r,disabled:t,onApply:n}){let[o,s]=br(""),[a,u]=br(null),c=tn(()=>{let i=je(o);if(!i.ok){u(i.error);return}u(null),n(i.value,o.trim()),s("")},[o,n]);return ye("div",{className:"urun-doc-patch",children:[X("textarea",{className:"urun-doc-patch-input",value:o,onChange:i=>s(i.target.value),placeholder:e,rows:3}),ye("div",{className:"urun-doc-patch-actions",children:[X("button",{type:"button",className:"urun-doc-patch-button",disabled:t||!o.trim(),onClick:c,children:r}),a?X("span",{className:"urun-doc-patch-error",role:"alert",children:a}):null]})]})}function nn({session:e,docKey:r,editable:t=!0,patchPlaceholder:n='{"desired": {"prompt": {"text": "a sunset"}}}',className:o}){let s=se(e,r),a=s(i=>i.doc),u=s(i=>i.synced),c=s(i=>i.set);return ye("div",{className:["urun-doc-panel",o].filter(Boolean).join(" "),children:[ye("div",{className:"urun-doc-panel-meta",children:[X("code",{children:r}),X("span",{className:"urun-doc-panel-synced","data-synced":u?"true":"false",children:u?"synced":"syncing\u2026"})]}),X("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(a??{},null,2)}),t?X(be,{placeholder:n,buttonLabel:"Apply patch",disabled:!e,onApply:i=>c(i)}):null]})}import{useEffect as on,useState as sn}from"react";import{jsx as ue,jsxs as Cr}from"react/jsx-runtime";function Tr(e,r=600){return e.length>r?`${e.slice(0,r)}\u2026`:e}function an({session:e,docKey:r="control",cap:t=200,className:n}){let[o,s]=sn([]);return on(()=>(s([]),e?e.doc(r).on("change",u=>{s(c=>H(c,{at:Date.now(),direction:"in",text:Tr(ae(u))},t))}):void 0),[e,r,t]),Cr("div",{className:["urun-control-sender",n].filter(Boolean).join(" "),children:[ue(be,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${r}`,disabled:!e,onApply:(a,u)=>{e?.doc(r).set(a),s(c=>H(c,{at:Date.now(),direction:"out",text:Tr(u)},t))}}),ue("div",{className:"urun-control-sender-log",children:o.length===0?ue("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...o].reverse().map((a,u)=>Cr("div",{className:"urun-control-sender-line","data-direction":a.direction,children:[ue("span",{className:"urun-control-sender-dir",children:a.direction==="out"?"sent":"change"})," ",ue("span",{className:"urun-control-sender-time",children:new Date(a.at).toLocaleTimeString()})," ",a.text]},`${a.at}-${u}`))})]})}import{useEffect as un,useState as cn}from"react";import{jsx as Te,jsxs as dn}from"react/jsx-runtime";function ln({session:e,trackNames:r=["video","audio"],docKeys:t=["control"],cap:n=200,className:o}){let[s,a]=cn([]),u=r.join(","),c=t.join(",");return un(()=>{if(a([]),!e)return;let i=(l,m)=>a(x=>H(x,{at:Date.now(),kind:l,text:m},n)),S=[];S.push(e.onPhase(l=>i("phase",`phase \u2192 ${l.name}`)));for(let l of r){let m=e.stream(l);S.push(m.on("track",x=>i("track",`${l}: ${x?"track arrived":"track ended"}`)))}for(let l of t){let m=e.doc(l);S.push(m.on("change",()=>i("doc",`${l} changed`)))}return()=>S.forEach(l=>l())},[e,u,c,n]),Te("div",{className:["urun-event-spine",o].filter(Boolean).join(" "),children:s.length===0?Te("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((i,S)=>dn("div",{className:"urun-event-spine-line","data-kind":i.kind,children:[Te("span",{className:"urun-event-spine-kind",children:i.kind})," ",Te("span",{className:"urun-event-spine-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${S}`))})}import{describeSessionPhase as yn,isWakingPhase as bn}from"@urun-sh/core";import{useEffect as pn,useState as mn}from"react";function G(e){let[r,t]=mn(e?.phase??null);return pn(()=>{if(!e){t(null);return}return e.onPhase(t)},[e]),r}import{describeSessionPhase as vn}from"@urun-sh/core";import{useEffect as fn,useRef as gn,useState as Sn}from"react";import{isWakingPhase as hn}from"@urun-sh/core";function ze(e){let r=G(e),t=hn(r?.name),n=gn(void 0);t?n.current??=Date.now():n.current=void 0;let o=t?r?.wakingSince??n.current:void 0,s=()=>o!==void 0?Math.max(0,Math.floor((Date.now()-o)/1e3)):0,[a,u]=Sn(s);return fn(()=>{if(o===void 0){u(0);return}u(Math.max(0,Math.floor((Date.now()-o)/1e3)));let c=setInterval(()=>{u(Math.max(0,Math.floor((Date.now()-o)/1e3)))},1e3);return()=>clearInterval(c)},[o]),{waking:t,phase:r,state:t?r?.runtime?.state:void 0,reason:t?r?.runtime?.reason:void 0,since:o,seconds:t?a:0}}import{Fragment as kn,jsx as Rr,jsxs as Ur}from"react/jsx-runtime";function Xe({session:e,render:r,className:t}){let n=ze(e);return!n.waking||!n.phase?null:Rr("span",{className:["urun-session-waking",t].filter(Boolean).join(" "),"data-phase":n.phase.name,"data-runtime-state":n.state,children:r?r(n):Ur(kn,{children:[Rr("span",{className:"urun-session-waking-label",children:vn(n.phase)})," ",Ur("span",{className:"urun-session-waking-elapsed",children:["(",n.seconds,"s)"]})]})})}import{jsx as K,jsxs as xr}from"react/jsx-runtime";var Tn={idle:"idle",queued:"queued",unavailable:"unavailable",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended"};function Cn({session:e,className:r}){let t=G(e),n=t?.name??"idle",o=t?.name==="queued"&&t.queue?`pos ${t.queue.position} / depth ${t.queue.depth}`:t?.name==="error"&&t.error?t.error.reason:t?.runtime?.reason??null;return xr("span",{className:["urun-session-status",r].filter(Boolean).join(" "),"data-phase":n,children:[K("span",{className:"urun-session-status-dot","data-phase":n}),K("span",{className:"urun-session-status-label",children:Tn[n]}),o?K("span",{className:"urun-session-status-detail",children:o}):null]})}function Rn({session:e,children:r,fallback:t,onStartOver:n,className:o}){let s=G(e);if(s?.name==="live")return K("div",{className:["urun-session-gate",o].filter(Boolean).join(" "),children:r});let a=t?t(s):K("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&bn(s.name)?K(Xe,{session:e}):s&&s.name!=="idle"?yn(s):"Waiting for a live session\u2026"}),u=n!==void 0&&(s?.name==="error"||s?.name==="ended");return xr("div",{className:["urun-session-gate",o].filter(Boolean).join(" "),children:[a,u?K("button",{type:"button",className:"urun-session-gate-start-over",onClick:n,children:"Start over"}):null]})}import{describeSessionPhase as ma,isWakingPhase as fa}from"@urun-sh/core";export{ot as ComponentRenderer,yr as DEFAULT_CAMERA_CONSTRAINTS,z as DEFAULT_LOG_CAP,hr as DEFAULT_VOICE_CONSTRAINTS,be as DocPatchForm,ht as ImageFrame,St as ImageFrameSchema,yt as MetricsPanel,kt as MetricsPanelSchema,it as ProgressCard,at as ProgressCardSchema,lt as StatusBadge,ut as StatusBadgeSchema,ft as TextStream,mt as TextStreamSchema,Be as UrunAudio,Er as UrunAuthProvider,qt as UrunCamera,an as UrunControlSender,nn as UrunDocPanel,te as UrunErrorBoundary,ln as UrunEventSpine,Ar as UrunJwtProvider,Lr as UrunProvider,Rn as UrunSessionGate,Cn as UrunSessionStatus,Xe as UrunSessionWaking,rn as UrunStreamTail,_t as UrunVoice,le as authMode,$e as createDocStore,ma as describeSessionPhase,ae as formatPayload,he as getUrunAudioContext,fa as isWakingPhase,je as parseJsonObject,H as pushCapped,nt as registerComponent,ve as resumeUrunAudioContext,F as urunPublicEnv,$r as useApp,tt as useChat,Yr as useCompletion,se as useDocStore,pr as useImageFrame,mr as useMetricsPanel,sr as useProgressCard,Xr as useRequest,Yt as useSessionDoc,G as useSessionPhase,jt as useSessionTrack,ze as useSessionWake,ir as useStatusBadge,Je as useStreamMessages,lr as useTextStream,Vt as useUrunAudioLevel,xe as useUrunAuth,Dr as usesWorkOSAuth};
|
package/dist/next-workos.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
+
"use client"
|
|
1
2
|
"use strict";var i=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var k=Object.prototype.hasOwnProperty;var f=(r,e)=>{for(var o in e)i(r,o,{get:e[o],enumerable:!0})},v=(r,e,o,u)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of h(e))!k.call(r,t)&&t!==o&&i(r,t,{get:()=>e[t],enumerable:!(u=P(e,t))||u.enumerable});return r};var U=r=>v(i({},"__esModule",{value:!0}),r);var x={};f(x,{UrunWorkOSProvider:()=>T});module.exports=U(x);var d=require("react"),c=require("@workos-inc/authkit-nextjs/components");var n=require("react"),A=require("react/jsx-runtime"),a=(0,n.createContext)(null);function p({getAccessToken:r,children:e}){let o=(0,n.useMemo)(()=>({getAccessToken:r}),[r]);return(0,A.jsx)(a.Provider,{value:o,children:e})}var s=require("react/jsx-runtime");function l({children:r}){let e=(0,c.useAccessToken)(),o=(0,d.useCallback)(u=>u?.forceRefresh&&e.refresh?e.refresh():e.getAccessToken(),[e]);return(0,s.jsx)(p,{getAccessToken:o,children:r})}function T({children:r,...e}){return(0,s.jsx)(c.AuthKitProvider,{...e,children:(0,s.jsx)(l,{children:r})})}0&&(module.exports={UrunWorkOSProvider});
|
package/dist/next-workos.mjs
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
"use client"
|
|
2
|
+
import{a as t}from"./chunk-WF2OBDSX.mjs";import{useCallback as c}from"react";import{AuthKitProvider as i,useAccessToken as u}from"@workos-inc/authkit-nextjs/components";import{jsx as o}from"react/jsx-runtime";function p({children:r}){let e=u(),s=c(n=>n?.forceRefresh&&e.refresh?e.refresh():e.getAccessToken(),[e]);return o(t,{getAccessToken:s,children:r})}function A({children:r,...e}){return o(i,{...e,children:o(p,{children:r})})}export{A as UrunWorkOSProvider};
|
package/dist/styles.css
CHANGED
|
@@ -399,3 +399,16 @@
|
|
|
399
399
|
.urun-session-status-detail {
|
|
400
400
|
color: var(--urun-wb-muted, #8a8a8a);
|
|
401
401
|
}
|
|
402
|
+
|
|
403
|
+
/* Scale-to-zero "waking (Ns)" building block (UrunSessionWaking) */
|
|
404
|
+
.urun-session-waking {
|
|
405
|
+
display: inline-flex;
|
|
406
|
+
align-items: baseline;
|
|
407
|
+
gap: 6px;
|
|
408
|
+
font-size: 12px;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
.urun-session-waking-elapsed {
|
|
412
|
+
color: var(--urun-wb-muted, #8a8a8a);
|
|
413
|
+
font-variant-numeric: tabular-nums;
|
|
414
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
:root{--urun-bg: #ffffff;--urun-text: #1a1a2e;--urun-border: #e2e8f0;--urun-radius: 8px;--urun-font: system-ui, -apple-system, sans-serif;--urun-progress-bg: #e2e8f0;--urun-progress-fill: #3b82f6;--urun-progress-success: #22c55e;--urun-progress-error: #ef4444;--urun-progress-height: 8px;--urun-status-thinking: #f59e0b;--urun-status-generating: #3b82f6;--urun-status-idle: #94a3b8;--urun-status-error: #ef4444;--urun-status-indicator-size: 8px;--urun-cursor-color: #3b82f6;--urun-cursor-width: 2px;--urun-metric-bg: #f8fafc;--urun-metric-label-color: #64748b;--urun-metric-value-color: #1a1a2e}.urun-progress-card{font-family:var(--urun-font);color:var(--urun-text);border:1px solid var(--urun-border);border-radius:var(--urun-radius);padding:12px 16px;background:var(--urun-bg)}.urun-progress-label{font-size:.875rem;font-weight:500;margin-bottom:8px}.urun-progress-bar{height:var(--urun-progress-height);background:var(--urun-progress-bg);border-radius:calc(var(--urun-progress-height) / 2);overflow:hidden}.urun-progress-fill{height:100%;background:var(--urun-progress-fill);border-radius:inherit;transition:width .3s ease}.urun-progress-card[data-variant=success] .urun-progress-fill{background:var(--urun-progress-success)}.urun-progress-card[data-variant=error] .urun-progress-fill{background:var(--urun-progress-error)}.urun-progress-text{font-size:.75rem;color:var(--urun-metric-label-color);margin-top:4px;text-align:right}.urun-status-badge{display:inline-flex;align-items:center;gap:6px;font-family:var(--urun-font);font-size:.875rem;color:var(--urun-text)}.urun-status-indicator{display:inline-block;width:var(--urun-status-indicator-size);height:var(--urun-status-indicator-size);border-radius:50%;background:var(--urun-status-idle);flex-shrink:0}.urun-status-badge[data-state=thinking] .urun-status-indicator{background:var(--urun-status-thinking)}.urun-status-badge[data-state=generating] .urun-status-indicator{background:var(--urun-status-generating)}.urun-status-badge[data-state=error] .urun-status-indicator{background:var(--urun-status-error)}.urun-status-pulse{animation:urun-pulse 1.5s ease-in-out infinite}.urun-text-stream{font-family:var(--urun-font);color:var(--urun-text);white-space:pre-wrap;word-break:break-word}.urun-text-cursor{display:inline-block;width:var(--urun-cursor-width);height:1em;background:var(--urun-cursor-color);vertical-align:text-bottom;animation:urun-blink 1s step-end infinite}.urun-image-frame{margin:0;border:1px solid var(--urun-border);border-radius:var(--urun-radius);overflow:hidden;background:var(--urun-bg)}.urun-image{display:block;width:100%;height:auto}.urun-image-caption{padding:8px 12px;font-family:var(--urun-font);font-size:.875rem;color:var(--urun-metric-label-color);text-align:center}.urun-metrics-panel{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:12px;font-family:var(--urun-font)}.urun-metric-card{background:var(--urun-metric-bg);border:1px solid var(--urun-border);border-radius:var(--urun-radius);padding:12px;text-align:center}.urun-metric-label{font-size:.75rem;color:var(--urun-metric-label-color);margin-bottom:4px}.urun-metric-value{font-size:1.25rem;font-weight:600;color:var(--urun-metric-value-color)}.urun-component-error{font-family:var(--urun-font);padding:8px 12px;border:1px solid var(--urun-status-error);border-radius:var(--urun-radius);background:#fef2f2;color:var(--urun-status-error);font-size:.875rem}@keyframes urun-pulse{0%,to{opacity:1}50%{opacity:.4}}@keyframes urun-blink{0%,to{opacity:1}50%{opacity:0}}[data-urun-video],[data-urun-video] .video-js,[data-urun-video] .vjs-tech{width:100%;height:100%}[data-urun-video] .vjs-tech{object-fit:contain}.urun-video-live.vjs-has-started .vjs-poster,.urun-video-live.vjs-has-started .vjs-loading-spinner,.urun-video-live.vjs-has-started .vjs-big-play-button{display:none!important}.urun-video-live .vjs-poster{background-color:transparent}.urun-stream-tail,.urun-doc-panel,.urun-control-sender,.urun-event-spine{display:flex;flex-direction:column;gap:6px;font-size:12px}.urun-stream-tail-meta,.urun-doc-panel-meta{display:flex;align-items:center;gap:8px;color:var(--urun-wb-muted, #8a8a8a)}.urun-stream-tail-log,.urun-control-sender-log{display:flex;flex-direction:column;gap:2px;max-height:220px;overflow:auto;padding:6px;border-radius:6px;background:var(--urun-wb-log-bg, rgba(0, 0, 0, .25));font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px}.urun-stream-tail-time,.urun-control-sender-time,.urun-event-spine-time{color:var(--urun-wb-muted, #8a8a8a)}.urun-doc-panel-snapshot{margin:0;padding:8px;max-height:220px;overflow:auto;border-radius:6px;background:var(--urun-wb-log-bg, rgba(0, 0, 0, .25));font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px}.urun-doc-patch,.urun-control-sender{display:flex;flex-direction:column;gap:6px}.urun-doc-patch-input{width:100%;resize:vertical;border-radius:6px;border:1px solid var(--urun-wb-border, rgba(128, 128, 128, .4));background:var(--urun-wb-input-bg, transparent);color:inherit;padding:6px 8px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}.urun-doc-patch-actions{display:flex;align-items:center;gap:8px}.urun-doc-patch-button,.urun-mic-button{cursor:pointer;border-radius:6px;border:1px solid var(--urun-wb-border, rgba(128, 128, 128, .4));background:var(--urun-wb-accent, #24db49);color:var(--urun-wb-accent-fg, #04120a);padding:4px 12px;font-size:12px;font-weight:600}.urun-doc-patch-button:disabled{cursor:default;opacity:.5}.urun-doc-patch-error,.urun-mic-error{color:var(--urun-wb-danger, #e5484d)}.urun-event-spine{max-height:260px;overflow:auto}.urun-event-spine-line,.urun-control-sender-line{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px}.urun-event-spine-kind,.urun-control-sender-dir{display:inline-block;min-width:3.5em;color:var(--urun-wb-muted, #8a8a8a)}.urun-session-status{display:inline-flex;align-items:center;gap:6px;font-size:12px}.urun-session-status-dot{width:8px;height:8px;border-radius:50%;background:var(--urun-wb-muted, #8a8a8a)}.urun-session-status-dot[data-phase=live]{background:var(--urun-wb-accent, #24db49)}.urun-session-status-dot[data-phase=connecting],.urun-session-status-dot[data-phase=provisioning],.urun-session-status-dot[data-phase=queued]{background:var(--urun-wb-warn, #ffb224)}.urun-session-status-dot[data-phase=error]{background:var(--urun-wb-danger, #e5484d)}.urun-session-status-detail{color:var(--urun-wb-muted, #8a8a8a)}
|
|
1
|
+
:root{--urun-bg: #ffffff;--urun-text: #1a1a2e;--urun-border: #e2e8f0;--urun-radius: 8px;--urun-font: system-ui, -apple-system, sans-serif;--urun-progress-bg: #e2e8f0;--urun-progress-fill: #3b82f6;--urun-progress-success: #22c55e;--urun-progress-error: #ef4444;--urun-progress-height: 8px;--urun-status-thinking: #f59e0b;--urun-status-generating: #3b82f6;--urun-status-idle: #94a3b8;--urun-status-error: #ef4444;--urun-status-indicator-size: 8px;--urun-cursor-color: #3b82f6;--urun-cursor-width: 2px;--urun-metric-bg: #f8fafc;--urun-metric-label-color: #64748b;--urun-metric-value-color: #1a1a2e}.urun-progress-card{font-family:var(--urun-font);color:var(--urun-text);border:1px solid var(--urun-border);border-radius:var(--urun-radius);padding:12px 16px;background:var(--urun-bg)}.urun-progress-label{font-size:.875rem;font-weight:500;margin-bottom:8px}.urun-progress-bar{height:var(--urun-progress-height);background:var(--urun-progress-bg);border-radius:calc(var(--urun-progress-height) / 2);overflow:hidden}.urun-progress-fill{height:100%;background:var(--urun-progress-fill);border-radius:inherit;transition:width .3s ease}.urun-progress-card[data-variant=success] .urun-progress-fill{background:var(--urun-progress-success)}.urun-progress-card[data-variant=error] .urun-progress-fill{background:var(--urun-progress-error)}.urun-progress-text{font-size:.75rem;color:var(--urun-metric-label-color);margin-top:4px;text-align:right}.urun-status-badge{display:inline-flex;align-items:center;gap:6px;font-family:var(--urun-font);font-size:.875rem;color:var(--urun-text)}.urun-status-indicator{display:inline-block;width:var(--urun-status-indicator-size);height:var(--urun-status-indicator-size);border-radius:50%;background:var(--urun-status-idle);flex-shrink:0}.urun-status-badge[data-state=thinking] .urun-status-indicator{background:var(--urun-status-thinking)}.urun-status-badge[data-state=generating] .urun-status-indicator{background:var(--urun-status-generating)}.urun-status-badge[data-state=error] .urun-status-indicator{background:var(--urun-status-error)}.urun-status-pulse{animation:urun-pulse 1.5s ease-in-out infinite}.urun-text-stream{font-family:var(--urun-font);color:var(--urun-text);white-space:pre-wrap;word-break:break-word}.urun-text-cursor{display:inline-block;width:var(--urun-cursor-width);height:1em;background:var(--urun-cursor-color);vertical-align:text-bottom;animation:urun-blink 1s step-end infinite}.urun-image-frame{margin:0;border:1px solid var(--urun-border);border-radius:var(--urun-radius);overflow:hidden;background:var(--urun-bg)}.urun-image{display:block;width:100%;height:auto}.urun-image-caption{padding:8px 12px;font-family:var(--urun-font);font-size:.875rem;color:var(--urun-metric-label-color);text-align:center}.urun-metrics-panel{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:12px;font-family:var(--urun-font)}.urun-metric-card{background:var(--urun-metric-bg);border:1px solid var(--urun-border);border-radius:var(--urun-radius);padding:12px;text-align:center}.urun-metric-label{font-size:.75rem;color:var(--urun-metric-label-color);margin-bottom:4px}.urun-metric-value{font-size:1.25rem;font-weight:600;color:var(--urun-metric-value-color)}.urun-component-error{font-family:var(--urun-font);padding:8px 12px;border:1px solid var(--urun-status-error);border-radius:var(--urun-radius);background:#fef2f2;color:var(--urun-status-error);font-size:.875rem}@keyframes urun-pulse{0%,to{opacity:1}50%{opacity:.4}}@keyframes urun-blink{0%,to{opacity:1}50%{opacity:0}}[data-urun-video],[data-urun-video] .video-js,[data-urun-video] .vjs-tech{width:100%;height:100%}[data-urun-video] .vjs-tech{object-fit:contain}.urun-video-live.vjs-has-started .vjs-poster,.urun-video-live.vjs-has-started .vjs-loading-spinner,.urun-video-live.vjs-has-started .vjs-big-play-button{display:none!important}.urun-video-live .vjs-poster{background-color:transparent}.urun-stream-tail,.urun-doc-panel,.urun-control-sender,.urun-event-spine{display:flex;flex-direction:column;gap:6px;font-size:12px}.urun-stream-tail-meta,.urun-doc-panel-meta{display:flex;align-items:center;gap:8px;color:var(--urun-wb-muted, #8a8a8a)}.urun-stream-tail-log,.urun-control-sender-log{display:flex;flex-direction:column;gap:2px;max-height:220px;overflow:auto;padding:6px;border-radius:6px;background:var(--urun-wb-log-bg, rgba(0, 0, 0, .25));font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px}.urun-stream-tail-time,.urun-control-sender-time,.urun-event-spine-time{color:var(--urun-wb-muted, #8a8a8a)}.urun-doc-panel-snapshot{margin:0;padding:8px;max-height:220px;overflow:auto;border-radius:6px;background:var(--urun-wb-log-bg, rgba(0, 0, 0, .25));font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px}.urun-doc-patch,.urun-control-sender{display:flex;flex-direction:column;gap:6px}.urun-doc-patch-input{width:100%;resize:vertical;border-radius:6px;border:1px solid var(--urun-wb-border, rgba(128, 128, 128, .4));background:var(--urun-wb-input-bg, transparent);color:inherit;padding:6px 8px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}.urun-doc-patch-actions{display:flex;align-items:center;gap:8px}.urun-doc-patch-button,.urun-mic-button{cursor:pointer;border-radius:6px;border:1px solid var(--urun-wb-border, rgba(128, 128, 128, .4));background:var(--urun-wb-accent, #24db49);color:var(--urun-wb-accent-fg, #04120a);padding:4px 12px;font-size:12px;font-weight:600}.urun-doc-patch-button:disabled{cursor:default;opacity:.5}.urun-doc-patch-error,.urun-mic-error{color:var(--urun-wb-danger, #e5484d)}.urun-event-spine{max-height:260px;overflow:auto}.urun-event-spine-line,.urun-control-sender-line{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px}.urun-event-spine-kind,.urun-control-sender-dir{display:inline-block;min-width:3.5em;color:var(--urun-wb-muted, #8a8a8a)}.urun-session-status{display:inline-flex;align-items:center;gap:6px;font-size:12px}.urun-session-status-dot{width:8px;height:8px;border-radius:50%;background:var(--urun-wb-muted, #8a8a8a)}.urun-session-status-dot[data-phase=live]{background:var(--urun-wb-accent, #24db49)}.urun-session-status-dot[data-phase=connecting],.urun-session-status-dot[data-phase=provisioning],.urun-session-status-dot[data-phase=queued]{background:var(--urun-wb-warn, #ffb224)}.urun-session-status-dot[data-phase=error]{background:var(--urun-wb-danger, #e5484d)}.urun-session-status-detail{color:var(--urun-wb-muted, #8a8a8a)}.urun-session-waking{display:inline-flex;align-items:baseline;gap:6px;font-size:12px}.urun-session-waking-elapsed{color:var(--urun-wb-muted, #8a8a8a);font-variant-numeric:tabular-nums}
|
package/dist/video.d.mts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { ReactNode } from 'react';
|
|
3
|
+
import Player from 'video.js/dist/types/player';
|
|
4
|
+
|
|
5
|
+
interface UrunVideoProps {
|
|
6
|
+
|
|
7
|
+
track?: MediaStreamTrack | null;
|
|
8
|
+
|
|
9
|
+
stream?: MediaStream | null;
|
|
10
|
+
|
|
11
|
+
name?: string;
|
|
12
|
+
|
|
13
|
+
src?: string;
|
|
14
|
+
|
|
15
|
+
type?: string;
|
|
16
|
+
|
|
17
|
+
className?: string;
|
|
18
|
+
|
|
19
|
+
videoClassName?: string;
|
|
20
|
+
|
|
21
|
+
poster?: string;
|
|
22
|
+
|
|
23
|
+
controls?: boolean;
|
|
24
|
+
|
|
25
|
+
autoPlay?: boolean;
|
|
26
|
+
|
|
27
|
+
muted?: boolean;
|
|
28
|
+
|
|
29
|
+
onVideoElement?: (el: HTMLVideoElement | null) => void;
|
|
30
|
+
|
|
31
|
+
onPlayerReady?: (player: Player | null) => void;
|
|
32
|
+
|
|
33
|
+
children?: ReactNode;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
declare const UrunVideo: react.ForwardRefExoticComponent<UrunVideoProps & react.RefAttributes<HTMLVideoElement>>;
|
|
37
|
+
|
|
38
|
+
export { UrunVideo, type UrunVideoProps };
|
package/dist/video.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { ReactNode } from 'react';
|
|
3
|
+
import Player from 'video.js/dist/types/player';
|
|
4
|
+
|
|
5
|
+
interface UrunVideoProps {
|
|
6
|
+
|
|
7
|
+
track?: MediaStreamTrack | null;
|
|
8
|
+
|
|
9
|
+
stream?: MediaStream | null;
|
|
10
|
+
|
|
11
|
+
name?: string;
|
|
12
|
+
|
|
13
|
+
src?: string;
|
|
14
|
+
|
|
15
|
+
type?: string;
|
|
16
|
+
|
|
17
|
+
className?: string;
|
|
18
|
+
|
|
19
|
+
videoClassName?: string;
|
|
20
|
+
|
|
21
|
+
poster?: string;
|
|
22
|
+
|
|
23
|
+
controls?: boolean;
|
|
24
|
+
|
|
25
|
+
autoPlay?: boolean;
|
|
26
|
+
|
|
27
|
+
muted?: boolean;
|
|
28
|
+
|
|
29
|
+
onVideoElement?: (el: HTMLVideoElement | null) => void;
|
|
30
|
+
|
|
31
|
+
onPlayerReady?: (player: Player | null) => void;
|
|
32
|
+
|
|
33
|
+
children?: ReactNode;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
declare const UrunVideo: react.ForwardRefExoticComponent<UrunVideoProps & react.RefAttributes<HTMLVideoElement>>;
|
|
37
|
+
|
|
38
|
+
export { UrunVideo, type UrunVideoProps };
|
package/dist/video.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
"use strict";var q=Object.create;var E=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf,J=Object.prototype.hasOwnProperty;var K=(t,r)=>{for(var n in r)E(t,n,{get:r[n],enumerable:!0})},M=(t,r,n,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of G(r))!J.call(t,s)&&s!==n&&E(t,s,{get:()=>r[s],enumerable:!(i=W(r,s))||i.enumerable});return t};var Q=(t,r,n)=>(n=t!=null?q(Y(t)):{},M(r||!t||!t.__esModule?E(n,"default",{value:t,enumerable:!0}):n,t)),X=t=>M(E({},"__esModule",{value:!0}),t);var se={};K(se,{UrunVideo:()=>H});module.exports=X(se);var o=require("react"),O=Q(require("video.js")),me=require("video.js/dist/video-js.css");var b=require("react");var k=require("react"),Z=require("@urun-sh/core"),$=require("@urun-sh/core/internal");var ee=require("react/jsx-runtime"),N=(0,k.createContext)(null);function R(t){let r=(0,b.useContext)(N);if(!r)throw new Error("useTrack must be used within <SessionProvider> or <UrunProvider>");let[n,i]=(0,b.useState)(null);return(0,b.useEffect)(()=>{let s=r.getState()._transport;if(!s)return;let m=s.getTrackByName?.bind(s),v=m?.(t);v&&v.readyState!=="ended"&&i(v);let j=s.on("track",h=>{let w=m?.(t);w&&w.id!==h.id||(i(h),h.addEventListener("ended",()=>{i(null)}))});return()=>{j()}},[t,r]),n}var l=require("react/jsx-runtime");function I(t){t.posterImage?.hide?.()}var re=`
|
|
3
|
+
[data-urun-video]{width:100%;height:100%}
|
|
4
|
+
[data-urun-video] .video-js,[data-urun-video] .vjs-tech{width:100%;height:100%}
|
|
5
|
+
[data-urun-video] .vjs-tech{object-fit:contain}
|
|
6
|
+
.urun-video-live.vjs-has-started .vjs-poster,
|
|
7
|
+
.urun-video-live.vjs-has-started .vjs-loading-spinner,
|
|
8
|
+
.urun-video-live.vjs-has-started .vjs-big-play-button{display:none !important}
|
|
9
|
+
.urun-video-live .vjs-poster{background-color:transparent}
|
|
10
|
+
`,U="urun-video-critical-css";function te(){if(typeof document>"u"||document.getElementById(U))return;let t=document.createElement("style");t.id=U,t.textContent=re,document.head.appendChild(t)}var ne=["playToggle","volumePanel","fullscreenToggle"],oe=["playToggle","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","remainingTimeDisplay","fullscreenToggle"],A=(0,o.forwardRef)(function(r,n){let{track:i,stream:s,src:m,type:v="video/mp4",className:j,videoClassName:h,poster:w,controls:D=!0,autoPlay:S=!0,muted:T=!0,onVideoElement:L,onPlayerReady:z,children:_}=r,P=typeof m=="string"&&m.length>0,c=!P,y=(0,o.useRef)(null),f=(0,o.useRef)(null),[B,x]=(0,o.useState)(!1),F=(0,o.useCallback)(e=>{y.current=e,typeof n=="function"?n(e):n&&(n.current=e),L?.(e)},[n,L]);(0,o.useImperativeHandle)(n,()=>y.current,[]);let g=(0,o.useCallback)(()=>{let e=y.current;if(!e||!e.srcObject&&!e.src)return;T&&(e.muted=!0,e.defaultMuted=!0),e.setAttribute("playsinline",""),e.setAttribute("webkit-playsinline","");let a=e.play();a&&typeof a.then=="function"&&a.then(()=>x(!1)).catch(d=>{(d instanceof Error?d.name:String(d))!=="AbortError"&&x(!0)})},[T]);return(0,o.useEffect)(()=>{if(typeof document>"u")return;let e=y.current;if(!e)return;te(),T&&(e.muted=!0,e.defaultMuted=!0,e.setAttribute("muted","")),e.autoplay=S,e.setAttribute("playsinline",""),e.setAttribute("webkit-playsinline","");let a=(0,O.default)(e,{controls:D,autoplay:S,muted:T,playsinline:!0,preload:"auto",fluid:!1,bigPlayButton:!0,poster:w,userActions:{click:!0,doubleClick:!1,hotkeys:!1},controlBar:{children:c?ne:oe}});c&&a.addClass("urun-video-live");let d=()=>x(!1),p=()=>{a.hasStarted(!0),I(a),d()},u=()=>{c&&g()};return e.addEventListener("playing",p),e.addEventListener("loadedmetadata",u),c&&e.addEventListener("pause",u),f.current=a,z?.(a),()=>{e.removeEventListener("playing",p),e.removeEventListener("loadedmetadata",u),e.removeEventListener("pause",u),z?.(null),f.current&&(f.current.dispose(),f.current=null)}},[c]),(0,o.useEffect)(()=>{if(!P)return;let e=f.current;if(!e)return;let a=e.tech?.(!0)?.el?.();a&&(a.srcObject=null),e.src({src:m,type:v}),S&&g()},[P,m,v,S,g]),(0,o.useEffect)(()=>{if(!c)return;let e=f.current;if(!e)return;let a=i??null,d=s??null;!d&&a&&(d=new MediaStream([a]));let p=e.tech?.(!0)?.el?.()??y.current;if(!p)return;if(!d){p.srcObject=null,x(!1);return}p.srcObject=d,g();let u=d.getVideoTracks()[0]??a??null,C=()=>{e.hasStarted(!0),I(e),g()},V=()=>{p.srcObject=null,x(!1)};return u&&(u.addEventListener("unmute",C),u.addEventListener("ended",V),u.muted||C()),()=>{u&&(u.removeEventListener("unmute",C),u.removeEventListener("ended",V))}},[c,i,s,g]),(0,l.jsxs)("div",{className:j,style:{position:"relative",width:"100%",height:"100%"},"data-urun-video":"","data-urun-video-mode":c?"live":"vod",children:[(0,l.jsx)("video",{ref:F,className:["video-js","vjs-default-skin",h].filter(Boolean).join(" "),playsInline:!0}),B&&(0,l.jsx)("button",{type:"button",onClick:g,"aria-label":"Tap to play",style:{position:"absolute",inset:0,zIndex:30,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.6)",border:0,cursor:"pointer",color:"#fff"},children:(0,l.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8,borderRadius:999,border:"1px solid rgba(255,255,255,0.2)",background:"rgba(255,255,255,0.1)",padding:"10px 20px",fontSize:14,fontWeight:500},children:[(0,l.jsx)("svg",{viewBox:"0 0 24 24",fill:"currentColor",width:16,height:16,"aria-hidden":!0,children:(0,l.jsx)("path",{d:"M8 5v14l11-7z"})}),"Tap to play"]})}),_]})}),ae=(0,o.forwardRef)(function({name:r,...n},i){let s=R(r);return(0,l.jsx)(A,{ref:i,...n,track:s})}),H=(0,o.forwardRef)(function(r,n){return!!r.name&&!r.track&&!r.stream&&!(typeof r.src=="string"&&r.src)?(0,l.jsx)(ae,{ref:n,...r,name:r.name}):(0,l.jsx)(A,{ref:n,...r})});0&&(module.exports={UrunVideo});
|
package/dist/video.mjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
import{forwardRef as j,useCallback as M,useEffect as E,useImperativeHandle as G,useRef as N,useState as Y}from"react";import J from"video.js";import"video.js/dist/video-js.css";import{useContext as F,useState as q,useEffect as W}from"react";import{createContext as B,useState as oe,useEffect as ae,useRef as se}from"react";import{observePageLifecycle as ue}from"@urun-sh/core";import{TransportSession as le}from"@urun-sh/core/internal";import{jsx as pe}from"react/jsx-runtime";var z=B(null);function V(o){let r=F(z);if(!r)throw new Error("useTrack must be used within <SessionProvider> or <UrunProvider>");let[n,i]=q(null);return W(()=>{let u=r.getState()._transport;if(!u)return;let c=u.getTrackByName?.bind(u),g=c?.(o);g&&g.readyState!=="ended"&&i(g);let w=u.on("track",f=>{let y=c?.(o);y&&y.id!==f.id||(i(f),f.addEventListener("ended",()=>{i(null)}))});return()=>{w()}},[o,r]),n}import{jsx as m,jsxs as U}from"react/jsx-runtime";function R(o){o.posterImage?.hide?.()}var K=`
|
|
3
|
+
[data-urun-video]{width:100%;height:100%}
|
|
4
|
+
[data-urun-video] .video-js,[data-urun-video] .vjs-tech{width:100%;height:100%}
|
|
5
|
+
[data-urun-video] .vjs-tech{object-fit:contain}
|
|
6
|
+
.urun-video-live.vjs-has-started .vjs-poster,
|
|
7
|
+
.urun-video-live.vjs-has-started .vjs-loading-spinner,
|
|
8
|
+
.urun-video-live.vjs-has-started .vjs-big-play-button{display:none !important}
|
|
9
|
+
.urun-video-live .vjs-poster{background-color:transparent}
|
|
10
|
+
`,I="urun-video-critical-css";function Q(){if(typeof document>"u"||document.getElementById(I))return;let o=document.createElement("style");o.id=I,o.textContent=K,document.head.appendChild(o)}var X=["playToggle","volumePanel","fullscreenToggle"],Z=["playToggle","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","remainingTimeDisplay","fullscreenToggle"],O=j(function(r,n){let{track:i,stream:u,src:c,type:g="video/mp4",className:w,videoClassName:f,poster:y,controls:A=!0,autoPlay:x=!0,muted:k=!0,onVideoElement:P,onPlayerReady:C,children:H}=r,S=typeof c=="string"&&c.length>0,d=!S,b=N(null),v=N(null),[D,h]=Y(!1),_=M(e=>{b.current=e,typeof n=="function"?n(e):n&&(n.current=e),P?.(e)},[n,P]);G(n,()=>b.current,[]);let p=M(()=>{let e=b.current;if(!e||!e.srcObject&&!e.src)return;k&&(e.muted=!0,e.defaultMuted=!0),e.setAttribute("playsinline",""),e.setAttribute("webkit-playsinline","");let t=e.play();t&&typeof t.then=="function"&&t.then(()=>h(!1)).catch(s=>{(s instanceof Error?s.name:String(s))!=="AbortError"&&h(!0)})},[k]);return E(()=>{if(typeof document>"u")return;let e=b.current;if(!e)return;Q(),k&&(e.muted=!0,e.defaultMuted=!0,e.setAttribute("muted","")),e.autoplay=x,e.setAttribute("playsinline",""),e.setAttribute("webkit-playsinline","");let t=J(e,{controls:A,autoplay:x,muted:k,playsinline:!0,preload:"auto",fluid:!1,bigPlayButton:!0,poster:y,userActions:{click:!0,doubleClick:!1,hotkeys:!1},controlBar:{children:d?X:Z}});d&&t.addClass("urun-video-live");let s=()=>h(!1),l=()=>{t.hasStarted(!0),R(t),s()},a=()=>{d&&p()};return e.addEventListener("playing",l),e.addEventListener("loadedmetadata",a),d&&e.addEventListener("pause",a),v.current=t,C?.(t),()=>{e.removeEventListener("playing",l),e.removeEventListener("loadedmetadata",a),e.removeEventListener("pause",a),C?.(null),v.current&&(v.current.dispose(),v.current=null)}},[d]),E(()=>{if(!S)return;let e=v.current;if(!e)return;let t=e.tech?.(!0)?.el?.();t&&(t.srcObject=null),e.src({src:c,type:g}),x&&p()},[S,c,g,x,p]),E(()=>{if(!d)return;let e=v.current;if(!e)return;let t=i??null,s=u??null;!s&&t&&(s=new MediaStream([t]));let l=e.tech?.(!0)?.el?.()??b.current;if(!l)return;if(!s){l.srcObject=null,h(!1);return}l.srcObject=s,p();let a=s.getVideoTracks()[0]??t??null,T=()=>{e.hasStarted(!0),R(e),p()},L=()=>{l.srcObject=null,h(!1)};return a&&(a.addEventListener("unmute",T),a.addEventListener("ended",L),a.muted||T()),()=>{a&&(a.removeEventListener("unmute",T),a.removeEventListener("ended",L))}},[d,i,u,p]),U("div",{className:w,style:{position:"relative",width:"100%",height:"100%"},"data-urun-video":"","data-urun-video-mode":d?"live":"vod",children:[m("video",{ref:_,className:["video-js","vjs-default-skin",f].filter(Boolean).join(" "),playsInline:!0}),D&&m("button",{type:"button",onClick:p,"aria-label":"Tap to play",style:{position:"absolute",inset:0,zIndex:30,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.6)",border:0,cursor:"pointer",color:"#fff"},children:U("span",{style:{display:"inline-flex",alignItems:"center",gap:8,borderRadius:999,border:"1px solid rgba(255,255,255,0.2)",background:"rgba(255,255,255,0.1)",padding:"10px 20px",fontSize:14,fontWeight:500},children:[m("svg",{viewBox:"0 0 24 24",fill:"currentColor",width:16,height:16,"aria-hidden":!0,children:m("path",{d:"M8 5v14l11-7z"})}),"Tap to play"]})}),H]})}),$=j(function({name:r,...n},i){let u=V(r);return m(O,{ref:i,...n,track:u})}),ee=j(function(r,n){return!!r.name&&!r.track&&!r.stream&&!(typeof r.src=="string"&&r.src)?m($,{ref:n,...r,name:r.name}):m(O,{ref:n,...r})});export{ee as UrunVideo};
|
package/dist/workos.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
+
"use client"
|
|
1
2
|
"use strict";var c=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var k=Object.prototype.hasOwnProperty;var v=(r,e)=>{for(var o in e)c(r,o,{get:e[o],enumerable:!0})},U=(r,e,o,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of h(e))!k.call(r,t)&&t!==o&&c(r,t,{get:()=>e[t],enumerable:!(i=P(e,t))||i.enumerable});return r};var a=r=>U(c({},"__esModule",{value:!0}),r);var T={};v(T,{UrunWorkOSProvider:()=>x});module.exports=a(T);var d=require("react"),s=require("@workos-inc/authkit-react");var n=require("react"),A=require("react/jsx-runtime"),l=(0,n.createContext)(null);function p({getAccessToken:r,children:e}){let o=(0,n.useMemo)(()=>({getAccessToken:r}),[r]);return(0,A.jsx)(l.Provider,{value:o,children:e})}var u=require("react/jsx-runtime");function f({children:r}){let e=(0,s.useAuth)(),o=(0,d.useCallback)(()=>e.getAccessToken(),[e]);return(0,u.jsx)(p,{getAccessToken:o,children:r})}function x({children:r,...e}){return(0,u.jsx)(s.AuthKitProvider,{...e,children:(0,u.jsx)(f,{children:r})})}0&&(module.exports={UrunWorkOSProvider});
|
package/dist/workos.mjs
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
"use client"
|
|
2
|
+
import{a as t}from"./chunk-WF2OBDSX.mjs";import{useCallback as n}from"react";import{AuthKitProvider as c,useAuth as s}from"@workos-inc/authkit-react";import{jsx as e}from"react/jsx-runtime";function u({children:r}){let o=s(),i=n(()=>o.getAccessToken(),[o]);return e(t,{getAccessToken:i,children:r})}function A({children:r,...o}){return e(c,{...o,children:e(u,{children:r})})}export{A as UrunWorkOSProvider};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urun-sh/react",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.8",
|
|
4
4
|
"description": "React bindings for the urun TypeScript SDK",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -35,6 +35,11 @@
|
|
|
35
35
|
"import": "./dist/next-workos.mjs",
|
|
36
36
|
"require": "./dist/next-workos.js"
|
|
37
37
|
},
|
|
38
|
+
"./video": {
|
|
39
|
+
"types": "./dist/video.d.ts",
|
|
40
|
+
"import": "./dist/video.mjs",
|
|
41
|
+
"require": "./dist/video.js"
|
|
42
|
+
},
|
|
38
43
|
"./styles.css": "./dist/styles.css",
|
|
39
44
|
"./package.json": "./package.json"
|
|
40
45
|
},
|
|
@@ -48,7 +53,7 @@
|
|
|
48
53
|
"dev": "tsup --watch"
|
|
49
54
|
},
|
|
50
55
|
"peerDependencies": {
|
|
51
|
-
"@urun-sh/core": "^0.2.
|
|
56
|
+
"@urun-sh/core": "^0.2.8",
|
|
52
57
|
"@workos-inc/authkit-nextjs": "^3.0.0",
|
|
53
58
|
"@workos-inc/authkit-react": "^0.15.0 || ^0.16.0",
|
|
54
59
|
"next": "^15.0.0 || ^16.0.0",
|
|
@@ -56,7 +61,7 @@
|
|
|
56
61
|
"video.js": "^8.0.0"
|
|
57
62
|
},
|
|
58
63
|
"dependencies": {
|
|
59
|
-
"yjs": "^13.6.
|
|
64
|
+
"yjs": "^13.6.31",
|
|
60
65
|
"zod": "^3.24.0",
|
|
61
66
|
"zustand": "^5.0.0"
|
|
62
67
|
},
|
package/dist/chunk-SSZO4I6Y.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function n(e){return e&&e.trim()?e.trim():void 0}function r(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return n(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return n(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return n(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return n(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return n(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return n(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return n(typeof process<"u"?process.env?.[e]:void 0)}}function s(){let e=r("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||r("VERCEL_ENV")==="production"?"workos":r("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function t(){return s()==="workos"}export{r as a,s as b,t as c};
|