@tanstack/ai-react 0.15.15 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.d.ts +5 -1
- package/dist/esm/index.js +6 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/mcp-apps.d.ts +20 -0
- package/dist/esm/mcp-apps.js +52 -0
- package/dist/esm/mcp-apps.js.map +1 -0
- package/dist/esm/use-audio-recorder.d.ts +43 -0
- package/dist/esm/use-audio-recorder.js +49 -0
- package/dist/esm/use-audio-recorder.js.map +1 -0
- package/dist/esm/use-generate-audio.d.ts +4 -4
- package/dist/esm/use-generate-audio.js.map +1 -1
- package/dist/esm/use-generate-image.d.ts +4 -4
- package/dist/esm/use-generate-image.js.map +1 -1
- package/dist/esm/use-generate-speech.d.ts +4 -4
- package/dist/esm/use-generate-speech.js.map +1 -1
- package/dist/esm/use-generate-video.d.ts +4 -4
- package/dist/esm/use-generate-video.js +4 -1
- package/dist/esm/use-generate-video.js.map +1 -1
- package/dist/esm/use-generation.d.ts +4 -4
- package/dist/esm/use-generation.js +4 -1
- package/dist/esm/use-generation.js.map +1 -1
- package/dist/esm/use-mcp-app-bridge.d.ts +25 -0
- package/dist/esm/use-mcp-app-bridge.js +26 -0
- package/dist/esm/use-mcp-app-bridge.js.map +1 -0
- package/dist/esm/use-summarize.d.ts +4 -4
- package/dist/esm/use-summarize.js.map +1 -1
- package/dist/esm/use-transcription.d.ts +4 -4
- package/dist/esm/use-transcription.js +1 -4
- package/dist/esm/use-transcription.js.map +1 -1
- package/package.json +15 -4
- package/src/index.ts +11 -0
- package/src/mcp-apps.tsx +88 -0
- package/src/use-audio-recorder.ts +112 -0
- package/src/use-generate-audio.ts +5 -8
- package/src/use-generate-image.ts +5 -8
- package/src/use-generate-speech.ts +7 -7
- package/src/use-generate-video.ts +18 -9
- package/src/use-generation.ts +17 -6
- package/src/use-mcp-app-bridge.ts +60 -0
- package/src/use-summarize.ts +7 -8
- package/src/use-transcription.ts +9 -11
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export { useChat } from './use-chat.js';
|
|
2
2
|
export { useRealtimeChat } from './use-realtime-chat.js';
|
|
3
|
+
export { useMcpAppBridge } from './use-mcp-app-bridge.js';
|
|
4
|
+
export type { UseMcpAppBridgeOptions } from './use-mcp-app-bridge.js';
|
|
3
5
|
export type { DeepPartial, UseChatOptions, UseChatReturn, UIMessage, ChatRequestBody, } from './types.js';
|
|
4
6
|
export type { UseRealtimeChatOptions, UseRealtimeChatReturn, } from './realtime-types.js';
|
|
5
7
|
export { useGeneration } from './use-generation.js';
|
|
@@ -16,4 +18,6 @@ export { useSummarize } from './use-summarize.js';
|
|
|
16
18
|
export type { UseSummarizeOptions, UseSummarizeReturn } from './use-summarize.js';
|
|
17
19
|
export { useGenerateVideo } from './use-generate-video.js';
|
|
18
20
|
export type { UseGenerateVideoOptions, UseGenerateVideoReturn, } from './use-generate-video.js';
|
|
19
|
-
export {
|
|
21
|
+
export { useAudioRecorder } from './use-audio-recorder.js';
|
|
22
|
+
export type { UseAudioRecorderOptions, UseAudioRecorderReturn, } from './use-audio-recorder.js';
|
|
23
|
+
export { fetchServerSentEvents, fetchHttpStream, xhrServerSentEvents, xhrHttpStream, stream, rpcStream, createChatClientOptions, createMcpAppBridge, type McpAppBridge, type CreateMcpAppBridgeOptions, type ChatFetcher, type ChatFetcherInput, type ChatFetcherOptions, type ConnectionAdapter, type ConnectConnectionAdapter, type SubscribeConnectionAdapter, type RunAgentInputContext, type FetchConnectionOptions, type XhrConnectionOptions, type InferChatMessages, type GenerationClientState, type ImageGenerateInput, type AudioGenerateInput, type SpeechGenerateInput, type TranscriptionGenerateInput, type SummarizeGenerateInput, type VideoGenerateInput, type VideoGenerateResult, type VideoStatusInfo, } from '@tanstack/ai-client';
|
package/dist/esm/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { useChat } from "./use-chat.js";
|
|
2
2
|
import { useRealtimeChat } from "./use-realtime-chat.js";
|
|
3
|
+
import { useMcpAppBridge } from "./use-mcp-app-bridge.js";
|
|
3
4
|
import { useGeneration } from "./use-generation.js";
|
|
4
5
|
import { useGenerateImage } from "./use-generate-image.js";
|
|
5
6
|
import { useGenerateAudio } from "./use-generate-audio.js";
|
|
@@ -7,19 +8,23 @@ import { useGenerateSpeech } from "./use-generate-speech.js";
|
|
|
7
8
|
import { useTranscription } from "./use-transcription.js";
|
|
8
9
|
import { useSummarize } from "./use-summarize.js";
|
|
9
10
|
import { useGenerateVideo } from "./use-generate-video.js";
|
|
10
|
-
import {
|
|
11
|
+
import { useAudioRecorder } from "./use-audio-recorder.js";
|
|
12
|
+
import { createChatClientOptions, createMcpAppBridge, fetchHttpStream, fetchServerSentEvents, rpcStream, stream, xhrHttpStream, xhrServerSentEvents } from "@tanstack/ai-client";
|
|
11
13
|
export {
|
|
12
14
|
createChatClientOptions,
|
|
15
|
+
createMcpAppBridge,
|
|
13
16
|
fetchHttpStream,
|
|
14
17
|
fetchServerSentEvents,
|
|
15
18
|
rpcStream,
|
|
16
19
|
stream,
|
|
20
|
+
useAudioRecorder,
|
|
17
21
|
useChat,
|
|
18
22
|
useGenerateAudio,
|
|
19
23
|
useGenerateImage,
|
|
20
24
|
useGenerateSpeech,
|
|
21
25
|
useGenerateVideo,
|
|
22
26
|
useGeneration,
|
|
27
|
+
useMcpAppBridge,
|
|
23
28
|
useRealtimeChat,
|
|
24
29
|
useSummarize,
|
|
25
30
|
useTranscription,
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { UIResourcePart } from '@tanstack/ai';
|
|
2
|
+
import { McpAppBridge } from '@tanstack/ai-client';
|
|
3
|
+
import { JSX } from 'react';
|
|
4
|
+
export interface MCPAppResourceProps {
|
|
5
|
+
/** The ui-resource part from a UIMessage assistant part. */
|
|
6
|
+
part: UIResourcePart;
|
|
7
|
+
/**
|
|
8
|
+
* Framework-agnostic bridge for tool calls, prompt sending, and link opening.
|
|
9
|
+
* Omit it to render the widget in display-only mode — iframe interactions
|
|
10
|
+
* that would trigger tool calls or prompts are ignored.
|
|
11
|
+
*/
|
|
12
|
+
bridge?: McpAppBridge;
|
|
13
|
+
/** Sandbox iframe configuration — must include the proxy page URL. */
|
|
14
|
+
sandbox: {
|
|
15
|
+
url: URL;
|
|
16
|
+
};
|
|
17
|
+
/** Optional structured arguments forwarded to the guest UI once it's ready. */
|
|
18
|
+
toolInput?: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
export declare function MCPAppResource(props: MCPAppResourceProps): JSX.Element;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { jsx } from "react/jsx-runtime";
|
|
2
|
+
import { AppRenderer } from "@mcp-ui/client";
|
|
3
|
+
function isRecord(value) {
|
|
4
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5
|
+
}
|
|
6
|
+
function resultToText(result) {
|
|
7
|
+
if (typeof result === "string") return result;
|
|
8
|
+
const stringify = JSON.stringify;
|
|
9
|
+
return stringify(result) ?? "null";
|
|
10
|
+
}
|
|
11
|
+
function MCPAppResource(props) {
|
|
12
|
+
const { bridge } = props;
|
|
13
|
+
return /* @__PURE__ */ jsx(
|
|
14
|
+
AppRenderer,
|
|
15
|
+
{
|
|
16
|
+
toolName: props.part.toolName,
|
|
17
|
+
sandbox: props.sandbox,
|
|
18
|
+
html: props.part.resource.text,
|
|
19
|
+
toolResourceUri: props.part.resource.uri,
|
|
20
|
+
toolInput: props.toolInput,
|
|
21
|
+
onCallTool: bridge ? async ({ name, arguments: args }) => {
|
|
22
|
+
const result = await bridge.callTool({
|
|
23
|
+
serverId: props.part.serverId,
|
|
24
|
+
toolName: name,
|
|
25
|
+
args
|
|
26
|
+
});
|
|
27
|
+
const structuredContent = isRecord(result) ? result : void 0;
|
|
28
|
+
return {
|
|
29
|
+
content: [
|
|
30
|
+
{
|
|
31
|
+
type: "text",
|
|
32
|
+
text: resultToText(result)
|
|
33
|
+
}
|
|
34
|
+
],
|
|
35
|
+
structuredContent
|
|
36
|
+
};
|
|
37
|
+
} : void 0,
|
|
38
|
+
onMessage: bridge ? async ({ content }) => {
|
|
39
|
+
const text = content.filter(
|
|
40
|
+
(c) => c.type === "text"
|
|
41
|
+
).map((c) => c.text).join("");
|
|
42
|
+
if (text) await bridge.sendPrompt(text);
|
|
43
|
+
return {};
|
|
44
|
+
} : void 0,
|
|
45
|
+
onOpenLink: bridge ? ({ url }) => Promise.resolve(bridge.openLink(url)) : void 0
|
|
46
|
+
}
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
export {
|
|
50
|
+
MCPAppResource
|
|
51
|
+
};
|
|
52
|
+
//# sourceMappingURL=mcp-apps.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-apps.js","sources":["../../src/mcp-apps.tsx"],"sourcesContent":["import { AppRenderer } from '@mcp-ui/client'\nimport type { UIResourcePart } from '@tanstack/ai'\nimport type { McpAppBridge } from '@tanstack/ai-client'\nimport type { JSX } from 'react'\n\nexport interface MCPAppResourceProps {\n /** The ui-resource part from a UIMessage assistant part. */\n part: UIResourcePart\n /**\n * Framework-agnostic bridge for tool calls, prompt sending, and link opening.\n * Omit it to render the widget in display-only mode — iframe interactions\n * that would trigger tool calls or prompts are ignored.\n */\n bridge?: McpAppBridge\n /** Sandbox iframe configuration — must include the proxy page URL. */\n sandbox: { url: URL }\n /** Optional structured arguments forwarded to the guest UI once it's ready. */\n toolInput?: Record<string, unknown>\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Coalesce an arbitrary bridge result into the `string` required by the\n * `CallToolResult` text content block. `JSON.stringify` is typed to return\n * `string` but actually returns `undefined` for inputs like `undefined` or a\n * function, so we narrow explicitly to avoid `text: undefined`.\n */\nfunction resultToText(result: unknown): string {\n if (typeof result === 'string') return result\n // `JSON.stringify`'s lib signature claims `string`, but it returns\n // `undefined` for `undefined`/function inputs; type the call honestly.\n const stringify: (value: unknown) => string | undefined = JSON.stringify\n return stringify(result) ?? 'null'\n}\n\nexport function MCPAppResource(props: MCPAppResourceProps): JSX.Element {\n const { bridge } = props\n return (\n <AppRenderer\n toolName={props.part.toolName}\n sandbox={props.sandbox}\n html={props.part.resource.text}\n toolResourceUri={props.part.resource.uri}\n toolInput={props.toolInput}\n onCallTool={\n bridge\n ? async ({ name, arguments: args }) => {\n const result = await bridge.callTool({\n serverId: props.part.serverId,\n toolName: name,\n args,\n })\n const structuredContent = isRecord(result) ? result : undefined\n return {\n content: [\n {\n type: 'text' as const,\n text: resultToText(result),\n },\n ],\n structuredContent,\n }\n }\n : undefined\n }\n onMessage={\n bridge\n ? async ({ content }) => {\n const text = content\n .filter(\n (c): c is { type: 'text'; text: string } => c.type === 'text',\n )\n .map((c) => c.text)\n .join('')\n if (text) await bridge.sendPrompt(text)\n return {}\n }\n : undefined\n }\n onOpenLink={\n bridge ? ({ url }) => Promise.resolve(bridge.openLink(url)) : undefined\n }\n />\n )\n}\n"],"names":[],"mappings":";;AAoBA,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAQA,SAAS,aAAa,QAAyB;AAC7C,MAAI,OAAO,WAAW,SAAU,QAAO;AAGvC,QAAM,YAAoD,KAAK;AAC/D,SAAO,UAAU,MAAM,KAAK;AAC9B;AAEO,SAAS,eAAe,OAAyC;AACtE,QAAM,EAAE,WAAW;AACnB,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,UAAU,MAAM,KAAK;AAAA,MACrB,SAAS,MAAM;AAAA,MACf,MAAM,MAAM,KAAK,SAAS;AAAA,MAC1B,iBAAiB,MAAM,KAAK,SAAS;AAAA,MACrC,WAAW,MAAM;AAAA,MACjB,YACE,SACI,OAAO,EAAE,MAAM,WAAW,WAAW;AACnC,cAAM,SAAS,MAAM,OAAO,SAAS;AAAA,UACnC,UAAU,MAAM,KAAK;AAAA,UACrB,UAAU;AAAA,UACV;AAAA,QAAA,CACD;AACD,cAAM,oBAAoB,SAAS,MAAM,IAAI,SAAS;AACtD,eAAO;AAAA,UACL,SAAS;AAAA,YACP;AAAA,cACE,MAAM;AAAA,cACN,MAAM,aAAa,MAAM;AAAA,YAAA;AAAA,UAC3B;AAAA,UAEF;AAAA,QAAA;AAAA,MAEJ,IACA;AAAA,MAEN,WACE,SACI,OAAO,EAAE,cAAc;AACrB,cAAM,OAAO,QACV;AAAA,UACC,CAAC,MAA2C,EAAE,SAAS;AAAA,QAAA,EAExD,IAAI,CAAC,MAAM,EAAE,IAAI,EACjB,KAAK,EAAE;AACV,YAAI,KAAM,OAAM,OAAO,WAAW,IAAI;AACtC,eAAO,CAAA;AAAA,MACT,IACA;AAAA,MAEN,YACE,SAAS,CAAC,EAAE,UAAU,QAAQ,QAAQ,OAAO,SAAS,GAAG,CAAC,IAAI;AAAA,IAAA;AAAA,EAAA;AAItE;"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { AudioRecorderOptions, AudioRecording, InferAudioRecordingOutput } from '@tanstack/ai-client';
|
|
2
|
+
export type UseAudioRecorderOptions<TOnComplete> = AudioRecorderOptions & {
|
|
3
|
+
/**
|
|
4
|
+
* Optional transform applied to the recording when `stop()` resolves. Its
|
|
5
|
+
* (awaited) return value becomes `recording` and the resolved value of
|
|
6
|
+
* `stop()`. Return nothing to keep the raw `AudioRecording`.
|
|
7
|
+
*/
|
|
8
|
+
onComplete?: TOnComplete;
|
|
9
|
+
};
|
|
10
|
+
export interface UseAudioRecorderReturn<TOutput> {
|
|
11
|
+
/** Latest recording (transformed if `onComplete` provided), or null. */
|
|
12
|
+
recording: TOutput | null;
|
|
13
|
+
/** True while actively capturing audio. */
|
|
14
|
+
isRecording: boolean;
|
|
15
|
+
/** Whether the browser supports recording (getUserMedia + MediaRecorder). */
|
|
16
|
+
isSupported: boolean;
|
|
17
|
+
/** Acquire the mic and begin recording. */
|
|
18
|
+
start: () => Promise<void>;
|
|
19
|
+
/** Stop and resolve with the completed recording (transformed if `onComplete` provided). */
|
|
20
|
+
stop: () => Promise<TOutput>;
|
|
21
|
+
/** Discard the in-progress recording and release the mic. */
|
|
22
|
+
cancel: () => void;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* React hook for recording an audio message. The resolved
|
|
26
|
+
* {@link AudioRecording} carries `.part` (an audio content part for
|
|
27
|
+
* `useChat.sendMessage`) and `.base64` (for the generation hooks).
|
|
28
|
+
*
|
|
29
|
+
* Errors are delivered via `onError`. `start()` and `stop()` also reject on
|
|
30
|
+
* failure (and `stop()` rejects with `Recording cancelled` if the component
|
|
31
|
+
* unmounts while a stop is in flight) — handle one channel, not both.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```tsx
|
|
35
|
+
* const { isRecording, start, stop, recording } = useAudioRecorder()
|
|
36
|
+
* const { sendMessage } = useChat({ connection })
|
|
37
|
+
* // ...
|
|
38
|
+
* const rec = await stop()
|
|
39
|
+
* sendMessage({ content: [rec.part] })
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export declare function useAudioRecorder<TOnComplete extends (recording: AudioRecording) => unknown>(options: UseAudioRecorderOptions<TOnComplete>): UseAudioRecorderReturn<InferAudioRecordingOutput<TOnComplete>>;
|
|
43
|
+
export declare function useAudioRecorder(options?: UseAudioRecorderOptions<undefined>): UseAudioRecorderReturn<AudioRecording>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { useState, useRef, useMemo, useEffect, useCallback } from "react";
|
|
2
|
+
import { AudioRecorder } from "@tanstack/ai-client";
|
|
3
|
+
function useAudioRecorder(options = {}) {
|
|
4
|
+
const [isRecording, setIsRecording] = useState(false);
|
|
5
|
+
const [recording, setRecording] = useState(null);
|
|
6
|
+
const optionsRef = useRef(options);
|
|
7
|
+
optionsRef.current = options;
|
|
8
|
+
const recorder = useMemo(
|
|
9
|
+
() => new AudioRecorder({
|
|
10
|
+
...options.audio !== void 0 && { audio: options.audio },
|
|
11
|
+
...options.mimeType !== void 0 && { mimeType: options.mimeType },
|
|
12
|
+
onError: (err) => optionsRef.current.onError?.(err)
|
|
13
|
+
}),
|
|
14
|
+
// Recorder config (audio/mimeType) is captured once at mount, matching the
|
|
15
|
+
// other hooks' create-once pattern.
|
|
16
|
+
[]
|
|
17
|
+
);
|
|
18
|
+
useEffect(() => {
|
|
19
|
+
const unsubscribe = recorder.subscribe((state) => {
|
|
20
|
+
setIsRecording(state === "recording");
|
|
21
|
+
});
|
|
22
|
+
return () => {
|
|
23
|
+
unsubscribe();
|
|
24
|
+
recorder.cancel();
|
|
25
|
+
};
|
|
26
|
+
}, [recorder]);
|
|
27
|
+
const start = useCallback(() => recorder.start(), [recorder]);
|
|
28
|
+
const stop = useCallback(async () => {
|
|
29
|
+
const recording2 = await recorder.stop();
|
|
30
|
+
const transformed = await optionsRef.current.onComplete?.(recording2);
|
|
31
|
+
const output = transformed === void 0 ? recording2 : transformed;
|
|
32
|
+
setRecording(() => output);
|
|
33
|
+
return output;
|
|
34
|
+
}, [recorder]);
|
|
35
|
+
const cancel = useCallback(() => recorder.cancel(), [recorder]);
|
|
36
|
+
return {
|
|
37
|
+
recording,
|
|
38
|
+
isRecording,
|
|
39
|
+
// recording is client-only; if SSR'd, gate UI on a mounted flag.
|
|
40
|
+
isSupported: AudioRecorder.isSupported(),
|
|
41
|
+
start,
|
|
42
|
+
stop,
|
|
43
|
+
cancel
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export {
|
|
47
|
+
useAudioRecorder
|
|
48
|
+
};
|
|
49
|
+
//# sourceMappingURL=use-audio-recorder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-audio-recorder.js","sources":["../../src/use-audio-recorder.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { AudioRecorder } from '@tanstack/ai-client'\nimport type {\n AudioRecorderOptions,\n AudioRecording,\n InferAudioRecordingOutput,\n} from '@tanstack/ai-client'\n\nexport type UseAudioRecorderOptions<TOnComplete> = AudioRecorderOptions & {\n /**\n * Optional transform applied to the recording when `stop()` resolves. Its\n * (awaited) return value becomes `recording` and the resolved value of\n * `stop()`. Return nothing to keep the raw `AudioRecording`.\n */\n onComplete?: TOnComplete\n}\n\nexport interface UseAudioRecorderReturn<TOutput> {\n /** Latest recording (transformed if `onComplete` provided), or null. */\n recording: TOutput | null\n /** True while actively capturing audio. */\n isRecording: boolean\n /** Whether the browser supports recording (getUserMedia + MediaRecorder). */\n isSupported: boolean\n /** Acquire the mic and begin recording. */\n start: () => Promise<void>\n /** Stop and resolve with the completed recording (transformed if `onComplete` provided). */\n stop: () => Promise<TOutput>\n /** Discard the in-progress recording and release the mic. */\n cancel: () => void\n}\n\n/**\n * React hook for recording an audio message. The resolved\n * {@link AudioRecording} carries `.part` (an audio content part for\n * `useChat.sendMessage`) and `.base64` (for the generation hooks).\n *\n * Errors are delivered via `onError`. `start()` and `stop()` also reject on\n * failure (and `stop()` rejects with `Recording cancelled` if the component\n * unmounts while a stop is in flight) — handle one channel, not both.\n *\n * @example\n * ```tsx\n * const { isRecording, start, stop, recording } = useAudioRecorder()\n * const { sendMessage } = useChat({ connection })\n * // ...\n * const rec = await stop()\n * sendMessage({ content: [rec.part] })\n * ```\n */\nexport function useAudioRecorder<\n TOnComplete extends (recording: AudioRecording) => unknown,\n>(\n options: UseAudioRecorderOptions<TOnComplete>,\n): UseAudioRecorderReturn<InferAudioRecordingOutput<TOnComplete>>\nexport function useAudioRecorder(\n options?: UseAudioRecorderOptions<undefined>,\n): UseAudioRecorderReturn<AudioRecording>\nexport function useAudioRecorder(\n options: UseAudioRecorderOptions<(recording: AudioRecording) => unknown> = {},\n): UseAudioRecorderReturn<unknown> {\n const [isRecording, setIsRecording] = useState(false)\n const [recording, setRecording] = useState<unknown>(null)\n // Read the freshest callbacks at fire time without recreating the recorder.\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const recorder = useMemo(\n () =>\n new AudioRecorder({\n ...(options.audio !== undefined && { audio: options.audio }),\n ...(options.mimeType !== undefined && { mimeType: options.mimeType }),\n onError: (err) => optionsRef.current.onError?.(err),\n }),\n // Recorder config (audio/mimeType) is captured once at mount, matching the\n // other hooks' create-once pattern.\n [],\n )\n\n useEffect(() => {\n const unsubscribe = recorder.subscribe((state) => {\n setIsRecording(state === 'recording')\n })\n return () => {\n unsubscribe()\n recorder.cancel()\n }\n }, [recorder])\n\n const start = useCallback(() => recorder.start(), [recorder])\n const stop = useCallback(async () => {\n const recording = await recorder.stop()\n const transformed = await optionsRef.current.onComplete?.(recording)\n // Only `undefined` (returning nothing) falls back to the raw recording, so\n // a transform that returns null is preserved — matching the inferred type,\n // which excludes only undefined/void/null from the transform's return.\n const output = transformed === undefined ? recording : transformed\n setRecording(() => output)\n return output\n }, [recorder])\n const cancel = useCallback(() => recorder.cancel(), [recorder])\n\n return {\n recording,\n isRecording,\n // recording is client-only; if SSR'd, gate UI on a mounted flag.\n isSupported: AudioRecorder.isSupported(),\n start,\n stop,\n cancel,\n }\n}\n"],"names":["recording"],"mappings":";;AA0DO,SAAS,iBACd,UAA2E,IAC1C;AACjC,QAAM,CAAC,aAAa,cAAc,IAAI,SAAS,KAAK;AACpD,QAAM,CAAC,WAAW,YAAY,IAAI,SAAkB,IAAI;AAExD,QAAM,aAAa,OAAO,OAAO;AACjC,aAAW,UAAU;AAErB,QAAM,WAAW;AAAA,IACf,MACE,IAAI,cAAc;AAAA,MAChB,GAAI,QAAQ,UAAU,UAAa,EAAE,OAAO,QAAQ,MAAA;AAAA,MACpD,GAAI,QAAQ,aAAa,UAAa,EAAE,UAAU,QAAQ,SAAA;AAAA,MAC1D,SAAS,CAAC,QAAQ,WAAW,QAAQ,UAAU,GAAG;AAAA,IAAA,CACnD;AAAA;AAAA;AAAA,IAGH,CAAA;AAAA,EAAC;AAGH,YAAU,MAAM;AACd,UAAM,cAAc,SAAS,UAAU,CAAC,UAAU;AAChD,qBAAe,UAAU,WAAW;AAAA,IACtC,CAAC;AACD,WAAO,MAAM;AACX,kBAAA;AACA,eAAS,OAAA;AAAA,IACX;AAAA,EACF,GAAG,CAAC,QAAQ,CAAC;AAEb,QAAM,QAAQ,YAAY,MAAM,SAAS,SAAS,CAAC,QAAQ,CAAC;AAC5D,QAAM,OAAO,YAAY,YAAY;AACnC,UAAMA,aAAY,MAAM,SAAS,KAAA;AACjC,UAAM,cAAc,MAAM,WAAW,QAAQ,aAAaA,UAAS;AAInE,UAAM,SAAS,gBAAgB,SAAYA,aAAY;AACvD,iBAAa,MAAM,MAAM;AACzB,WAAO;AAAA,EACT,GAAG,CAAC,QAAQ,CAAC;AACb,QAAM,SAAS,YAAY,MAAM,SAAS,UAAU,CAAC,QAAQ,CAAC;AAE9D,SAAO;AAAA,IACL;AAAA,IACA;AAAA;AAAA,IAEA,aAAa,cAAc,YAAA;AAAA,IAC3B;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AudioGenerationResult, StreamChunk } from '@tanstack/ai';
|
|
2
|
-
import { AIDevtoolsDisplayOptions, AudioGenerateInput, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher,
|
|
2
|
+
import { AIDevtoolsDisplayOptions, AudioGenerateInput, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, InferGenerationOutputFromReturn } from '@tanstack/ai-client';
|
|
3
3
|
/**
|
|
4
4
|
* Options for the useGenerateAudio hook.
|
|
5
5
|
*
|
|
@@ -82,6 +82,6 @@ export interface UseGenerateAudioReturn<TOutput = AudioGenerationResult> {
|
|
|
82
82
|
* }
|
|
83
83
|
* ```
|
|
84
84
|
*/
|
|
85
|
-
export declare function useGenerateAudio<
|
|
86
|
-
onResult?:
|
|
87
|
-
}): UseGenerateAudioReturn<
|
|
85
|
+
export declare function useGenerateAudio<TTransformed = void>(options: Omit<UseGenerateAudioOptions, 'onResult'> & {
|
|
86
|
+
onResult?: (result: AudioGenerationResult) => TTransformed;
|
|
87
|
+
}): UseGenerateAudioReturn<InferGenerationOutputFromReturn<AudioGenerationResult, TTransformed>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-audio.js","sources":["../../src/use-generate-audio.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport type { AudioGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n AudioGenerateInput,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n
|
|
1
|
+
{"version":3,"file":"use-generate-audio.js","sources":["../../src/use-generate-audio.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport type { AudioGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n AudioGenerateInput,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGenerateAudio hook.\n *\n * @template TOutput - The output type after optional transform (defaults to AudioGenerationResult)\n */\nexport interface UseGenerateAudioOptions<TOutput = AudioGenerationResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for audio generation */\n fetcher?: GenerationFetcher<AudioGenerateInput, AudioGenerationResult>\n /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when audio is generated. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: AudioGenerationResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the useGenerateAudio hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseGenerateAudioReturn<TOutput = AudioGenerationResult> {\n /** Trigger audio generation */\n generate: (input: AudioGenerateInput) => Promise<void>\n /** The generation result containing audio, or null */\n result: TOutput | null\n /** Whether generation is in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation */\n status: GenerationClientState\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n}\n\n/**\n * React hook for generating audio (music, sound effects) using AI models.\n *\n * Supports two transport modes:\n * - **ConnectConnectionAdapter** — Streaming transport (SSE, HTTP stream, custom)\n * - **Fetcher** — Direct async function call\n *\n * @example\n * ```tsx\n * import { useGenerateAudio } from '@tanstack/ai-react'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function AudioGenerator() {\n * const { generate, result, isLoading, error, reset } = useGenerateAudio({\n * connection: fetchServerSentEvents('/api/generate/audio'),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ prompt: 'An upbeat electronic track', duration: 10 })}>\n * Generate\n * </button>\n * {isLoading && <p>Generating...</p>}\n * {error && <p>Error: {error.message}</p>}\n * {result?.audio.url && <audio src={result.audio.url} controls />}\n * </div>\n * )\n * }\n * ```\n */\nexport function useGenerateAudio<TTransformed = void>(\n options: Omit<UseGenerateAudioOptions, 'onResult'> & {\n onResult?: (result: AudioGenerationResult) => TTransformed\n },\n): UseGenerateAudioReturn<\n InferGenerationOutputFromReturn<AudioGenerationResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'react',\n hookName: 'useGenerateAudio',\n outputKind: 'audio' as const,\n }\n const { generate, result, isLoading, error, status, stop, reset } =\n useGeneration<AudioGenerateInput, AudioGenerationResult, TTransformed>({\n ...options,\n devtools,\n })\n\n return {\n generate: generate as (input: AudioGenerateInput) => Promise<void>,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"names":[],"mappings":";AA+FO,SAAS,iBACd,SAKA;AACA,QAAM,WAAW;AAAA,IACf,GAAG,QAAQ;AAAA,IACX,WAAW;AAAA,IACX,UAAU;AAAA,IACV,YAAY;AAAA,EAAA;AAEd,QAAM,EAAE,UAAU,QAAQ,WAAW,OAAO,QAAQ,MAAM,MAAA,IACxD,cAAuE;AAAA,IACrE,GAAG;AAAA,IACH;AAAA,EAAA,CACD;AAEH,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ImageGenerationResult, StreamChunk } from '@tanstack/ai';
|
|
2
|
-
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, ImageGenerateInput,
|
|
2
|
+
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, ImageGenerateInput, InferGenerationOutputFromReturn } from '@tanstack/ai-client';
|
|
3
3
|
/**
|
|
4
4
|
* Options for the useGenerateImage hook.
|
|
5
5
|
*
|
|
@@ -84,6 +84,6 @@ export interface UseGenerateImageReturn<TOutput = ImageGenerationResult> {
|
|
|
84
84
|
* }
|
|
85
85
|
* ```
|
|
86
86
|
*/
|
|
87
|
-
export declare function useGenerateImage<
|
|
88
|
-
onResult?:
|
|
89
|
-
}): UseGenerateImageReturn<
|
|
87
|
+
export declare function useGenerateImage<TTransformed = void>(options: Omit<UseGenerateImageOptions, 'onResult'> & {
|
|
88
|
+
onResult?: (result: ImageGenerationResult) => TTransformed;
|
|
89
|
+
}): UseGenerateImageReturn<InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-image.js","sources":["../../src/use-generate-image.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport type { ImageGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n ImageGenerateInput,\n
|
|
1
|
+
{"version":3,"file":"use-generate-image.js","sources":["../../src/use-generate-image.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport type { ImageGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n ImageGenerateInput,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGenerateImage hook.\n *\n * @template TOutput - The output type after optional transform (defaults to ImageGenerationResult)\n */\nexport interface UseGenerateImageOptions<TOutput = ImageGenerationResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for image generation */\n fetcher?: GenerationFetcher<ImageGenerateInput, ImageGenerationResult>\n /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when images are generated. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: ImageGenerationResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the useGenerateImage hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseGenerateImageReturn<TOutput = ImageGenerationResult> {\n /** Trigger image generation */\n generate: (input: ImageGenerateInput) => Promise<void>\n /** The generation result containing images, or null */\n result: TOutput | null\n /** Whether generation is in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation */\n status: GenerationClientState\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n}\n\n/**\n * React hook for generating images using AI models.\n *\n * Supports two transport modes:\n * - **ConnectConnectionAdapter** — Streaming transport (SSE, HTTP stream, custom)\n * - **Fetcher** — Direct async function call\n *\n * @example\n * ```tsx\n * import { useGenerateImage } from '@tanstack/ai-react'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function ImageGenerator() {\n * const { generate, result, isLoading, error, reset } = useGenerateImage({\n * connection: fetchServerSentEvents('/api/generate/image'),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ prompt: 'A sunset over mountains' })}>\n * Generate\n * </button>\n * {isLoading && <p>Generating...</p>}\n * {error && <p>Error: {error.message}</p>}\n * {result?.images.map((img, i) => (\n * <img key={i} src={img.url || `data:image/png;base64,${img.b64Json}`} />\n * ))}\n * </div>\n * )\n * }\n * ```\n */\nexport function useGenerateImage<TTransformed = void>(\n options: Omit<UseGenerateImageOptions, 'onResult'> & {\n onResult?: (result: ImageGenerationResult) => TTransformed\n },\n): UseGenerateImageReturn<\n InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'react',\n hookName: 'useGenerateImage',\n outputKind: 'image' as const,\n }\n const { generate, result, isLoading, error, status, stop, reset } =\n useGeneration<ImageGenerateInput, ImageGenerationResult, TTransformed>({\n ...options,\n devtools,\n })\n\n return {\n generate: generate as (input: ImageGenerateInput) => Promise<void>,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"names":[],"mappings":";AAiGO,SAAS,iBACd,SAKA;AACA,QAAM,WAAW;AAAA,IACf,GAAG,QAAQ;AAAA,IACX,WAAW;AAAA,IACX,UAAU;AAAA,IACV,YAAY;AAAA,EAAA;AAEd,QAAM,EAAE,UAAU,QAAQ,WAAW,OAAO,QAAQ,MAAM,MAAA,IACxD,cAAuE;AAAA,IACrE,GAAG;AAAA,IACH;AAAA,EAAA,CACD;AAEH,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { StreamChunk, TTSResult } from '@tanstack/ai';
|
|
2
|
-
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher,
|
|
2
|
+
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, InferGenerationOutputFromReturn, SpeechGenerateInput } from '@tanstack/ai-client';
|
|
3
3
|
/**
|
|
4
4
|
* Options for the useGenerateSpeech hook.
|
|
5
5
|
*
|
|
@@ -78,6 +78,6 @@ export interface UseGenerateSpeechReturn<TOutput = TTSResult> {
|
|
|
78
78
|
* }
|
|
79
79
|
* ```
|
|
80
80
|
*/
|
|
81
|
-
export declare function useGenerateSpeech<
|
|
82
|
-
onResult?:
|
|
83
|
-
}): UseGenerateSpeechReturn<
|
|
81
|
+
export declare function useGenerateSpeech<TTransformed = void>(options: Omit<UseGenerateSpeechOptions, 'onResult'> & {
|
|
82
|
+
onResult?: (result: TTSResult) => TTransformed;
|
|
83
|
+
}): UseGenerateSpeechReturn<InferGenerationOutputFromReturn<TTSResult, TTransformed>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-speech.js","sources":["../../src/use-generate-speech.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport type { StreamChunk, TTSResult } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n
|
|
1
|
+
{"version":3,"file":"use-generate-speech.js","sources":["../../src/use-generate-speech.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport type { StreamChunk, TTSResult } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n SpeechGenerateInput,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGenerateSpeech hook.\n *\n * @template TOutput - The output type after optional transform (defaults to TTSResult)\n */\nexport interface UseGenerateSpeechOptions<TOutput = TTSResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for speech generation */\n fetcher?: GenerationFetcher<SpeechGenerateInput, TTSResult>\n /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when speech is generated. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: TTSResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the useGenerateSpeech hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseGenerateSpeechReturn<TOutput = TTSResult> {\n /** Trigger speech generation */\n generate: (input: SpeechGenerateInput) => Promise<void>\n /** The TTS result containing audio data, or null */\n result: TOutput | null\n /** Whether generation is in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation */\n status: GenerationClientState\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n}\n\n/**\n * React hook for generating speech (text-to-speech) using AI models.\n *\n * @example\n * ```tsx\n * import { useGenerateSpeech } from '@tanstack/ai-react'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function SpeechGenerator() {\n * const { generate, result, isLoading } = useGenerateSpeech({\n * connection: fetchServerSentEvents('/api/generate/speech'),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ text: 'Hello world', voice: 'alloy' })}>\n * Generate Speech\n * </button>\n * {result && (\n * <audio src={`data:audio/${result.format};base64,${result.audio}`} controls />\n * )}\n * </div>\n * )\n * }\n * ```\n */\nexport function useGenerateSpeech<TTransformed = void>(\n options: Omit<UseGenerateSpeechOptions, 'onResult'> & {\n onResult?: (result: TTSResult) => TTransformed\n },\n): UseGenerateSpeechReturn<\n InferGenerationOutputFromReturn<TTSResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'react',\n hookName: 'useGenerateSpeech',\n outputKind: 'audio' as const,\n }\n const { generate, result, isLoading, error, status, stop, reset } =\n useGeneration<SpeechGenerateInput, TTSResult, TTransformed>({\n ...options,\n devtools,\n })\n\n return {\n generate: generate as (input: SpeechGenerateInput) => Promise<void>,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"names":[],"mappings":";AA2FO,SAAS,kBACd,SAKA;AACA,QAAM,WAAW;AAAA,IACf,GAAG,QAAQ;AAAA,IACX,WAAW;AAAA,IACX,UAAU;AAAA,IACV,YAAY;AAAA,EAAA;AAEd,QAAM,EAAE,UAAU,QAAQ,WAAW,OAAO,QAAQ,MAAM,MAAA,IACxD,cAA4D;AAAA,IAC1D,GAAG;AAAA,IACH;AAAA,EAAA,CACD;AAEH,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { StreamChunk } from '@tanstack/ai';
|
|
2
|
-
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher,
|
|
2
|
+
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, InferGenerationOutputFromReturn, VideoGenerateInput, VideoGenerateResult, VideoStatusInfo } from '@tanstack/ai-client';
|
|
3
3
|
/**
|
|
4
4
|
* Options for the useGenerateVideo hook.
|
|
5
5
|
*/
|
|
@@ -89,6 +89,6 @@ export interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {
|
|
|
89
89
|
* }
|
|
90
90
|
* ```
|
|
91
91
|
*/
|
|
92
|
-
export declare function useGenerateVideo<
|
|
93
|
-
onResult?:
|
|
94
|
-
}): UseGenerateVideoReturn<
|
|
92
|
+
export declare function useGenerateVideo<TTransformed = void>(options: Omit<UseGenerateVideoOptions, 'onResult'> & {
|
|
93
|
+
onResult?: (result: VideoGenerateResult) => TTransformed;
|
|
94
|
+
}): UseGenerateVideoReturn<InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>>;
|
|
@@ -24,7 +24,10 @@ function useGenerateVideo(options) {
|
|
|
24
24
|
hookName: "useGenerateVideo",
|
|
25
25
|
outputKind: "video"
|
|
26
26
|
},
|
|
27
|
-
|
|
27
|
+
// The transform's raw return type (`TTransformed`) and the stored output
|
|
28
|
+
// (`TOutput`, with null/void/undefined stripped) are identical at runtime;
|
|
29
|
+
// the cast bridges the relationship that the conditional type hides.
|
|
30
|
+
onResult: ((r) => optionsRef.current.onResult?.(r)),
|
|
28
31
|
onError: (e) => {
|
|
29
32
|
optionsRef.current.onError?.(e);
|
|
30
33
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-video.js","sources":["../../src/use-generate-video.ts"],"sourcesContent":["import { VideoGenerationClient } from '@tanstack/ai-client'\nimport { createVideoDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutput,\n VideoGenerateInput,\n VideoGenerateResult,\n VideoStatusInfo,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGenerateVideo hook.\n */\nexport interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {\n /** Connect-based adapter for streaming transport (server handles polling) */\n connection?: ConnectConnectionAdapter\n /** Direct async function that returns a completed video result */\n fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>\n /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when video generation completes. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: VideoGenerateResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback when a video job is created */\n onJobCreated?: (jobId: string) => void\n /** Callback on each status update */\n onStatusUpdate?: (status: VideoStatusInfo) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the useGenerateVideo hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {\n /** Trigger video generation */\n generate: (input: VideoGenerateInput) => Promise<void>\n /** The final video result (with URL), or null */\n result: TOutput | null\n /** The current job ID, or null */\n jobId: string | null\n /** Current video generation status info, or null */\n videoStatus: VideoStatusInfo | null\n /** Whether generation/polling is in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation */\n status: GenerationClientState\n /** Abort the current generation/polling */\n stop: () => void\n /** Clear all state and return to idle */\n reset: () => void\n}\n\n/**\n * React hook for generating videos using AI models.\n *\n * Video generation is asynchronous: a job is created, then polled for status\n * until completion. This hook handles the full lifecycle.\n *\n * @example\n * ```tsx\n * import { useGenerateVideo } from '@tanstack/ai-react'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function VideoGenerator() {\n * const { generate, result, videoStatus, isLoading } = useGenerateVideo({\n * connection: fetchServerSentEvents('/api/generate/video'),\n * onStatusUpdate: (status) => console.log(`Progress: ${status.progress}%`),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ prompt: 'A flying car over a city' })}>\n * Generate Video\n * </button>\n * {isLoading && videoStatus && (\n * <p>Status: {videoStatus.status} ({videoStatus.progress}%)</p>\n * )}\n * {result && <video src={result.url} controls />}\n * </div>\n * )\n * }\n * ```\n */\nexport function useGenerateVideo<\n TOnResult extends ((result: VideoGenerateResult) => any) | undefined =\n undefined,\n>(\n options: Omit<UseGenerateVideoOptions, 'onResult'> & {\n onResult?: TOnResult\n },\n): UseGenerateVideoReturn<\n InferGenerationOutput<VideoGenerateResult, TOnResult>\n> {\n type TOutput = InferGenerationOutput<VideoGenerateResult, TOnResult>\n const hookId = useId()\n const clientId = options.id || hookId\n\n const [result, setResult] = useState<TOutput | null>(null)\n const [jobId, setJobId] = useState<string | null>(null)\n const [videoStatus, setVideoStatus] = useState<VideoStatusInfo | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n const [status, setStatus] = useState<GenerationClientState>('idle')\n\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const client = useMemo(() => {\n const opts = optionsRef.current\n\n // Conditional spread for `body` (strict-optional in target).\n // Optional callbacks are wrapped in non-returning bodies so\n // `?.()`'s implicit `undefined` doesn't widen the function\n // return type (which `exactOptionalPropertyTypes` rejects\n // against the strict-optional target).\n const baseOptions = {\n id: clientId,\n body: opts.body,\n devtoolsBridgeFactory: createVideoDevtoolsBridge,\n devtools: {\n ...opts.devtools,\n framework: 'react',\n hookName: 'useGenerateVideo',\n outputKind: 'video' as const,\n },\n onResult: (r: VideoGenerateResult) => optionsRef.current.onResult?.(r),\n onError: (e: Error) => {\n optionsRef.current.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n optionsRef.current.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n optionsRef.current.onChunk?.(c)\n },\n onJobCreated: (id: string) => {\n optionsRef.current.onJobCreated?.(id)\n },\n onStatusUpdate: (s: VideoStatusInfo) => {\n optionsRef.current.onStatusUpdate?.(s)\n },\n onResultChange: setResult,\n onLoadingChange: setIsLoading,\n onErrorChange: setError,\n onStatusChange: setStatus,\n onJobIdChange: setJobId,\n onVideoStatusChange: setVideoStatus,\n }\n\n if (opts.connection) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n connection: opts.connection,\n })\n }\n\n if (opts.fetcher) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n fetcher: opts.fetcher,\n })\n }\n\n throw new Error(\n 'useGenerateVideo requires either a connection or fetcher option',\n )\n }, [clientId])\n\n // Sync body changes without recreating client\n useEffect(() => {\n // Conditional spread: target uses strict-optional `body?: T`.\n client.updateOptions({\n ...(options.body !== undefined && { body: options.body }),\n })\n }, [client, options.body])\n\n // Cleanup on unmount\n useEffect(() => {\n client.mountDevtools()\n\n return () => {\n client.dispose()\n }\n }, [client])\n\n const generate = useCallback(\n async (input: VideoGenerateInput) => {\n await client.generate(input)\n },\n [client],\n )\n\n const stop = useCallback(() => {\n client.stop()\n }, [client])\n\n const reset = useCallback(() => {\n client.reset()\n }, [client])\n\n return {\n generate,\n result,\n jobId,\n videoStatus,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"names":[],"mappings":";;;AA0GO,SAAS,iBAId,SAKA;AAEA,QAAM,SAAS,MAAA;AACf,QAAM,WAAW,QAAQ,MAAM;AAE/B,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAyB,IAAI;AACzD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAwB,IAAI;AACtD,QAAM,CAAC,aAAa,cAAc,IAAI,SAAiC,IAAI;AAC3E,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA4B,MAAS;AAC/D,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAgC,MAAM;AAElE,QAAM,aAAa,OAAO,OAAO;AACjC,aAAW,UAAU;AAErB,QAAM,SAAS,QAAQ,MAAM;AAC3B,UAAM,OAAO,WAAW;AAOxB,UAAM,cAAc;AAAA,MAClB,IAAI;AAAA,MACJ,MAAM,KAAK;AAAA,MACX,uBAAuB;AAAA,MACvB,UAAU;AAAA,QACR,GAAG,KAAK;AAAA,QACR,WAAW;AAAA,QACX,UAAU;AAAA,QACV,YAAY;AAAA,MAAA;AAAA,MAEd,UAAU,CAAC,MAA2B,WAAW,QAAQ,WAAW,CAAC;AAAA,MACrE,SAAS,CAAC,MAAa;AACrB,mBAAW,QAAQ,UAAU,CAAC;AAAA,MAChC;AAAA,MACA,YAAY,CAAC,GAAW,MAAe;AACrC,mBAAW,QAAQ,aAAa,GAAG,CAAC;AAAA,MACtC;AAAA,MACA,SAAS,CAAC,MAAmB;AAC3B,mBAAW,QAAQ,UAAU,CAAC;AAAA,MAChC;AAAA,MACA,cAAc,CAAC,OAAe;AAC5B,mBAAW,QAAQ,eAAe,EAAE;AAAA,MACtC;AAAA,MACA,gBAAgB,CAAC,MAAuB;AACtC,mBAAW,QAAQ,iBAAiB,CAAC;AAAA,MACvC;AAAA,MACA,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,MACjB,eAAe;AAAA,MACf,gBAAgB;AAAA,MAChB,eAAe;AAAA,MACf,qBAAqB;AAAA,IAAA;AAGvB,QAAI,KAAK,YAAY;AACnB,aAAO,IAAI,sBAA+B;AAAA,QACxC,GAAG;AAAA,QACH,YAAY,KAAK;AAAA,MAAA,CAClB;AAAA,IACH;AAEA,QAAI,KAAK,SAAS;AAChB,aAAO,IAAI,sBAA+B;AAAA,QACxC,GAAG;AAAA,QACH,SAAS,KAAK;AAAA,MAAA,CACf;AAAA,IACH;AAEA,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ,GAAG,CAAC,QAAQ,CAAC;AAGb,YAAU,MAAM;AAEd,WAAO,cAAc;AAAA,MACnB,GAAI,QAAQ,SAAS,UAAa,EAAE,MAAM,QAAQ,KAAA;AAAA,IAAK,CACxD;AAAA,EACH,GAAG,CAAC,QAAQ,QAAQ,IAAI,CAAC;AAGzB,YAAU,MAAM;AACd,WAAO,cAAA;AAEP,WAAO,MAAM;AACX,aAAO,QAAA;AAAA,IACT;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,WAAW;AAAA,IACf,OAAO,UAA8B;AACnC,YAAM,OAAO,SAAS,KAAK;AAAA,IAC7B;AAAA,IACA,CAAC,MAAM;AAAA,EAAA;AAGT,QAAM,OAAO,YAAY,MAAM;AAC7B,WAAO,KAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,QAAQ,YAAY,MAAM;AAC9B,WAAO,MAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"use-generate-video.js","sources":["../../src/use-generate-video.ts"],"sourcesContent":["import { VideoGenerationClient } from '@tanstack/ai-client'\nimport { createVideoDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n VideoGenerateInput,\n VideoGenerateResult,\n VideoStatusInfo,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGenerateVideo hook.\n */\nexport interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {\n /** Connect-based adapter for streaming transport (server handles polling) */\n connection?: ConnectConnectionAdapter\n /** Direct async function that returns a completed video result */\n fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>\n /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when video generation completes. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: VideoGenerateResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback when a video job is created */\n onJobCreated?: (jobId: string) => void\n /** Callback on each status update */\n onStatusUpdate?: (status: VideoStatusInfo) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the useGenerateVideo hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {\n /** Trigger video generation */\n generate: (input: VideoGenerateInput) => Promise<void>\n /** The final video result (with URL), or null */\n result: TOutput | null\n /** The current job ID, or null */\n jobId: string | null\n /** Current video generation status info, or null */\n videoStatus: VideoStatusInfo | null\n /** Whether generation/polling is in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation */\n status: GenerationClientState\n /** Abort the current generation/polling */\n stop: () => void\n /** Clear all state and return to idle */\n reset: () => void\n}\n\n/**\n * React hook for generating videos using AI models.\n *\n * Video generation is asynchronous: a job is created, then polled for status\n * until completion. This hook handles the full lifecycle.\n *\n * @example\n * ```tsx\n * import { useGenerateVideo } from '@tanstack/ai-react'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function VideoGenerator() {\n * const { generate, result, videoStatus, isLoading } = useGenerateVideo({\n * connection: fetchServerSentEvents('/api/generate/video'),\n * onStatusUpdate: (status) => console.log(`Progress: ${status.progress}%`),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ prompt: 'A flying car over a city' })}>\n * Generate Video\n * </button>\n * {isLoading && videoStatus && (\n * <p>Status: {videoStatus.status} ({videoStatus.progress}%)</p>\n * )}\n * {result && <video src={result.url} controls />}\n * </div>\n * )\n * }\n * ```\n */\n// `TTransformed` infers from the `onResult` return position so the callback\n// parameter is typed as `VideoGenerateResult` and `result` narrows to the\n// transform's return. See issue #848.\nexport function useGenerateVideo<TTransformed = void>(\n options: Omit<UseGenerateVideoOptions, 'onResult'> & {\n onResult?: (result: VideoGenerateResult) => TTransformed\n },\n): UseGenerateVideoReturn<\n InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>\n> {\n type TOutput = InferGenerationOutputFromReturn<\n VideoGenerateResult,\n TTransformed\n >\n const hookId = useId()\n const clientId = options.id || hookId\n\n const [result, setResult] = useState<TOutput | null>(null)\n const [jobId, setJobId] = useState<string | null>(null)\n const [videoStatus, setVideoStatus] = useState<VideoStatusInfo | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n const [status, setStatus] = useState<GenerationClientState>('idle')\n\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const client = useMemo(() => {\n const opts = optionsRef.current\n\n // Conditional spread for `body` (strict-optional in target).\n // Optional callbacks are wrapped in non-returning bodies so\n // `?.()`'s implicit `undefined` doesn't widen the function\n // return type (which `exactOptionalPropertyTypes` rejects\n // against the strict-optional target).\n const baseOptions = {\n id: clientId,\n body: opts.body,\n devtoolsBridgeFactory: createVideoDevtoolsBridge,\n devtools: {\n ...opts.devtools,\n framework: 'react',\n hookName: 'useGenerateVideo',\n outputKind: 'video' as const,\n },\n // The transform's raw return type (`TTransformed`) and the stored output\n // (`TOutput`, with null/void/undefined stripped) are identical at runtime;\n // the cast bridges the relationship that the conditional type hides.\n onResult: ((r: VideoGenerateResult) =>\n optionsRef.current.onResult?.(r)) as (\n result: VideoGenerateResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n optionsRef.current.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n optionsRef.current.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n optionsRef.current.onChunk?.(c)\n },\n onJobCreated: (id: string) => {\n optionsRef.current.onJobCreated?.(id)\n },\n onStatusUpdate: (s: VideoStatusInfo) => {\n optionsRef.current.onStatusUpdate?.(s)\n },\n onResultChange: setResult,\n onLoadingChange: setIsLoading,\n onErrorChange: setError,\n onStatusChange: setStatus,\n onJobIdChange: setJobId,\n onVideoStatusChange: setVideoStatus,\n }\n\n if (opts.connection) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n connection: opts.connection,\n })\n }\n\n if (opts.fetcher) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n fetcher: opts.fetcher,\n })\n }\n\n throw new Error(\n 'useGenerateVideo requires either a connection or fetcher option',\n )\n }, [clientId])\n\n // Sync body changes without recreating client\n useEffect(() => {\n // Conditional spread: target uses strict-optional `body?: T`.\n client.updateOptions({\n ...(options.body !== undefined && { body: options.body }),\n })\n }, [client, options.body])\n\n // Cleanup on unmount\n useEffect(() => {\n client.mountDevtools()\n\n return () => {\n client.dispose()\n }\n }, [client])\n\n const generate = useCallback(\n async (input: VideoGenerateInput) => {\n await client.generate(input)\n },\n [client],\n )\n\n const stop = useCallback(() => {\n client.stop()\n }, [client])\n\n const reset = useCallback(() => {\n client.reset()\n }, [client])\n\n return {\n generate,\n result,\n jobId,\n videoStatus,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"names":[],"mappings":";;;AA6GO,SAAS,iBACd,SAKA;AAKA,QAAM,SAAS,MAAA;AACf,QAAM,WAAW,QAAQ,MAAM;AAE/B,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAyB,IAAI;AACzD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAwB,IAAI;AACtD,QAAM,CAAC,aAAa,cAAc,IAAI,SAAiC,IAAI;AAC3E,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA4B,MAAS;AAC/D,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAgC,MAAM;AAElE,QAAM,aAAa,OAAO,OAAO;AACjC,aAAW,UAAU;AAErB,QAAM,SAAS,QAAQ,MAAM;AAC3B,UAAM,OAAO,WAAW;AAOxB,UAAM,cAAc;AAAA,MAClB,IAAI;AAAA,MACJ,MAAM,KAAK;AAAA,MACX,uBAAuB;AAAA,MACvB,UAAU;AAAA,QACR,GAAG,KAAK;AAAA,QACR,WAAW;AAAA,QACX,UAAU;AAAA,QACV,YAAY;AAAA,MAAA;AAAA;AAAA;AAAA;AAAA,MAKd,WAAW,CAAC,MACV,WAAW,QAAQ,WAAW,CAAC;AAAA,MAGjC,SAAS,CAAC,MAAa;AACrB,mBAAW,QAAQ,UAAU,CAAC;AAAA,MAChC;AAAA,MACA,YAAY,CAAC,GAAW,MAAe;AACrC,mBAAW,QAAQ,aAAa,GAAG,CAAC;AAAA,MACtC;AAAA,MACA,SAAS,CAAC,MAAmB;AAC3B,mBAAW,QAAQ,UAAU,CAAC;AAAA,MAChC;AAAA,MACA,cAAc,CAAC,OAAe;AAC5B,mBAAW,QAAQ,eAAe,EAAE;AAAA,MACtC;AAAA,MACA,gBAAgB,CAAC,MAAuB;AACtC,mBAAW,QAAQ,iBAAiB,CAAC;AAAA,MACvC;AAAA,MACA,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,MACjB,eAAe;AAAA,MACf,gBAAgB;AAAA,MAChB,eAAe;AAAA,MACf,qBAAqB;AAAA,IAAA;AAGvB,QAAI,KAAK,YAAY;AACnB,aAAO,IAAI,sBAA+B;AAAA,QACxC,GAAG;AAAA,QACH,YAAY,KAAK;AAAA,MAAA,CAClB;AAAA,IACH;AAEA,QAAI,KAAK,SAAS;AAChB,aAAO,IAAI,sBAA+B;AAAA,QACxC,GAAG;AAAA,QACH,SAAS,KAAK;AAAA,MAAA,CACf;AAAA,IACH;AAEA,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ,GAAG,CAAC,QAAQ,CAAC;AAGb,YAAU,MAAM;AAEd,WAAO,cAAc;AAAA,MACnB,GAAI,QAAQ,SAAS,UAAa,EAAE,MAAM,QAAQ,KAAA;AAAA,IAAK,CACxD;AAAA,EACH,GAAG,CAAC,QAAQ,QAAQ,IAAI,CAAC;AAGzB,YAAU,MAAM;AACd,WAAO,cAAA;AAEP,WAAO,MAAM;AACX,aAAO,QAAA;AAAA,IACT;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,WAAW;AAAA,IACf,OAAO,UAA8B;AACnC,YAAM,OAAO,SAAS,KAAK;AAAA,IAC7B;AAAA,IACA,CAAC,MAAM;AAAA,EAAA;AAGT,QAAM,OAAO,YAAY,MAAM;AAC7B,WAAO,KAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,QAAQ,YAAY,MAAM;AAC9B,WAAO,MAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { StreamChunk } from '@tanstack/ai';
|
|
2
|
-
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher,
|
|
2
|
+
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, InferGenerationOutputFromReturn } from '@tanstack/ai-client';
|
|
3
3
|
/**
|
|
4
4
|
* Options for the useGeneration hook.
|
|
5
5
|
*
|
|
@@ -75,6 +75,6 @@ export interface UseGenerationReturn<TOutput> {
|
|
|
75
75
|
* await generate({ prompt: 'Hello' })
|
|
76
76
|
* ```
|
|
77
77
|
*/
|
|
78
|
-
export declare function useGeneration<TInput extends Record<string, any>, TResult,
|
|
79
|
-
onResult?:
|
|
80
|
-
}): UseGenerationReturn<
|
|
78
|
+
export declare function useGeneration<TInput extends Record<string, any>, TResult, TTransformed = void>(options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult'> & {
|
|
79
|
+
onResult?: (result: TResult) => TTransformed;
|
|
80
|
+
}): UseGenerationReturn<InferGenerationOutputFromReturn<TResult, TTransformed>>;
|
|
@@ -21,7 +21,10 @@ function useGeneration(options) {
|
|
|
21
21
|
framework: "react",
|
|
22
22
|
...opts.devtools
|
|
23
23
|
},
|
|
24
|
-
|
|
24
|
+
// The transform's raw return type (`TTransformed`) and the stored output
|
|
25
|
+
// (`TOutput`, with null/void/undefined stripped) are identical at runtime;
|
|
26
|
+
// the cast bridges the relationship that the conditional type hides.
|
|
27
|
+
onResult: ((r) => optionsRef.current.onResult?.(r)),
|
|
25
28
|
onError: (e) => {
|
|
26
29
|
optionsRef.current.onError?.(e);
|
|
27
30
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generation.js","sources":["../../src/use-generation.ts"],"sourcesContent":["import { GenerationClient } from '@tanstack/ai-client'\nimport { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientOptions,\n GenerationClientState,\n GenerationFetcher,\n
|
|
1
|
+
{"version":3,"file":"use-generation.js","sources":["../../src/use-generation.ts"],"sourcesContent":["import { GenerationClient } from '@tanstack/ai-client'\nimport { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientOptions,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGeneration hook.\n *\n * Accepts either a `connection` (streaming transport) or a `fetcher` (direct async call).\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n * @template TOutput - The output type after optional transform (defaults to TResult)\n */\nexport interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for one-shot generation (no streaming protocol needed) */\n fetcher?: GenerationFetcher<TInput, TResult>\n /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when a result is received. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: TResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the useGeneration hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseGenerationReturn<TOutput> {\n /** Trigger a generation request */\n generate: (input: Record<string, any>) => Promise<void>\n /** The generation result, or null if not yet generated */\n result: TOutput | null\n /** Whether a generation is currently in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation client */\n status: GenerationClientState\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n}\n\n/**\n * Generic React hook for one-shot generation tasks.\n *\n * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,\n * `useTranscription`, and `useSummarize`. You can also use it directly\n * for custom generation types.\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n *\n * @example\n * ```tsx\n * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({\n * connection: fetchServerSentEvents('/api/generate/custom'),\n * })\n *\n * await generate({ prompt: 'Hello' })\n * ```\n */\n// `TTransformed` infers from the `onResult` return position (a covariant\n// inference site that works even for an optional nested property), which types\n// the callback parameter as `TResult` and narrows `result`. Inferring the\n// whole callback as a defaulted type parameter instead collapses to the\n// default, leaving the parameter `any` — a hard error under `strict`. See\n// issue #848.\nexport function useGeneration<\n TInput extends Record<string, any>,\n TResult,\n TTransformed = void,\n>(\n options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult'> & {\n onResult?: (result: TResult) => TTransformed\n },\n): UseGenerationReturn<InferGenerationOutputFromReturn<TResult, TTransformed>> {\n type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>\n const hookId = useId()\n const clientId = options.id || hookId\n\n const [result, setResult] = useState<TOutput | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n const [status, setStatus] = useState<GenerationClientState>('idle')\n\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const client = useMemo(() => {\n const opts = optionsRef.current\n\n // Conditional spread for `body` (strict-optional in target;\n // local source is `Record<string, any> | undefined`). Callbacks\n // wrap optional ones in non-returning bodies so `?.()`'s\n // implicit `undefined` doesn't pollute the function return type.\n const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {\n id: clientId,\n body: opts.body,\n devtoolsBridgeFactory: createGenerationDevtoolsBridge,\n devtools: {\n hookName: 'useGeneration',\n framework: 'react',\n ...opts.devtools,\n },\n // The transform's raw return type (`TTransformed`) and the stored output\n // (`TOutput`, with null/void/undefined stripped) are identical at runtime;\n // the cast bridges the relationship that the conditional type hides.\n onResult: ((r: TResult) => optionsRef.current.onResult?.(r)) as (\n result: TResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n optionsRef.current.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n optionsRef.current.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n optionsRef.current.onChunk?.(c)\n },\n onResultChange: setResult,\n onLoadingChange: setIsLoading,\n onErrorChange: setError,\n onStatusChange: setStatus,\n }\n\n if (opts.connection) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n connection: opts.connection,\n })\n }\n\n if (opts.fetcher) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n fetcher: opts.fetcher,\n })\n }\n\n throw new Error(\n 'useGeneration requires either a connection or fetcher option',\n )\n }, [clientId])\n\n // Sync body changes without recreating client\n useEffect(() => {\n // Conditional spread: target uses strict-optional `body?: T`.\n client.updateOptions({\n ...(options.body !== undefined && { body: options.body }),\n })\n }, [client, options.body])\n\n // Cleanup on unmount\n useEffect(() => {\n client.mountDevtools()\n\n return () => {\n client.dispose()\n }\n }, [client])\n\n const generate = useCallback(\n async (input: TInput) => {\n await client.generate(input)\n },\n [client],\n )\n\n const stop = useCallback(() => {\n client.stop()\n }, [client])\n\n const reset = useCallback(() => {\n client.reset()\n }, [client])\n\n return {\n generate: generate as (input: Record<string, any>) => Promise<void>,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"names":[],"mappings":";;;AAgGO,SAAS,cAKd,SAG6E;AAE7E,QAAM,SAAS,MAAA;AACf,QAAM,WAAW,QAAQ,MAAM;AAE/B,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAyB,IAAI;AACzD,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA4B,MAAS;AAC/D,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAgC,MAAM;AAElE,QAAM,aAAa,OAAO,OAAO;AACjC,aAAW,UAAU;AAErB,QAAM,SAAS,QAAQ,MAAM;AAC3B,UAAM,OAAO,WAAW;AAMxB,UAAM,gBAAmE;AAAA,MACvE,IAAI;AAAA,MACJ,MAAM,KAAK;AAAA,MACX,uBAAuB;AAAA,MACvB,UAAU;AAAA,QACR,UAAU;AAAA,QACV,WAAW;AAAA,QACX,GAAG,KAAK;AAAA,MAAA;AAAA;AAAA;AAAA;AAAA,MAKV,WAAW,CAAC,MAAe,WAAW,QAAQ,WAAW,CAAC;AAAA,MAG1D,SAAS,CAAC,MAAa;AACrB,mBAAW,QAAQ,UAAU,CAAC;AAAA,MAChC;AAAA,MACA,YAAY,CAAC,GAAW,MAAe;AACrC,mBAAW,QAAQ,aAAa,GAAG,CAAC;AAAA,MACtC;AAAA,MACA,SAAS,CAAC,MAAmB;AAC3B,mBAAW,QAAQ,UAAU,CAAC;AAAA,MAChC;AAAA,MACA,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,MACjB,eAAe;AAAA,MACf,gBAAgB;AAAA,IAAA;AAGlB,QAAI,KAAK,YAAY;AACnB,aAAO,IAAI,iBAA2C;AAAA,QACpD,GAAG;AAAA,QACH,YAAY,KAAK;AAAA,MAAA,CAClB;AAAA,IACH;AAEA,QAAI,KAAK,SAAS;AAChB,aAAO,IAAI,iBAA2C;AAAA,QACpD,GAAG;AAAA,QACH,SAAS,KAAK;AAAA,MAAA,CACf;AAAA,IACH;AAEA,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ,GAAG,CAAC,QAAQ,CAAC;AAGb,YAAU,MAAM;AAEd,WAAO,cAAc;AAAA,MACnB,GAAI,QAAQ,SAAS,UAAa,EAAE,MAAM,QAAQ,KAAA;AAAA,IAAK,CACxD;AAAA,EACH,GAAG,CAAC,QAAQ,QAAQ,IAAI,CAAC;AAGzB,YAAU,MAAM;AACd,WAAO,cAAA;AAEP,WAAO,MAAM;AACX,aAAO,QAAA;AAAA,IACT;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,WAAW;AAAA,IACf,OAAO,UAAkB;AACvB,YAAM,OAAO,SAAS,KAAK;AAAA,IAC7B;AAAA,IACA,CAAC,MAAM;AAAA,EAAA;AAGT,QAAM,OAAO,YAAY,MAAM;AAC7B,WAAO,KAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,QAAQ,YAAY,MAAM;AAC9B,WAAO,MAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { CreateMcpAppBridgeOptions, McpAppBridge } from '@tanstack/ai-client';
|
|
2
|
+
export type UseMcpAppBridgeOptions = CreateMcpAppBridgeOptions;
|
|
3
|
+
/**
|
|
4
|
+
* React wrapper around `createMcpAppBridge` that returns a **stable** bridge for
|
|
5
|
+
* the given `threadId`/`callEndpoint`, while always invoking the latest
|
|
6
|
+
* `chat.sendMessage` and `onLink` (kept in refs). This avoids both recreating
|
|
7
|
+
* the bridge on every render and the stale-closure / `exhaustive-deps` dance
|
|
8
|
+
* you'd otherwise write by hand:
|
|
9
|
+
*
|
|
10
|
+
* ```tsx
|
|
11
|
+
* const { sendMessage } = useChat({ threadId, connection })
|
|
12
|
+
* const bridge = useMcpAppBridge({
|
|
13
|
+
* threadId,
|
|
14
|
+
* callEndpoint: '/api/mcp-apps-call',
|
|
15
|
+
* chat: { sendMessage: async (content) => void sendMessage(content) },
|
|
16
|
+
* onLink: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
|
|
17
|
+
* })
|
|
18
|
+
* // pass `bridge` to <MCPAppResource bridge={bridge} … />
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* The bridge is recreated only when `threadId`, `callEndpoint`, `fetchImpl`, or
|
|
22
|
+
* the *presence* of `onLink` changes — passing a new inline `onLink`/`sendMessage`
|
|
23
|
+
* each render does not churn it.
|
|
24
|
+
*/
|
|
25
|
+
export declare function useMcpAppBridge(options: UseMcpAppBridgeOptions): McpAppBridge;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { useRef, useMemo } from "react";
|
|
2
|
+
import { createMcpAppBridge } from "@tanstack/ai-client";
|
|
3
|
+
function useMcpAppBridge(options) {
|
|
4
|
+
const { threadId, callEndpoint, chat, fetchImpl, onLink } = options;
|
|
5
|
+
const chatRef = useRef(chat);
|
|
6
|
+
chatRef.current = chat;
|
|
7
|
+
const onLinkRef = useRef(onLink);
|
|
8
|
+
onLinkRef.current = onLink;
|
|
9
|
+
const hasOnLink = onLink != null;
|
|
10
|
+
return useMemo(
|
|
11
|
+
() => createMcpAppBridge({
|
|
12
|
+
threadId,
|
|
13
|
+
callEndpoint,
|
|
14
|
+
fetchImpl,
|
|
15
|
+
chat: {
|
|
16
|
+
sendMessage: (content, body) => chatRef.current.sendMessage(content, body)
|
|
17
|
+
},
|
|
18
|
+
onLink: hasOnLink ? (url) => onLinkRef.current?.(url) : void 0
|
|
19
|
+
}),
|
|
20
|
+
[threadId, callEndpoint, fetchImpl, hasOnLink]
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
export {
|
|
24
|
+
useMcpAppBridge
|
|
25
|
+
};
|
|
26
|
+
//# sourceMappingURL=use-mcp-app-bridge.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-mcp-app-bridge.js","sources":["../../src/use-mcp-app-bridge.ts"],"sourcesContent":["import { useMemo, useRef } from 'react'\nimport { createMcpAppBridge } from '@tanstack/ai-client'\nimport type {\n CreateMcpAppBridgeOptions,\n McpAppBridge,\n} from '@tanstack/ai-client'\n\nexport type UseMcpAppBridgeOptions = CreateMcpAppBridgeOptions\n\n/**\n * React wrapper around `createMcpAppBridge` that returns a **stable** bridge for\n * the given `threadId`/`callEndpoint`, while always invoking the latest\n * `chat.sendMessage` and `onLink` (kept in refs). This avoids both recreating\n * the bridge on every render and the stale-closure / `exhaustive-deps` dance\n * you'd otherwise write by hand:\n *\n * ```tsx\n * const { sendMessage } = useChat({ threadId, connection })\n * const bridge = useMcpAppBridge({\n * threadId,\n * callEndpoint: '/api/mcp-apps-call',\n * chat: { sendMessage: async (content) => void sendMessage(content) },\n * onLink: (url) => window.open(url, '_blank', 'noopener,noreferrer'),\n * })\n * // pass `bridge` to <MCPAppResource bridge={bridge} … />\n * ```\n *\n * The bridge is recreated only when `threadId`, `callEndpoint`, `fetchImpl`, or\n * the *presence* of `onLink` changes — passing a new inline `onLink`/`sendMessage`\n * each render does not churn it.\n */\nexport function useMcpAppBridge(options: UseMcpAppBridgeOptions): McpAppBridge {\n const { threadId, callEndpoint, chat, fetchImpl, onLink } = options\n\n // Latest-value refs so the bridge identity stays stable but its callbacks are\n // never stale (the bridge calls `.current` at invocation time, not creation).\n const chatRef = useRef(chat)\n chatRef.current = chat\n const onLinkRef = useRef(onLink)\n onLinkRef.current = onLink\n\n // Whether a link handler was supplied governs the bridge's link behavior\n // (forward vs. display-only warn), so it's part of the bridge's identity.\n const hasOnLink = onLink != null\n\n return useMemo(\n () =>\n createMcpAppBridge({\n threadId,\n callEndpoint,\n fetchImpl,\n chat: {\n sendMessage: (content, body) =>\n chatRef.current.sendMessage(content, body),\n },\n onLink: hasOnLink ? (url) => onLinkRef.current?.(url) : undefined,\n }),\n [threadId, callEndpoint, fetchImpl, hasOnLink],\n )\n}\n"],"names":[],"mappings":";;AA+BO,SAAS,gBAAgB,SAA+C;AAC7E,QAAM,EAAE,UAAU,cAAc,MAAM,WAAW,WAAW;AAI5D,QAAM,UAAU,OAAO,IAAI;AAC3B,UAAQ,UAAU;AAClB,QAAM,YAAY,OAAO,MAAM;AAC/B,YAAU,UAAU;AAIpB,QAAM,YAAY,UAAU;AAE5B,SAAO;AAAA,IACL,MACE,mBAAmB;AAAA,MACjB;AAAA,MACA;AAAA,MACA;AAAA,MACA,MAAM;AAAA,QACJ,aAAa,CAAC,SAAS,SACrB,QAAQ,QAAQ,YAAY,SAAS,IAAI;AAAA,MAAA;AAAA,MAE7C,QAAQ,YAAY,CAAC,QAAQ,UAAU,UAAU,GAAG,IAAI;AAAA,IAAA,CACzD;AAAA,IACH,CAAC,UAAU,cAAc,WAAW,SAAS;AAAA,EAAA;AAEjD;"}
|