@tanstack/ai-solid 0.16.2 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/types.d.ts +1 -1
- package/dist/use-chat.js +4 -2
- package/dist/use-chat.js.map +1 -1
- package/dist/use-generate-audio.d.ts +1 -5
- package/dist/use-generate-audio.js.map +1 -1
- package/dist/use-generate-image.d.ts +1 -5
- package/dist/use-generate-image.js.map +1 -1
- package/dist/use-generate-speech.d.ts +1 -5
- package/dist/use-generate-speech.js.map +1 -1
- package/dist/use-generate-video.d.ts +3 -7
- package/dist/use-generate-video.js +5 -4
- package/dist/use-generate-video.js.map +1 -1
- package/dist/use-generation.d.ts +3 -7
- package/dist/use-generation.js +7 -4
- package/dist/use-generation.js.map +1 -1
- package/dist/use-summarize.d.ts +1 -5
- package/dist/use-summarize.js.map +1 -1
- package/dist/use-transcription.d.ts +1 -5
- package/dist/use-transcription.js.map +1 -1
- package/package.json +6 -6
- package/src/index.ts +2 -0
- package/src/types.ts +0 -4
- package/src/use-chat.ts +13 -8
- package/src/use-generate-audio.ts +1 -5
- package/src/use-generate-image.ts +1 -5
- package/src/use-generate-speech.ts +1 -5
- package/src/use-generate-video.ts +13 -17
- package/src/use-generation.ts +21 -17
- package/src/use-summarize.ts +1 -5
- package/src/use-transcription.ts +1 -5
package/README.md
CHANGED
|
@@ -87,8 +87,7 @@ interface UseChatOptions {
|
|
|
87
87
|
|
|
88
88
|
// Configuration
|
|
89
89
|
initialMessages?: UIMessage[] // Starting messages
|
|
90
|
-
|
|
91
|
-
threadId?: string // AG-UI thread ID (auto-generated if omitted)
|
|
90
|
+
threadId?: string // The only chat identity. Required when persistence is on. Minted after mount if omitted.
|
|
92
91
|
forwardedProps?: Record<string, any> // Forwarded to AG-UI RunAgentInput.forwardedProps
|
|
93
92
|
/** @deprecated Use `forwardedProps` instead. */
|
|
94
93
|
body?: Record<string, any>
|
package/dist/index.d.ts
CHANGED
|
@@ -8,5 +8,5 @@ import { UseTranscriptionOptions, UseTranscriptionReturn, useTranscription } fro
|
|
|
8
8
|
import { UseSummarizeOptions, UseSummarizeReturn, useSummarize } from "./use-summarize.js";
|
|
9
9
|
import { UseGenerateVideoOptions, UseGenerateVideoReturn, useGenerateVideo } from "./use-generate-video.js";
|
|
10
10
|
import { UseAudioRecorderOptions, UseAudioRecorderReturn, useAudioRecorder } from "./use-audio-recorder.js";
|
|
11
|
-
import { AudioGenerateInput, ChatClientPersistence, ChatPersistedState, ChatPersistenceOption, ChatStorageAdapter, ConnectConnectionAdapter, ConnectionAdapter, FetchConnectionOptions, GenerationClientState, ImageGenerateInput, IndexedDBPersistenceOptions, InferChatMessages, RunAgentInputContext, SpeechGenerateInput, StorageUnavailableError, SubscribeConnectionAdapter, SummarizeGenerateInput, TranscriptionGenerateInput, VideoGenerateInput, VideoGenerateResult, VideoStatusInfo, WebStoragePersistenceOptions, XhrConnectionOptions, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, xhrHttpStream, xhrServerSentEvents } from "@tanstack/ai-client";
|
|
12
|
-
export { type AudioGenerateInput, type ChatClientPersistence, type ChatPersistedState, type ChatPersistenceOption, type ChatRequestBody, type ChatStorageAdapter, type ConnectConnectionAdapter, type ConnectionAdapter, type DeepPartial, type FetchConnectionOptions, type GenerationClientState, type ImageGenerateInput, type IndexedDBPersistenceOptions, type InferChatMessages, type QueueConfig, type QueueOption, type QueueStrategy, type QueuedMessage, type RunAgentInputContext, type SendMessageOptions, type SpeechGenerateInput, StorageUnavailableError, type SubscribeConnectionAdapter, type SummarizeGenerateInput, type TranscriptionGenerateInput, type UIMessage, type UseAudioRecorderOptions, type UseAudioRecorderReturn, type UseChatOptions, type UseChatReturn, type UseGenerateAudioOptions, type UseGenerateAudioReturn, type UseGenerateImageOptions, type UseGenerateImageReturn, type UseGenerateSpeechOptions, type UseGenerateSpeechReturn, type UseGenerateVideoOptions, type UseGenerateVideoReturn, type UseGenerationOptions, type UseGenerationReturn, type UseSummarizeOptions, type UseSummarizeReturn, type UseTranscriptionOptions, type UseTranscriptionReturn, type VideoGenerateInput, type VideoGenerateResult, type VideoStatusInfo, type WebStoragePersistenceOptions, type WhenBusy, type XhrConnectionOptions, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, useAudioRecorder, useChat, useGenerateAudio, useGenerateImage, useGenerateSpeech, useGenerateVideo, useGeneration, useSummarize, useTranscription, xhrHttpStream, xhrServerSentEvents };
|
|
11
|
+
import { AudioGenerateInput, ChatClientPersistence, ChatPersistedState, ChatPersistenceOption, ChatStorageAdapter, ConnectConnectionAdapter, ConnectionAdapter, FetchConnectionOptions, GenerationClientState, ImageGenerateInput, IndexedDBPersistenceOptions, InferChatMessages, RunAgentInputContext, SpeechGenerateInput, StorageUnavailableError, SubscribeConnectionAdapter, SummarizeGenerateInput, TranscriptionGenerateInput, VideoGenerateInput, VideoGenerateResult, VideoStatusInfo, WebSocketConnectionOptions, WebStoragePersistenceOptions, XhrConnectionOptions, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, webSocket, xhrHttpStream, xhrServerSentEvents } from "@tanstack/ai-client";
|
|
12
|
+
export { type AudioGenerateInput, type ChatClientPersistence, type ChatPersistedState, type ChatPersistenceOption, type ChatRequestBody, type ChatStorageAdapter, type ConnectConnectionAdapter, type ConnectionAdapter, type DeepPartial, type FetchConnectionOptions, type GenerationClientState, type ImageGenerateInput, type IndexedDBPersistenceOptions, type InferChatMessages, type QueueConfig, type QueueOption, type QueueStrategy, type QueuedMessage, type RunAgentInputContext, type SendMessageOptions, type SpeechGenerateInput, StorageUnavailableError, type SubscribeConnectionAdapter, type SummarizeGenerateInput, type TranscriptionGenerateInput, type UIMessage, type UseAudioRecorderOptions, type UseAudioRecorderReturn, type UseChatOptions, type UseChatReturn, type UseGenerateAudioOptions, type UseGenerateAudioReturn, type UseGenerateImageOptions, type UseGenerateImageReturn, type UseGenerateSpeechOptions, type UseGenerateSpeechReturn, type UseGenerateVideoOptions, type UseGenerateVideoReturn, type UseGenerationOptions, type UseGenerationReturn, type UseSummarizeOptions, type UseSummarizeReturn, type UseTranscriptionOptions, type UseTranscriptionReturn, type VideoGenerateInput, type VideoGenerateResult, type VideoStatusInfo, type WebSocketConnectionOptions, type WebStoragePersistenceOptions, type WhenBusy, type XhrConnectionOptions, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, useAudioRecorder, useChat, useGenerateAudio, useGenerateImage, useGenerateSpeech, useGenerateVideo, useGeneration, useSummarize, useTranscription, webSocket, xhrHttpStream, xhrServerSentEvents };
|
package/dist/index.js
CHANGED
|
@@ -7,6 +7,6 @@ import { useTranscription } from "./use-transcription.js";
|
|
|
7
7
|
import { useSummarize } from "./use-summarize.js";
|
|
8
8
|
import { useGenerateVideo } from "./use-generate-video.js";
|
|
9
9
|
import { useAudioRecorder } from "./use-audio-recorder.js";
|
|
10
|
-
import { StorageUnavailableError, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, xhrHttpStream, xhrServerSentEvents } from "@tanstack/ai-client";
|
|
10
|
+
import { StorageUnavailableError, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, webSocket, xhrHttpStream, xhrServerSentEvents } from "@tanstack/ai-client";
|
|
11
11
|
|
|
12
|
-
export { StorageUnavailableError, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, useAudioRecorder, useChat, useGenerateAudio, useGenerateImage, useGenerateSpeech, useGenerateVideo, useGeneration, useSummarize, useTranscription, xhrHttpStream, xhrServerSentEvents };
|
|
12
|
+
export { StorageUnavailableError, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, useAudioRecorder, useChat, useGenerateAudio, useGenerateImage, useGenerateSpeech, useGenerateVideo, useGeneration, useSummarize, useTranscription, webSocket, xhrHttpStream, xhrServerSentEvents };
|
package/dist/types.d.ts
CHANGED
|
@@ -31,7 +31,7 @@ type DeepPartial<T> = T extends ReadonlyArray<infer U> ? Array<DeepPartial<U>> :
|
|
|
31
31
|
* Note: Connection and body changes will recreate the ChatClient instance.
|
|
32
32
|
* To update these options, remount the component or use a key prop.
|
|
33
33
|
*/
|
|
34
|
-
type UseChatOptions<TTools extends ReadonlyArray<AnyClientTool> = any, TSchema extends SchemaInput | undefined = undefined, TContext = InferredClientContext<TTools>> = DistributedOmit<ChatClientOptions<TTools, TContext>, 'onMessagesChange' | 'onLoadingChange' | 'onErrorChange' | 'onStatusChange' | 'onSubscriptionChange' | 'onConnectionStatusChange' | 'onSessionGeneratingChange' | 'onQueueChange' | 'onResumeStateChange' | 'onRunIdChange' | 'context' | 'devtools'
|
|
34
|
+
type UseChatOptions<TTools extends ReadonlyArray<AnyClientTool> = any, TSchema extends SchemaInput | undefined = undefined, TContext = InferredClientContext<TTools>> = DistributedOmit<ChatClientOptions<TTools, TContext>, 'onMessagesChange' | 'onLoadingChange' | 'onErrorChange' | 'onStatusChange' | 'onSubscriptionChange' | 'onConnectionStatusChange' | 'onSessionGeneratingChange' | 'onQueueChange' | 'onResumeStateChange' | 'onRunIdChange' | 'context' | 'devtools'> & {
|
|
35
35
|
/** Display options for TanStack AI Devtools. */
|
|
36
36
|
devtools?: AIDevtoolsDisplayOptions;
|
|
37
37
|
live?: boolean;
|
package/dist/use-chat.js
CHANGED
|
@@ -32,10 +32,12 @@ function useChat(options = {}) {
|
|
|
32
32
|
devtoolsBridgeFactory: createChatDevtoolsBridge,
|
|
33
33
|
...options.connection ? { connection: options.connection } : { fetcher: options.fetcher },
|
|
34
34
|
...options.initialMessages !== void 0 && { initialMessages: options.initialMessages },
|
|
35
|
-
...options.
|
|
35
|
+
...typeof options.threadId === "string" && options.persistence ? {
|
|
36
|
+
persistence: options.persistence,
|
|
37
|
+
threadId: options.threadId
|
|
38
|
+
} : { ...options.threadId !== void 0 && { threadId: options.threadId } },
|
|
36
39
|
...options.initialResumeSnapshot !== void 0 && { initialResumeSnapshot: options.initialResumeSnapshot },
|
|
37
40
|
body: options.body,
|
|
38
|
-
...options.threadId !== void 0 && { threadId: options.threadId },
|
|
39
41
|
...options.forwardedProps !== void 0 && { forwardedProps: options.forwardedProps },
|
|
40
42
|
...options.context !== void 0 && { context: options.context },
|
|
41
43
|
devtools: {
|
package/dist/use-chat.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-chat.js","names":[],"sources":["../src/use-chat.ts"],"sourcesContent":["import {\n createEffect,\n createMemo,\n createSignal,\n createUniqueId,\n onCleanup,\n onMount,\n} from 'solid-js'\n\nimport { ChatClient } from '@tanstack/ai-client'\nimport { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport type {\n ChatClientState,\n ChatInterrupt,\n ChatInterruptState,\n ChatResumeState,\n ConnectionStatus,\n InferredClientContext,\n QueuedMessage,\n SendMessageOptions,\n StructuredOutputPart,\n} from '@tanstack/ai-client'\nimport type {\n AnyClientTool,\n InferSchemaType,\n ModelMessage,\n RunAgentResumeItem,\n SchemaInput,\n StreamChunk,\n} from '@tanstack/ai'\nimport type {\n DeepPartial,\n MultimodalContent,\n UIMessage,\n UseChatOptions,\n UseChatReturn,\n} from './types'\n\nconst EMPTY_INTERRUPTS = Object.freeze([])\nconst EMPTY_INTERRUPT_ERRORS = Object.freeze([])\n\nexport function useChat<\n const TTools extends ReadonlyArray<AnyClientTool> = any,\n TSchema extends SchemaInput | undefined = undefined,\n TContext = InferredClientContext<TTools>,\n>(\n options: UseChatOptions<TTools, TSchema, TContext> = {} as UseChatOptions<\n TTools,\n TSchema,\n TContext\n >,\n): UseChatReturn<TTools, TSchema> {\n // The hook's identity is its `threadId` — also the persistence key, so a\n // reload with the same `threadId` restores the same conversation. `hookId` is\n // only a stable fallback for client-recreation keying when no `threadId` is\n // given (an ephemeral chat), never a persistence key.\n const hookId = createUniqueId()\n const clientId = options.threadId ?? hookId\n\n const [messages, setMessages] = createSignal<Array<UIMessage<TTools>>>(\n options.initialMessages || [],\n )\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<ChatClientState>('ready')\n const [isSubscribed, setIsSubscribed] = createSignal(false)\n const [connectionStatus, setConnectionStatus] =\n createSignal<ConnectionStatus>('disconnected')\n const [sessionGenerating, setSessionGenerating] = createSignal(false)\n const [queue, setQueue] = createSignal<Array<QueuedMessage>>([])\n const [runId, setRunId] = createSignal<string | null>(null)\n const [interruptState, setInterruptState] = createSignal<\n ChatInterruptState<TTools>\n >({\n interrupts: EMPTY_INTERRUPTS,\n pendingInterrupts: EMPTY_INTERRUPTS,\n interruptErrors: EMPTY_INTERRUPT_ERRORS,\n resuming: false,\n })\n\n const syncResumeState = () => {\n setRunId(client().getCurrentRunId())\n setInterruptState(client().getInterruptState())\n }\n\n // Structured-output `partial` / `final` are derived from `messages` —\n // specifically from the structured-output part on the latest assistant\n // message (the one after the most recent user message). Per-turn parts\n // keep history coherent without a separate reset signal.\n type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>\n type Final = InferSchemaType<NonNullable<TSchema>>\n\n // Create ChatClient instance with callbacks to sync state.\n // Every user-provided callback is wrapped so the LATEST `options.xxx` value\n // is read at call time. Direct assignment would freeze the callback to the\n // reference we saw at creation; the wrapper lets reactive `options` or\n // in-place mutations propagate. When the user clears a callback (sets it to\n // undefined), `?.` no-ops.\n const client = createMemo(() => {\n // Build options with conditional spreads for fields whose source\n // type is `T | undefined` but the ChatClient target uses a strict\n // optional (`field?: T`) — `exactOptionalPropertyTypes` rejects\n // assigning `undefined` to those, so we omit the key when absent.\n const transport = options.connection\n ? { connection: options.connection }\n : { fetcher: options.fetcher }\n return new ChatClient<TTools, TContext>({\n devtoolsBridgeFactory: createChatDevtoolsBridge,\n ...transport,\n ...(options.initialMessages !== undefined && {\n initialMessages: options.initialMessages,\n }),\n ...(options.persistence !== undefined && {\n persistence: options.persistence,\n }),\n ...(options.initialResumeSnapshot !== undefined && {\n initialResumeSnapshot: options.initialResumeSnapshot,\n }),\n body: options.body,\n ...(options.threadId !== undefined && { threadId: options.threadId }),\n ...(options.forwardedProps !== undefined && {\n forwardedProps: options.forwardedProps,\n }),\n ...(options.context !== undefined && { context: options.context }),\n devtools: {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useChat',\n outputKind: options.outputSchema ? 'structured' : 'chat',\n },\n onResponse: (response) => options.onResponse?.(response),\n onChunk: (chunk: StreamChunk) => {\n options.onChunk?.(chunk)\n },\n onFinish: (message) => {\n options.onFinish?.(message)\n },\n onError: (err) => {\n options.onError?.(err)\n },\n tools: options.tools,\n onCustomEvent: (eventType, data, context) =>\n options.onCustomEvent?.(eventType, data, context),\n ...(options.streamProcessor !== undefined && {\n streamProcessor: options.streamProcessor,\n }),\n onMessagesChange: (newMessages: Array<UIMessage<TTools>>) => {\n setMessages(newMessages)\n },\n onLoadingChange: (newIsLoading: boolean) => {\n setIsLoading(newIsLoading)\n syncResumeState()\n },\n onStatusChange: (newStatus: ChatClientState) => {\n setStatus(newStatus)\n },\n onErrorChange: (newError: Error | undefined) => {\n setError(newError)\n },\n onSubscriptionChange: (nextIsSubscribed: boolean) => {\n setIsSubscribed(nextIsSubscribed)\n },\n onConnectionStatusChange: (nextStatus: ConnectionStatus) => {\n setConnectionStatus(nextStatus)\n },\n onSessionGeneratingChange: (isGenerating: boolean) => {\n setSessionGenerating(isGenerating)\n },\n ...(options.queue !== undefined && { queue: options.queue }),\n onQueueChange: (nextQueue: Array<QueuedMessage>) => {\n setQueue(nextQueue)\n },\n onRunIdChange: (nextRunId) => {\n setRunId(nextRunId)\n },\n onResumeStateChange: (_nextResumeState, nextPendingInterrupts) => {\n setInterruptState((current) => ({\n ...current,\n interrupts: nextPendingInterrupts,\n pendingInterrupts: nextPendingInterrupts,\n }))\n },\n onInterruptStateChange: (nextInterruptState) => {\n setInterruptState(nextInterruptState)\n options.onInterruptStateChange?.(nextInterruptState)\n },\n })\n // Only recreate when clientId changes\n // Connection and other options are captured at creation time\n }, [clientId])\n\n setMessages(client().getMessages())\n syncResumeState()\n\n // Sync body / forwardedProps changes to the client.\n // Both populate the same wire payload; `forwardedProps` is preferred\n // and `body` is deprecated but still supported.\n createEffect(() => {\n // Conditional spread: `updateOptions` declares strict-optional\n // fields and rejects explicit `undefined` under EOPT.\n client().updateOptions({\n ...(options.body !== undefined && { body: options.body }),\n ...(options.forwardedProps !== undefined && {\n forwardedProps: options.forwardedProps,\n }),\n context: options.context,\n ...(options.queue !== undefined && { queue: options.queue }),\n })\n })\n\n // Apply initial live mode immediately on hook creation.\n if (options.live) {\n client().subscribe()\n } else {\n client().unsubscribe()\n }\n\n createEffect(() => {\n if (options.live) {\n client().subscribe()\n } else {\n client().unsubscribe()\n }\n })\n\n onMount(() => {\n // START TAILING HERE, not in the constructor. A client is idle until a view\n // attaches it, so a client that gets built and thrown away never opens a\n // connection — an unreachable stream would hold one of the browser's ~6\n // connections per origin until the page reloaded.\n client().attach()\n client().mountDevtools()\n // Delivery-durability resume is transparent: the resumable SSE connection\n // adapter reattaches via the browser's native Last-Event-ID on reconnect.\n // We only seed interrupt (state) resume from the client here.\n syncResumeState()\n })\n\n // Cleanup on unmount: stop any in-flight requests.\n onCleanup(() => {\n // Release the connection first: `detach` is the counterpart of the `attach`\n // above, and it keeps the transcript and resume pointer so a later mount can\n // pick the run back up from the durable log.\n client().detach()\n if (options.live) {\n client().unsubscribe()\n } else {\n client().stop()\n }\n client().dispose()\n })\n\n // Callback options are read through `options.xxx` at call time, so reactive\n // or mutated options propagate without recreating the client.\n\n const sendMessage = async (\n content: string | MultimodalContent,\n sendOptions?: SendMessageOptions,\n ) => {\n try {\n await client().sendMessage(content, undefined, sendOptions)\n } finally {\n syncResumeState()\n }\n }\n\n const append = async (message: ModelMessage | UIMessage<TTools>) => {\n try {\n await client().append(message)\n } finally {\n syncResumeState()\n }\n }\n\n const reload = async () => {\n try {\n await client().reload()\n } finally {\n syncResumeState()\n }\n }\n\n const stop = () => {\n client().stop()\n }\n\n const clear = () => {\n client().clear()\n syncResumeState()\n }\n\n const setMessagesManually = (newMessages: Array<UIMessage<TTools>>) => {\n client().setMessagesManually(newMessages)\n }\n\n const addToolResult = async (result: {\n toolCallId: string\n tool: string\n output: any\n state?: 'output-available' | 'output-error'\n errorText?: string\n }) => {\n await client().addToolResult(result)\n }\n\n const addToolApprovalResponse = async (response: {\n id: string\n approved: boolean\n }) => {\n await client().addToolApprovalResponse(response)\n syncResumeState()\n }\n\n const cancelQueued = (id: string) => client().cancelQueued(id)\n\n const resumeInterrupts = async (\n resumeItems: Array<RunAgentResumeItem>,\n state?: ChatResumeState,\n ) => {\n const result = await client().resumeInterrupts(resumeItems, state)\n syncResumeState()\n return result\n }\n\n const resolveInterrupts = (\n resolution: boolean | ((interrupt: ChatInterrupt<TTools>) => undefined),\n ) => {\n if (typeof resolution === 'boolean') {\n client().resolveInterrupts(resolution)\n } else {\n client().resolveInterrupts(resolution)\n }\n }\n\n const cancelInterrupts = () => {\n client().cancelInterrupts()\n }\n\n const retryInterrupts = () => {\n client().retryInterrupts()\n }\n\n const resumeInterruptsUnsafe = (\n resumeItems: Array<RunAgentResumeItem>,\n state?: ChatResumeState,\n ) => client().resumeInterruptsUnsafe(resumeItems, state)\n\n const interrupts = () => interruptState().interrupts\n const pendingInterrupts = () => interruptState().pendingInterrupts\n const interruptErrors = () => interruptState().interruptErrors\n const resuming = () => interruptState().resuming\n\n // The \"active\" structured-output part is on the assistant message after\n // the latest user message. When no user message exists yet, return null\n // rather than scanning history — otherwise a stale `final` from\n // `initialMessages` would leak into the value on first render.\n const activeStructuredPart = createMemo<StructuredOutputPart | null>(() => {\n const list = messages()\n let lastUserIndex = -1\n for (let i = list.length - 1; i >= 0; i--) {\n if (list[i]?.role === 'user') {\n lastUserIndex = i\n break\n }\n }\n if (lastUserIndex === -1) return null\n for (let i = list.length - 1; i > lastUserIndex; i--) {\n const m = list[i]\n if (m?.role !== 'assistant') continue\n const part = m.parts.find(\n (p): p is StructuredOutputPart => p.type === 'structured-output',\n )\n if (part) return part\n }\n return null\n })\n\n const partial = createMemo<Partial>(() => {\n const part = activeStructuredPart()\n if (!part) return {} as Partial\n const v = part.partial ?? part.data\n return (v ?? {}) as Partial\n })\n\n const final = createMemo<Final | null>(() => {\n const part = activeStructuredPart()\n if (!part || part.status !== 'complete') return null\n return part.data as Final\n })\n\n // partial / final are runtime-tracked unconditionally; the conditional\n // return type hides them when no `outputSchema` is supplied.\n // oxlint-disable-next-line eslint-js/no-restricted-syntax -- primitive return shape diverges from generic UseChatReturn<TTools, TSchema>; TS can't structurally narrow the conditional partial/final fields\n return {\n messages,\n queue,\n sendMessage,\n append,\n reload,\n stop,\n isLoading,\n error,\n status,\n isSubscribed,\n connectionStatus,\n sessionGenerating,\n setMessages: setMessagesManually,\n clear,\n addToolResult,\n addToolApprovalResponse,\n cancelQueued,\n runId,\n interrupts,\n pendingInterrupts,\n interruptErrors,\n resuming,\n resolveInterrupts,\n cancelInterrupts,\n retryInterrupts,\n resumeInterruptsUnsafe,\n resumeInterrupts,\n partial,\n final,\n } as unknown as UseChatReturn<TTools, TSchema>\n}\n"],"mappings":";;;;;AAsCA,MAAM,mBAAmB,OAAO,OAAO,EAAE,CAAC;AAC1C,MAAM,yBAAyB,OAAO,OAAO,EAAE,CAAC;AAEhD,SAAgB,QAKd,UAAqD,EAAE,EAKvB;CAKhC,MAAM,SAAS,gBAAgB;CAC/B,MAAM,WAAW,QAAQ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AAK,QAClB,EAAE;IACf;EAwCA,OAtCY,iBAA+B;GAC3C,MAAM,OAAO,sBAAsB;AACnC,OAAI,CAAC,QAAQ,KAAK,WAAW,WAAY,QAAO;AAChD,UAAO,KAAK;IACZ;EAmCD"}
|
|
1
|
+
{"version":3,"file":"use-chat.js","names":[],"sources":["../src/use-chat.ts"],"sourcesContent":["import {\n createEffect,\n createMemo,\n createSignal,\n createUniqueId,\n onCleanup,\n onMount,\n} from 'solid-js'\n\nimport { ChatClient } from '@tanstack/ai-client'\nimport { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport type {\n ChatClientState,\n ChatInterrupt,\n ChatInterruptState,\n ChatResumeState,\n ConnectionStatus,\n InferredClientContext,\n QueuedMessage,\n SendMessageOptions,\n StructuredOutputPart,\n} from '@tanstack/ai-client'\nimport type {\n AnyClientTool,\n InferSchemaType,\n ModelMessage,\n RunAgentResumeItem,\n SchemaInput,\n StreamChunk,\n} from '@tanstack/ai'\nimport type {\n DeepPartial,\n MultimodalContent,\n UIMessage,\n UseChatOptions,\n UseChatReturn,\n} from './types'\n\nconst EMPTY_INTERRUPTS = Object.freeze([])\nconst EMPTY_INTERRUPT_ERRORS = Object.freeze([])\n\nexport function useChat<\n const TTools extends ReadonlyArray<AnyClientTool> = any,\n TSchema extends SchemaInput | undefined = undefined,\n TContext = InferredClientContext<TTools>,\n>(\n options: UseChatOptions<TTools, TSchema, TContext> = {} as UseChatOptions<\n TTools,\n TSchema,\n TContext\n >,\n): UseChatReturn<TTools, TSchema> {\n // The hook's identity is its `threadId`. Reload with the same `threadId`\n // restores the same conversation. `hookId` is only a recreation key when no\n // `threadId` is given. It is never sent on the wire.\n const hookId = createUniqueId()\n const clientId = options.threadId ?? hookId\n\n const [messages, setMessages] = createSignal<Array<UIMessage<TTools>>>(\n options.initialMessages || [],\n )\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<ChatClientState>('ready')\n const [isSubscribed, setIsSubscribed] = createSignal(false)\n const [connectionStatus, setConnectionStatus] =\n createSignal<ConnectionStatus>('disconnected')\n const [sessionGenerating, setSessionGenerating] = createSignal(false)\n const [queue, setQueue] = createSignal<Array<QueuedMessage>>([])\n const [runId, setRunId] = createSignal<string | null>(null)\n const [interruptState, setInterruptState] = createSignal<\n ChatInterruptState<TTools>\n >({\n interrupts: EMPTY_INTERRUPTS,\n pendingInterrupts: EMPTY_INTERRUPTS,\n interruptErrors: EMPTY_INTERRUPT_ERRORS,\n resuming: false,\n })\n\n const syncResumeState = () => {\n setRunId(client().getCurrentRunId())\n setInterruptState(client().getInterruptState())\n }\n\n // Structured-output `partial` / `final` are derived from `messages` —\n // specifically from the structured-output part on the latest assistant\n // message (the one after the most recent user message). Per-turn parts\n // keep history coherent without a separate reset signal.\n type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>\n type Final = InferSchemaType<NonNullable<TSchema>>\n\n // Create ChatClient instance with callbacks to sync state.\n // Every user-provided callback is wrapped so the LATEST `options.xxx` value\n // is read at call time. Direct assignment would freeze the callback to the\n // reference we saw at creation; the wrapper lets reactive `options` or\n // in-place mutations propagate. When the user clears a callback (sets it to\n // undefined), `?.` no-ops.\n const client = createMemo(() => {\n // Build options with conditional spreads for fields whose source\n // type is `T | undefined` but the ChatClient target uses a strict\n // optional (`field?: T`) — `exactOptionalPropertyTypes` rejects\n // assigning `undefined` to those, so we omit the key when absent.\n const transport = options.connection\n ? { connection: options.connection }\n : { fetcher: options.fetcher }\n return new ChatClient<TTools, TContext>({\n devtoolsBridgeFactory: createChatDevtoolsBridge,\n ...transport,\n ...(options.initialMessages !== undefined && {\n initialMessages: options.initialMessages,\n }),\n ...(typeof options.threadId === 'string' && options.persistence\n ? {\n persistence: options.persistence,\n threadId: options.threadId,\n }\n : {\n ...(options.threadId !== undefined && {\n threadId: options.threadId,\n }),\n }),\n ...(options.initialResumeSnapshot !== undefined && {\n initialResumeSnapshot: options.initialResumeSnapshot,\n }),\n body: options.body,\n ...(options.forwardedProps !== undefined && {\n forwardedProps: options.forwardedProps,\n }),\n ...(options.context !== undefined && { context: options.context }),\n devtools: {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useChat',\n outputKind: options.outputSchema ? 'structured' : 'chat',\n },\n onResponse: (response) => options.onResponse?.(response),\n onChunk: (chunk: StreamChunk) => {\n options.onChunk?.(chunk)\n },\n onFinish: (message) => {\n options.onFinish?.(message)\n },\n onError: (err) => {\n options.onError?.(err)\n },\n tools: options.tools,\n onCustomEvent: (eventType, data, context) =>\n options.onCustomEvent?.(eventType, data, context),\n ...(options.streamProcessor !== undefined && {\n streamProcessor: options.streamProcessor,\n }),\n onMessagesChange: (newMessages: Array<UIMessage<TTools>>) => {\n setMessages(newMessages)\n },\n onLoadingChange: (newIsLoading: boolean) => {\n setIsLoading(newIsLoading)\n syncResumeState()\n },\n onStatusChange: (newStatus: ChatClientState) => {\n setStatus(newStatus)\n },\n onErrorChange: (newError: Error | undefined) => {\n setError(newError)\n },\n onSubscriptionChange: (nextIsSubscribed: boolean) => {\n setIsSubscribed(nextIsSubscribed)\n },\n onConnectionStatusChange: (nextStatus: ConnectionStatus) => {\n setConnectionStatus(nextStatus)\n },\n onSessionGeneratingChange: (isGenerating: boolean) => {\n setSessionGenerating(isGenerating)\n },\n ...(options.queue !== undefined && { queue: options.queue }),\n onQueueChange: (nextQueue: Array<QueuedMessage>) => {\n setQueue(nextQueue)\n },\n onRunIdChange: (nextRunId) => {\n setRunId(nextRunId)\n },\n onResumeStateChange: (_nextResumeState, nextPendingInterrupts) => {\n setInterruptState((current) => ({\n ...current,\n interrupts: nextPendingInterrupts,\n pendingInterrupts: nextPendingInterrupts,\n }))\n },\n onInterruptStateChange: (nextInterruptState) => {\n setInterruptState(nextInterruptState)\n options.onInterruptStateChange?.(nextInterruptState)\n },\n })\n // Only recreate when clientId changes\n // Connection and other options are captured at creation time\n }, [clientId])\n\n setMessages(client().getMessages())\n syncResumeState()\n\n // Sync body / forwardedProps changes to the client.\n // Both populate the same wire payload; `forwardedProps` is preferred\n // and `body` is deprecated but still supported.\n createEffect(() => {\n // Conditional spread: `updateOptions` declares strict-optional\n // fields and rejects explicit `undefined` under EOPT.\n client().updateOptions({\n ...(options.body !== undefined && { body: options.body }),\n ...(options.forwardedProps !== undefined && {\n forwardedProps: options.forwardedProps,\n }),\n context: options.context,\n ...(options.queue !== undefined && { queue: options.queue }),\n })\n })\n\n // Apply initial live mode immediately on hook creation.\n if (options.live) {\n client().subscribe()\n } else {\n client().unsubscribe()\n }\n\n createEffect(() => {\n if (options.live) {\n client().subscribe()\n } else {\n client().unsubscribe()\n }\n })\n\n onMount(() => {\n // START TAILING HERE, not in the constructor. A client is idle until a view\n // attaches it, so a client that gets built and thrown away never opens a\n // connection — an unreachable stream would hold one of the browser's ~6\n // connections per origin until the page reloaded.\n client().attach()\n client().mountDevtools()\n // Delivery-durability resume is transparent: the resumable SSE connection\n // adapter reattaches via the browser's native Last-Event-ID on reconnect.\n // We only seed interrupt (state) resume from the client here.\n syncResumeState()\n })\n\n // Cleanup on unmount: stop any in-flight requests.\n onCleanup(() => {\n // Release the connection first: `detach` is the counterpart of the `attach`\n // above, and it keeps the transcript and resume pointer so a later mount can\n // pick the run back up from the durable log.\n client().detach()\n if (options.live) {\n client().unsubscribe()\n } else {\n client().stop()\n }\n client().dispose()\n })\n\n // Callback options are read through `options.xxx` at call time, so reactive\n // or mutated options propagate without recreating the client.\n\n const sendMessage = async (\n content: string | MultimodalContent,\n sendOptions?: SendMessageOptions,\n ) => {\n try {\n await client().sendMessage(content, undefined, sendOptions)\n } finally {\n syncResumeState()\n }\n }\n\n const append = async (message: ModelMessage | UIMessage<TTools>) => {\n try {\n await client().append(message)\n } finally {\n syncResumeState()\n }\n }\n\n const reload = async () => {\n try {\n await client().reload()\n } finally {\n syncResumeState()\n }\n }\n\n const stop = () => {\n client().stop()\n }\n\n const clear = () => {\n client().clear()\n syncResumeState()\n }\n\n const setMessagesManually = (newMessages: Array<UIMessage<TTools>>) => {\n client().setMessagesManually(newMessages)\n }\n\n const addToolResult = async (result: {\n toolCallId: string\n tool: string\n output: any\n state?: 'output-available' | 'output-error'\n errorText?: string\n }) => {\n await client().addToolResult(result)\n }\n\n const addToolApprovalResponse = async (response: {\n id: string\n approved: boolean\n }) => {\n await client().addToolApprovalResponse(response)\n syncResumeState()\n }\n\n const cancelQueued = (id: string) => client().cancelQueued(id)\n\n const resumeInterrupts = async (\n resumeItems: Array<RunAgentResumeItem>,\n state?: ChatResumeState,\n ) => {\n const result = await client().resumeInterrupts(resumeItems, state)\n syncResumeState()\n return result\n }\n\n const resolveInterrupts = (\n resolution: boolean | ((interrupt: ChatInterrupt<TTools>) => undefined),\n ) => {\n if (typeof resolution === 'boolean') {\n client().resolveInterrupts(resolution)\n } else {\n client().resolveInterrupts(resolution)\n }\n }\n\n const cancelInterrupts = () => {\n client().cancelInterrupts()\n }\n\n const retryInterrupts = () => {\n client().retryInterrupts()\n }\n\n const resumeInterruptsUnsafe = (\n resumeItems: Array<RunAgentResumeItem>,\n state?: ChatResumeState,\n ) => client().resumeInterruptsUnsafe(resumeItems, state)\n\n const interrupts = () => interruptState().interrupts\n const pendingInterrupts = () => interruptState().pendingInterrupts\n const interruptErrors = () => interruptState().interruptErrors\n const resuming = () => interruptState().resuming\n\n // The \"active\" structured-output part is on the assistant message after\n // the latest user message. When no user message exists yet, return null\n // rather than scanning history — otherwise a stale `final` from\n // `initialMessages` would leak into the value on first render.\n const activeStructuredPart = createMemo<StructuredOutputPart | null>(() => {\n const list = messages()\n let lastUserIndex = -1\n for (let i = list.length - 1; i >= 0; i--) {\n if (list[i]?.role === 'user') {\n lastUserIndex = i\n break\n }\n }\n if (lastUserIndex === -1) return null\n for (let i = list.length - 1; i > lastUserIndex; i--) {\n const m = list[i]\n if (m?.role !== 'assistant') continue\n const part = m.parts.find(\n (p): p is StructuredOutputPart => p.type === 'structured-output',\n )\n if (part) return part\n }\n return null\n })\n\n const partial = createMemo<Partial>(() => {\n const part = activeStructuredPart()\n if (!part) return {} as Partial\n const v = part.partial ?? part.data\n return (v ?? {}) as Partial\n })\n\n const final = createMemo<Final | null>(() => {\n const part = activeStructuredPart()\n if (!part || part.status !== 'complete') return null\n return part.data as Final\n })\n\n // partial / final are runtime-tracked unconditionally; the conditional\n // return type hides them when no `outputSchema` is supplied.\n // oxlint-disable-next-line eslint-js/no-restricted-syntax -- primitive return shape diverges from generic UseChatReturn<TTools, TSchema>; TS can't structurally narrow the conditional partial/final fields\n return {\n messages,\n queue,\n sendMessage,\n append,\n reload,\n stop,\n isLoading,\n error,\n status,\n isSubscribed,\n connectionStatus,\n sessionGenerating,\n setMessages: setMessagesManually,\n clear,\n addToolResult,\n addToolApprovalResponse,\n cancelQueued,\n runId,\n interrupts,\n pendingInterrupts,\n interruptErrors,\n resuming,\n resolveInterrupts,\n cancelInterrupts,\n retryInterrupts,\n resumeInterruptsUnsafe,\n resumeInterrupts,\n partial,\n final,\n } as unknown as UseChatReturn<TTools, TSchema>\n}\n"],"mappings":";;;;;AAsCA,MAAM,mBAAmB,OAAO,OAAO,EAAE,CAAC;AAC1C,MAAM,yBAAyB,OAAO,OAAO,EAAE,CAAC;AAEhD,SAAgB,QAKd,UAAqD,EAAE,EAKvB;CAIhC,MAAM,SAAS,gBAAgB;CAC/B,MAAM,WAAW,QAAQ,YAAY;CAErC,MAAM,CAAC,UAAU,eAAe,aAC9B,QAAQ,mBAAmB,EAAE,CAC9B;CACD,MAAM,CAAC,WAAW,gBAAgB,aAAa,MAAM;CACrD,MAAM,CAAC,OAAO,YAAY,aAAgC,OAAU;CACpE,MAAM,CAAC,QAAQ,aAAa,aAA8B,QAAQ;CAClE,MAAM,CAAC,cAAc,mBAAmB,aAAa,MAAM;CAC3D,MAAM,CAAC,kBAAkB,uBACvB,aAA+B,eAAe;CAChD,MAAM,CAAC,mBAAmB,wBAAwB,aAAa,MAAM;CACrE,MAAM,CAAC,OAAO,YAAY,aAAmC,EAAE,C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A,UACG,QAAQ,CAAC,uBAAuB,aAAa,MAAM;CAExD,MAAM,mBAAmB,gBAAgB,CAAC;CAC1C,MAAM,0BAA0B,gBAAgB,CAAC;CACjD,MAAM,wBAAwB,gBAAgB,CAAC;CAC/C,MAAM,iBAAiB,gBAAgB,CAAC;CAMxC,MAAM,uBAAuB,iBAA8C;EACzE,MAAM,OAAO,UAAU;EACvB,IAAI,gBAAgB;AACpB,OAAK,IAAI,IAAI,KAAK,SAAS,GAAG,KAAK,GAAG,IACpC,KAAI,KAAK,IAAI,SAAS,QAAQ;AAC5B,mBAAgB;AAChB;;AAGJ,MAAI,kBAAkB,GAAI,QAAO;AACjC,OAAK,IAAI,IAAI,KAAK,SAAS,GAAG,IAAI,eAAe,KAAK;GACpD,MAAM,IAAI,KAAK;AACf,OAAI,GAAG,SAAS,YAAa;GAC7B,MAAM,OAAO,EAAE,MAAM,MAClB,MAAiC,EAAE,SAAS,oBAC9C;AACD,OAAI,KAAM,QAAO;;AAEnB,SAAO;GACP;AAkBF,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,aAAa;EACb;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SA5Cc,iBAA0B;GACxC,MAAM,OAAO,sBAAsB;AACnC,OAAI,CAAC,KAAM,QAAO,EAAE;AAEpB,UADU,KAAK,WAAW,KAAK,QAClB,EAAE;IACf;EAwCA,OAtCY,iBAA+B;GAC3C,MAAM,OAAO,sBAAsB;AACnC,OAAI,CAAC,QAAQ,KAAK,WAAW,WAAY,QAAO;AAChD,UAAO,KAAK;IACZ;EAmCD"}
|
|
@@ -15,10 +15,6 @@ interface UseGenerateAudioOptions<TOutput = AudioGenerationResult> extends Pick<
|
|
|
15
15
|
connection?: ConnectConnectionAdapter;
|
|
16
16
|
/** Direct async function for audio generation */
|
|
17
17
|
fetcher?: GenerationFetcher<AudioGenerateInput, AudioGenerationResult>;
|
|
18
|
-
/**
|
|
19
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
20
|
-
*/
|
|
21
|
-
id?: string;
|
|
22
18
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
23
19
|
body?: Record<string, any>;
|
|
24
20
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -79,7 +75,7 @@ interface UseGenerateAudioReturn<TOutput = AudioGenerationResult> extends Omit<U
|
|
|
79
75
|
* }
|
|
80
76
|
* ```
|
|
81
77
|
*/
|
|
82
|
-
declare function useGenerateAudio<TTransformed = void>(options: Omit<UseGenerateAudioOptions, 'onResult' | 'persistence' | 'threadId'
|
|
78
|
+
declare function useGenerateAudio<TTransformed = void>(options: Omit<UseGenerateAudioOptions, 'onResult' | 'persistence' | 'threadId'> & {
|
|
83
79
|
onResult?: (result: AudioGenerationResult) => TTransformed;
|
|
84
80
|
} & GenerationPersistenceOptions): UseGenerateAudioReturn<InferGenerationOutputFromReturn<AudioGenerationResult, TTransformed>>;
|
|
85
81
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-audio.js","names":[],"sources":["../src/use-generate-audio.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructAudioResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { AudioGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n AudioGenerateInput,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateAudio hook.\n *\n * @template TOutput - The transformed output type (defaults to AudioGenerationResult)\n */\nexport interface UseGenerateAudioOptions<\n TOutput = AudioGenerationResult,\n> extends Pick<\n UseGenerationOptions<AudioGenerateInput, AudioGenerationResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\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
|
|
1
|
+
{"version":3,"file":"use-generate-audio.js","names":[],"sources":["../src/use-generate-audio.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructAudioResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { AudioGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n AudioGenerateInput,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateAudio hook.\n *\n * @template TOutput - The transformed output type (defaults to AudioGenerationResult)\n */\nexport interface UseGenerateAudioOptions<\n TOutput = AudioGenerationResult,\n> extends Pick<\n UseGenerationOptions<AudioGenerateInput, AudioGenerationResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\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 /** 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 transformed output type (defaults to AudioGenerationResult)\n */\nexport interface UseGenerateAudioReturn<\n TOutput = AudioGenerationResult,\n> extends Omit<UseGenerationReturn<TOutput>, 'generate'> {\n /** Trigger audio generation */\n generate: (input: AudioGenerateInput) => Promise<void>\n /** The generation result containing audio, or null */\n result: Accessor<TOutput | null>\n /** Whether generation is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<GenerationClientState>\n}\n\n/**\n * Solid hook for generating audio (music, sound effects) using AI models.\n *\n * @example\n * ```tsx\n * import { useGenerateAudio } from '@tanstack/ai-solid'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function AudioGenerator() {\n * const { generate, result, isLoading } = 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 * {result()?.audio.url && <audio src={result()!.audio.url} controls />}\n * </div>\n * )\n * }\n * ```\n */\nexport function useGenerateAudio<TTransformed = void>(\n options: Omit<\n UseGenerateAudioOptions,\n 'onResult' | 'persistence' | 'threadId'\n > & {\n onResult?: (result: AudioGenerationResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerateAudioReturn<\n InferGenerationOutputFromReturn<AudioGenerationResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useGenerateAudio',\n outputKind: 'audio' as const,\n }\n const generation = useGeneration<\n AudioGenerateInput,\n AudioGenerationResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructAudioResult,\n })\n\n return generation\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiGA,SAAgB,iBACd,SAQA;CACA,MAAM,WAAW;EACf,GAAG,QAAQ;EACX,WAAW;EACX,UAAU;EACV,YAAY;EACb;AAWD,QAVmB,cAIjB;EACA,GAAG;EACH;EACA,mBAAmB;EACpB,CAAC"}
|
|
@@ -15,10 +15,6 @@ interface UseGenerateImageOptions<TOutput = ImageGenerationResult> extends Pick<
|
|
|
15
15
|
connection?: ConnectConnectionAdapter;
|
|
16
16
|
/** Direct async function for image generation */
|
|
17
17
|
fetcher?: GenerationFetcher<ImageGenerateInput, ImageGenerationResult>;
|
|
18
|
-
/**
|
|
19
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
20
|
-
*/
|
|
21
|
-
id?: string;
|
|
22
18
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
23
19
|
body?: Record<string, any>;
|
|
24
20
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -87,7 +83,7 @@ interface UseGenerateImageReturn<TOutput = ImageGenerationResult> extends Omit<U
|
|
|
87
83
|
* }
|
|
88
84
|
* ```
|
|
89
85
|
*/
|
|
90
|
-
declare function useGenerateImage<TTransformed = void>(options: Omit<UseGenerateImageOptions, 'onResult' | 'persistence' | 'threadId'
|
|
86
|
+
declare function useGenerateImage<TTransformed = void>(options: Omit<UseGenerateImageOptions, 'onResult' | 'persistence' | 'threadId'> & {
|
|
91
87
|
onResult?: (result: ImageGenerationResult) => TTransformed;
|
|
92
88
|
} & GenerationPersistenceOptions): UseGenerateImageReturn<InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>>;
|
|
93
89
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-image.js","names":[],"sources":["../src/use-generate-image.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructImageResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { ImageGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n ImageGenerateInput,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateImage hook.\n *\n * @template TOutput - The transformed output type (defaults to ImageGenerationResult)\n */\nexport interface UseGenerateImageOptions<\n TOutput = ImageGenerationResult,\n> extends Pick<\n UseGenerationOptions<ImageGenerateInput, ImageGenerationResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\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
|
|
1
|
+
{"version":3,"file":"use-generate-image.js","names":[],"sources":["../src/use-generate-image.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructImageResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { ImageGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n ImageGenerateInput,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateImage hook.\n *\n * @template TOutput - The transformed output type (defaults to ImageGenerationResult)\n */\nexport interface UseGenerateImageOptions<\n TOutput = ImageGenerationResult,\n> extends Pick<\n UseGenerationOptions<ImageGenerateInput, ImageGenerationResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\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 /** 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 transformed output type (defaults to ImageGenerationResult)\n */\nexport interface UseGenerateImageReturn<\n TOutput = ImageGenerationResult,\n> extends Omit<UseGenerationReturn<TOutput>, 'generate'> {\n /** Trigger image generation */\n generate: (input: ImageGenerateInput) => Promise<void>\n /** The generation result containing images, or null */\n result: Accessor<TOutput | null>\n /** Whether generation is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<GenerationClientState>\n}\n\n/**\n * Solid 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-solid'\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 src={img.url || `data:image/png;base64,${img.b64Json}`} />\n * ))}\n * </div>\n * )\n * }\n * ```\n */\nexport function useGenerateImage<TTransformed = void>(\n options: Omit<\n UseGenerateImageOptions,\n 'onResult' | 'persistence' | 'threadId'\n > & {\n onResult?: (result: ImageGenerationResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerateImageReturn<\n InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useGenerateImage',\n outputKind: 'image' as const,\n }\n const generation = useGeneration<\n ImageGenerateInput,\n ImageGenerationResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructImageResult,\n })\n\n return generation\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyGA,SAAgB,iBACd,SAQA;CACA,MAAM,WAAW;EACf,GAAG,QAAQ;EACX,WAAW;EACX,UAAU;EACV,YAAY;EACb;AAWD,QAVmB,cAIjB;EACA,GAAG;EACH;EACA,mBAAmB;EACpB,CAAC"}
|
|
@@ -15,10 +15,6 @@ interface UseGenerateSpeechOptions<TOutput = TTSResult> extends Pick<UseGenerati
|
|
|
15
15
|
connection?: ConnectConnectionAdapter;
|
|
16
16
|
/** Direct async function for speech generation */
|
|
17
17
|
fetcher?: GenerationFetcher<SpeechGenerateInput, TTSResult>;
|
|
18
|
-
/**
|
|
19
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
20
|
-
*/
|
|
21
|
-
id?: string;
|
|
22
18
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
23
19
|
body?: Record<string, any>;
|
|
24
20
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -81,7 +77,7 @@ interface UseGenerateSpeechReturn<TOutput = TTSResult> extends Omit<UseGeneratio
|
|
|
81
77
|
* }
|
|
82
78
|
* ```
|
|
83
79
|
*/
|
|
84
|
-
declare function useGenerateSpeech<TTransformed = void>(options: Omit<UseGenerateSpeechOptions, 'onResult' | 'persistence' | 'threadId'
|
|
80
|
+
declare function useGenerateSpeech<TTransformed = void>(options: Omit<UseGenerateSpeechOptions, 'onResult' | 'persistence' | 'threadId'> & {
|
|
85
81
|
onResult?: (result: TTSResult) => TTransformed;
|
|
86
82
|
} & GenerationPersistenceOptions): UseGenerateSpeechReturn<InferGenerationOutputFromReturn<TTSResult, TTransformed>>;
|
|
87
83
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-speech.js","names":[],"sources":["../src/use-generate-speech.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructSpeechResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { StreamChunk, TTSResult } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n SpeechGenerateInput,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateSpeech hook.\n *\n * @template TOutput - The transformed output type (defaults to TTSResult)\n */\nexport interface UseGenerateSpeechOptions<TOutput = TTSResult> extends Pick<\n UseGenerationOptions<SpeechGenerateInput, TTSResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\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
|
|
1
|
+
{"version":3,"file":"use-generate-speech.js","names":[],"sources":["../src/use-generate-speech.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructSpeechResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { StreamChunk, TTSResult } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n SpeechGenerateInput,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateSpeech hook.\n *\n * @template TOutput - The transformed output type (defaults to TTSResult)\n */\nexport interface UseGenerateSpeechOptions<TOutput = TTSResult> extends Pick<\n UseGenerationOptions<SpeechGenerateInput, TTSResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\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 /** 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 transformed output type (defaults to TTSResult)\n */\nexport interface UseGenerateSpeechReturn<TOutput = TTSResult> extends Omit<\n UseGenerationReturn<TOutput>,\n 'generate'\n> {\n /** Trigger speech generation */\n generate: (input: SpeechGenerateInput) => Promise<void>\n /** The TTS result containing audio data, or null */\n result: Accessor<TOutput | null>\n /** Whether generation is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<GenerationClientState>\n}\n\n/**\n * Solid hook for generating speech (text-to-speech) using AI models.\n *\n * @example\n * ```tsx\n * import { useGenerateSpeech } from '@tanstack/ai-solid'\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<\n UseGenerateSpeechOptions,\n 'onResult' | 'persistence' | 'threadId'\n > & {\n onResult?: (result: TTSResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerateSpeechReturn<\n InferGenerationOutputFromReturn<TTSResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useGenerateSpeech',\n outputKind: 'audio' as const,\n }\n const generation = useGeneration<\n SpeechGenerateInput,\n TTSResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructSpeechResult,\n })\n\n return generation\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkGA,SAAgB,kBACd,SAQA;CACA,MAAM,WAAW;EACf,GAAG,QAAQ;EACX,WAAW;EACX,UAAU;EACV,YAAY;EACb;AAWD,QAVmB,cAIjB;EACA,GAAG;EACH;EACA,mBAAmB;EACpB,CAAC"}
|
|
@@ -14,10 +14,6 @@ interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {
|
|
|
14
14
|
connection?: ConnectConnectionAdapter;
|
|
15
15
|
/** Direct async function that returns a completed video result */
|
|
16
16
|
fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>;
|
|
17
|
-
/**
|
|
18
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
19
|
-
*/
|
|
20
|
-
id?: string;
|
|
21
17
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
22
18
|
body?: Record<string, any>;
|
|
23
19
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -41,8 +37,8 @@ interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {
|
|
|
41
37
|
* id on the wire, which the protocol requires.
|
|
42
38
|
*
|
|
43
39
|
* **Required whenever `persistence` is set** — an app that cannot name the
|
|
44
|
-
* scope has nothing to restore to. Optional for ephemeral generations
|
|
45
|
-
*
|
|
40
|
+
* scope has nothing to restore to. Optional for ephemeral generations. If
|
|
41
|
+
* omitted, the client mints a wire id after mount.
|
|
46
42
|
*/
|
|
47
43
|
threadId?: string;
|
|
48
44
|
/**
|
|
@@ -141,7 +137,7 @@ interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {
|
|
|
141
137
|
* }
|
|
142
138
|
* ```
|
|
143
139
|
*/
|
|
144
|
-
declare function useGenerateVideo<TTransformed = void>(options: Omit<UseGenerateVideoOptions, 'onResult' | 'persistence' | 'threadId'
|
|
140
|
+
declare function useGenerateVideo<TTransformed = void>(options: Omit<UseGenerateVideoOptions, 'onResult' | 'persistence' | 'threadId'> & {
|
|
145
141
|
onResult?: (result: VideoGenerateResult) => TTransformed;
|
|
146
142
|
} & GenerationPersistenceOptions): UseGenerateVideoReturn<InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>>;
|
|
147
143
|
//#endregion
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createEffect, createSignal,
|
|
1
|
+
import { createEffect, createSignal, onCleanup, onMount, untrack } from "solid-js";
|
|
2
2
|
import { VideoGenerationClient } from "@tanstack/ai-client";
|
|
3
3
|
import { createVideoDevtoolsBridge } from "@tanstack/ai-client/devtools";
|
|
4
4
|
|
|
@@ -35,7 +35,6 @@ import { createVideoDevtoolsBridge } from "@tanstack/ai-client/devtools";
|
|
|
35
35
|
* ```
|
|
36
36
|
*/
|
|
37
37
|
function useGenerateVideo(options) {
|
|
38
|
-
const hookId = createUniqueId();
|
|
39
38
|
const [result, setResult] = createSignal(null);
|
|
40
39
|
const [jobId, setJobId] = createSignal(null);
|
|
41
40
|
const [videoStatus, setVideoStatus] = createSignal(null);
|
|
@@ -47,8 +46,10 @@ function useGenerateVideo(options) {
|
|
|
47
46
|
const client = untrack(() => {
|
|
48
47
|
const baseOptions = {
|
|
49
48
|
body: options.body,
|
|
50
|
-
...options.threadId
|
|
51
|
-
|
|
49
|
+
...typeof options.threadId === "string" && options.persistence ? {
|
|
50
|
+
persistence: options.persistence,
|
|
51
|
+
threadId: options.threadId
|
|
52
|
+
} : { ...options.threadId !== void 0 && { threadId: options.threadId } },
|
|
52
53
|
...options.hydrateGeneration !== void 0 && { hydrateGeneration: options.hydrateGeneration },
|
|
53
54
|
...options.joinRun !== void 0 && { joinRun: options.joinRun },
|
|
54
55
|
devtoolsBridgeFactory: createVideoDevtoolsBridge,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-video.js","names":[],"sources":["../src/use-generate-video.ts"],"sourcesContent":["import { VideoGenerationClient } from '@tanstack/ai-client'\nimport { createVideoDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n createEffect,\n createSignal,\n createUniqueId,\n onCleanup,\n onMount,\n untrack,\n} from 'solid-js'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n VideoGenerateInput,\n VideoGenerateResult,\n VideoStatusInfo,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateVideo hook.\n *\n * @template TOutput - The transformed output type (defaults to VideoGenerateResult)\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 /**\n * @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).\n */\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 * How this generation persists across reloads.\n * - Omit / `false`: ephemeral, in-memory only.\n * - `true`: server-driven — on mount the client hydrates the last generation\n * for its `threadId` from the server (needs a connection with a\n * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.\n */\n persistence?: boolean\n /**\n * The **scope** this generation belongs to: a stable, app-chosen name for the\n * slot successive runs fill — not a link to a chat conversation.\n *\n * The hook starts empty and produces many runs over its life; each gets its\n * own `runId`, but all belong to one scope. Persistence keys on this, so\n * derive it from your own domain and keep it identical across reloads (e.g.\n * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread\n * id on the wire, which the protocol requires.\n *\n * **Required whenever `persistence` is set** — an app that cannot name the\n * scope has nothing to restore to. Optional for ephemeral generations, where\n * it falls back to `id` purely to satisfy the wire.\n */\n threadId?: string\n /**\n * Server-driven hydration handler for `persistence: true` when the\n * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /\n * `rpcStream()` adapter built without handlers) — typically a one-line\n * server-function call. The connection's own handler takes precedence.\n */\n hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']\n /**\n * Re-attach handler that replays a run still generating to completion on\n * mount, when the connection doesn't carry one. Without it, a restored\n * `running` snapshot surfaces as an (interrupted) error. The connection's\n * own handler takes precedence.\n */\n joinRun?: ConnectConnectionAdapter['joinRun']\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 transformed output type (defaults to VideoGenerateResult)\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: Accessor<TOutput | null>\n /** The current job ID, or null */\n jobId: Accessor<string | null>\n /** Current video generation status info, or null */\n videoStatus: Accessor<VideoStatusInfo | null>\n /** Whether generation/polling is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<GenerationClientState>\n /** Abort the current generation/polling */\n stop: () => void\n /** Clear all state and return to idle */\n reset: () => void\n /**\n * The id of the generation job currently running, or `null` when nothing is in\n * flight. Each call to `generate` is one job with its own id. Pass it to your\n * own endpoint to cancel or poll the provider job — `stop()` only aborts the\n * local stream, it does not stop work already running on the provider.\n */\n runId: Accessor<string | null>\n}\n\n/**\n * Solid 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-solid'\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<\n UseGenerateVideoOptions,\n 'onResult' | 'persistence' | 'threadId' | 'id'\n > & {\n onResult?: (result: VideoGenerateResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerateVideoReturn<\n InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>\n> {\n type TOutput = InferGenerationOutputFromReturn<\n VideoGenerateResult,\n TTransformed\n >\n const hookId = createUniqueId()\n\n const [result, setResult] = createSignal<TOutput | null>(null)\n const [jobId, setJobId] = createSignal<string | null>(null)\n const [videoStatus, setVideoStatus] = createSignal<VideoStatusInfo | null>(\n null,\n )\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<GenerationClientState>('idle')\n const [runId, setRunId] = createSignal<string | null>(null)\n let disposed = false\n\n // Built once. `untrack` keeps the option reads below from subscribing\n // construction to `options.persistence` / `options.devtools` /\n // `options.body`: a re-run would build a second client\n // and orphan the first (only the live one is disposed on cleanup). Later\n // `options.body` changes are pushed through `updateOptions` instead.\n const client = untrack((): VideoGenerationClient<TOutput> => {\n // Conditional spread on `body`: VideoGenerationClientOptions.body\n // is a strict optional; EOPT forbids passing `T | undefined`.\n const baseOptions = {\n body: options.body,\n // Identity: pass `threadId` alone when set (never also pass deprecated `id`).\n ...(options.threadId !== undefined\n ? { threadId: options.threadId }\n : { id: options.id ?? hookId }),\n ...(options.persistence !== undefined && {\n persistence: options.persistence,\n }),\n ...(options.hydrateGeneration !== undefined && {\n hydrateGeneration: options.hydrateGeneration,\n }),\n ...(options.joinRun !== undefined && { joinRun: options.joinRun }),\n devtoolsBridgeFactory: createVideoDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'solid',\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) => options.onResult?.(r)) as (\n result: VideoGenerateResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n if (!disposed) options.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n if (!disposed) options.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n if (!disposed) options.onChunk?.(c)\n },\n onJobCreated: (id: string) => {\n if (!disposed) options.onJobCreated?.(id)\n },\n onStatusUpdate: (s: VideoStatusInfo) => {\n if (!disposed) options.onStatusUpdate?.(s)\n },\n onResultChange: (r: TOutput | null) => {\n if (!disposed) setResult(() => r)\n },\n onLoadingChange: (l: boolean) => {\n if (!disposed) setIsLoading(l)\n },\n onErrorChange: (e: Error | undefined) => {\n if (!disposed) setError(e)\n },\n onStatusChange: (s: GenerationClientState) => {\n if (!disposed) setStatus(s)\n },\n onJobIdChange: (id: string | null) => {\n if (!disposed) setJobId(id)\n },\n onVideoStatusChange: (s: VideoStatusInfo | null) => {\n if (!disposed) setVideoStatus(s)\n },\n onResumeStateChange: (rs: { runId: string } | null) => {\n if (!disposed) setRunId(rs?.runId ?? null)\n },\n }\n\n if (options.connection) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n connection: options.connection,\n })\n }\n\n if (options.fetcher) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n fetcher: options.fetcher,\n })\n }\n\n throw new Error(\n 'useGenerateVideo requires either a connection or fetcher option',\n )\n })\n\n // Sync body changes without recreating client\n createEffect(() => {\n const currentBody = options.body\n client.updateOptions({\n ...(currentBody !== undefined && { body: currentBody }),\n })\n })\n\n // Mount devtools only. Generation runs are never auto-started on mount — a\n // persisted snapshot is hydrated for display, never replayed.\n onMount(() => {\n client.mountDevtools()\n })\n\n // Cleanup on unmount: stop any in-flight requests and unregister devtools\n onCleanup(() => {\n disposed = true\n client.dispose()\n })\n\n const generate = async (input: VideoGenerateInput) => {\n await client.generate(input)\n }\n\n const stop = () => {\n client.stop()\n }\n\n const reset = () => {\n client.reset()\n }\n\n return {\n generate,\n result,\n jobId,\n videoStatus,\n isLoading,\n error,\n status,\n stop,\n reset,\n runId,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsKA,SAAgB,iBACd,SAQA;CAKA,MAAM,SAAS,gBAAgB;CAE/B,MAAM,CAAC,QAAQ,aAAa,aAA6B,KAAK;CAC9D,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,MAAM,CAAC,aAAa,kBAAkB,aACpC,KACD;CACD,MAAM,CAAC,WAAW,gBAAgB,aAAa,MAAM;CACrD,MAAM,CAAC,OAAO,YAAY,aAAgC,OAAU;CACpE,MAAM,CAAC,QAAQ,aAAa,aAAoC,OAAO;CACvE,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,IAAI,WAAW;CAOf,MAAM,SAAS,cAA8C;EAG3D,MAAM,cAAc;GAClB,MAAM,QAAQ;GAEd,GAAI,QAAQ,aAAa,SACrB,EAAE,UAAU,QAAQ,UAAU,GAC9B,EAAE,IAAI,QAAQ,MAAM,QAAQ;GAChC,GAAI,QAAQ,gBAAgB,UAAa,EACvC,aAAa,QAAQ,aACtB;GACD,GAAI,QAAQ,sBAAsB,UAAa,EAC7C,mBAAmB,QAAQ,mBAC5B;GACD,GAAI,QAAQ,YAAY,UAAa,EAAE,SAAS,QAAQ,SAAS;GACjE,uBAAuB;GACvB,UAAU;IACR,GAAG,QAAQ;IACX,WAAW;IACX,UAAU;IACV,YAAY;IACb;GAID,YAAY,MAA2B,QAAQ,WAAW,EAAE;GAG5D,UAAU,MAAa;AACrB,QAAI,CAAC,SAAU,SAAQ,UAAU,EAAE;;GAErC,aAAa,GAAW,MAAe;AACrC,QAAI,CAAC,SAAU,SAAQ,aAAa,GAAG,EAAE;;GAE3C,UAAU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A;EACA;EACA;EACD"}
|
|
1
|
+
{"version":3,"file":"use-generate-video.js","names":[],"sources":["../src/use-generate-video.ts"],"sourcesContent":["import { VideoGenerationClient } from '@tanstack/ai-client'\nimport { createVideoDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n createEffect,\n createSignal,\n onCleanup,\n onMount,\n untrack,\n} from 'solid-js'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n VideoGenerateInput,\n VideoGenerateResult,\n VideoStatusInfo,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateVideo hook.\n *\n * @template TOutput - The transformed output type (defaults to VideoGenerateResult)\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 /** 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 * How this generation persists across reloads.\n * - Omit / `false`: ephemeral, in-memory only.\n * - `true`: server-driven — on mount the client hydrates the last generation\n * for its `threadId` from the server (needs a connection with a\n * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.\n */\n persistence?: boolean\n /**\n * The **scope** this generation belongs to: a stable, app-chosen name for the\n * slot successive runs fill — not a link to a chat conversation.\n *\n * The hook starts empty and produces many runs over its life; each gets its\n * own `runId`, but all belong to one scope. Persistence keys on this, so\n * derive it from your own domain and keep it identical across reloads (e.g.\n * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread\n * id on the wire, which the protocol requires.\n *\n * **Required whenever `persistence` is set** — an app that cannot name the\n * scope has nothing to restore to. Optional for ephemeral generations. If\n * omitted, the client mints a wire id after mount.\n */\n threadId?: string\n /**\n * Server-driven hydration handler for `persistence: true` when the\n * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /\n * `rpcStream()` adapter built without handlers) — typically a one-line\n * server-function call. The connection's own handler takes precedence.\n */\n hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']\n /**\n * Re-attach handler that replays a run still generating to completion on\n * mount, when the connection doesn't carry one. Without it, a restored\n * `running` snapshot surfaces as an (interrupted) error. The connection's\n * own handler takes precedence.\n */\n joinRun?: ConnectConnectionAdapter['joinRun']\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 transformed output type (defaults to VideoGenerateResult)\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: Accessor<TOutput | null>\n /** The current job ID, or null */\n jobId: Accessor<string | null>\n /** Current video generation status info, or null */\n videoStatus: Accessor<VideoStatusInfo | null>\n /** Whether generation/polling is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<GenerationClientState>\n /** Abort the current generation/polling */\n stop: () => void\n /** Clear all state and return to idle */\n reset: () => void\n /**\n * The id of the generation job currently running, or `null` when nothing is in\n * flight. Each call to `generate` is one job with its own id. Pass it to your\n * own endpoint to cancel or poll the provider job — `stop()` only aborts the\n * local stream, it does not stop work already running on the provider.\n */\n runId: Accessor<string | null>\n}\n\n/**\n * Solid 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-solid'\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<\n UseGenerateVideoOptions,\n 'onResult' | 'persistence' | 'threadId'\n > & {\n onResult?: (result: VideoGenerateResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerateVideoReturn<\n InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>\n> {\n type TOutput = InferGenerationOutputFromReturn<\n VideoGenerateResult,\n TTransformed\n >\n const [result, setResult] = createSignal<TOutput | null>(null)\n const [jobId, setJobId] = createSignal<string | null>(null)\n const [videoStatus, setVideoStatus] = createSignal<VideoStatusInfo | null>(\n null,\n )\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<GenerationClientState>('idle')\n const [runId, setRunId] = createSignal<string | null>(null)\n let disposed = false\n\n // Built once. `untrack` keeps the option reads below from subscribing\n // construction to `options.persistence` / `options.devtools` /\n // `options.body`: a re-run would build a second client\n // and orphan the first (only the live one is disposed on cleanup). Later\n // `options.body` changes are pushed through `updateOptions` instead.\n const client = untrack((): VideoGenerationClient<TOutput> => {\n // Conditional spread on `body`: VideoGenerationClientOptions.body\n // is a strict optional; EOPT forbids passing `T | undefined`.\n const baseOptions = {\n body: options.body,\n ...(typeof options.threadId === 'string' && options.persistence\n ? {\n persistence: options.persistence,\n threadId: options.threadId,\n }\n : {\n ...(options.threadId !== undefined && {\n threadId: options.threadId,\n }),\n }),\n ...(options.hydrateGeneration !== undefined && {\n hydrateGeneration: options.hydrateGeneration,\n }),\n ...(options.joinRun !== undefined && { joinRun: options.joinRun }),\n devtoolsBridgeFactory: createVideoDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'solid',\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) => options.onResult?.(r)) as (\n result: VideoGenerateResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n if (!disposed) options.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n if (!disposed) options.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n if (!disposed) options.onChunk?.(c)\n },\n onJobCreated: (id: string) => {\n if (!disposed) options.onJobCreated?.(id)\n },\n onStatusUpdate: (s: VideoStatusInfo) => {\n if (!disposed) options.onStatusUpdate?.(s)\n },\n onResultChange: (r: TOutput | null) => {\n if (!disposed) setResult(() => r)\n },\n onLoadingChange: (l: boolean) => {\n if (!disposed) setIsLoading(l)\n },\n onErrorChange: (e: Error | undefined) => {\n if (!disposed) setError(e)\n },\n onStatusChange: (s: GenerationClientState) => {\n if (!disposed) setStatus(s)\n },\n onJobIdChange: (id: string | null) => {\n if (!disposed) setJobId(id)\n },\n onVideoStatusChange: (s: VideoStatusInfo | null) => {\n if (!disposed) setVideoStatus(s)\n },\n onResumeStateChange: (rs: { runId: string } | null) => {\n if (!disposed) setRunId(rs?.runId ?? null)\n },\n }\n\n if (options.connection) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n connection: options.connection,\n })\n }\n\n if (options.fetcher) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n fetcher: options.fetcher,\n })\n }\n\n throw new Error(\n 'useGenerateVideo requires either a connection or fetcher option',\n )\n })\n\n // Sync body changes without recreating client\n createEffect(() => {\n const currentBody = options.body\n client.updateOptions({\n ...(currentBody !== undefined && { body: currentBody }),\n })\n })\n\n // Mount devtools only. Generation runs are never auto-started on mount — a\n // persisted snapshot is hydrated for display, never replayed.\n onMount(() => {\n client.mountDevtools()\n })\n\n // Cleanup on unmount: stop any in-flight requests and unregister devtools\n onCleanup(() => {\n disposed = true\n client.dispose()\n })\n\n const generate = async (input: VideoGenerateInput) => {\n await client.generate(input)\n }\n\n const stop = () => {\n client.stop()\n }\n\n const reset = () => {\n client.reset()\n }\n\n return {\n generate,\n result,\n jobId,\n videoStatus,\n isLoading,\n error,\n status,\n stop,\n reset,\n runId,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiKA,SAAgB,iBACd,SAQA;CAKA,MAAM,CAAC,QAAQ,aAAa,aAA6B,KAAK;CAC9D,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,MAAM,CAAC,aAAa,kBAAkB,aACpC,KACD;CACD,MAAM,CAAC,WAAW,gBAAgB,aAAa,MAAM;CACrD,MAAM,CAAC,OAAO,YAAY,aAAgC,OAAU;CACpE,MAAM,CAAC,QAAQ,aAAa,aAAoC,OAAO;CACvE,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,IAAI,WAAW;CAOf,MAAM,SAAS,cAA8C;EAG3D,MAAM,cAAc;GAClB,MAAM,QAAQ;GACd,GAAI,OAAO,QA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GACrB,CAAC;AAGJ,MAAI,QAAQ,QACV,QAAO,IAAI,sBAA+B;GACxC,GAAG;GACH,SAAS,QAAQ;GAClB,CAAC;AAGJ,QAAM,IAAI,MACR,kEACD;GACD;AAGF,oBAAmB;EACjB,MAAM,cAAc,QAAQ;AAC5B,SAAO,cAAc,EACnB,GAAI,gBAAgB,UAAa,EAAE,MAAM,aAAa,EACvD,CAAC;GACF;AAIF,eAAc;AACZ,SAAO,eAAe;GACtB;AAGF,iBAAgB;AACd,aAAW;AACX,SAAO,SAAS;GAChB;CAEF,MAAM,WAAW,OAAO,UAA8B;AACpD,QAAM,OAAO,SAAS,MAAM;;CAG9B,MAAM,aAAa;AACjB,SAAO,MAAM;;CAGf,MAAM,cAAc;AAClB,SAAO,OAAO;;AAGhB,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
|
package/dist/use-generation.d.ts
CHANGED
|
@@ -18,10 +18,6 @@ interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
|
|
|
18
18
|
connection?: ConnectConnectionAdapter;
|
|
19
19
|
/** Direct async function for one-shot generation (no streaming protocol needed) */
|
|
20
20
|
fetcher?: GenerationFetcher<TInput, TResult>;
|
|
21
|
-
/**
|
|
22
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
23
|
-
*/
|
|
24
|
-
id?: string;
|
|
25
21
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
26
22
|
body?: Record<string, any>;
|
|
27
23
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -45,8 +41,8 @@ interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
|
|
|
45
41
|
* id on the wire, which the protocol requires.
|
|
46
42
|
*
|
|
47
43
|
* **Required whenever `persistence` is set** — an app that cannot name the
|
|
48
|
-
* scope has nothing to restore to. Optional for ephemeral generations
|
|
49
|
-
*
|
|
44
|
+
* scope has nothing to restore to. Optional for ephemeral generations. If
|
|
45
|
+
* omitted, the client mints a wire id after mount.
|
|
50
46
|
*/
|
|
51
47
|
threadId?: string;
|
|
52
48
|
/**
|
|
@@ -133,7 +129,7 @@ interface UseGenerationReturn<TOutput, TInput extends Record<string, any> = Reco
|
|
|
133
129
|
* await generate({ prompt: 'Hello' })
|
|
134
130
|
* ```
|
|
135
131
|
*/
|
|
136
|
-
declare function useGeneration<TInput extends Record<string, any>, TResult, TTransformed = void>(options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult' | 'persistence' | 'threadId'
|
|
132
|
+
declare function useGeneration<TInput extends Record<string, any>, TResult, TTransformed = void>(options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult' | 'persistence' | 'threadId'> & {
|
|
137
133
|
onResult?: (result: TResult) => TTransformed;
|
|
138
134
|
} & GenerationPersistenceOptions): UseGenerationReturn<InferGenerationOutputFromReturn<TResult, TTransformed>, TInput>;
|
|
139
135
|
//#endregion
|
package/dist/use-generation.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createEffect, createSignal,
|
|
1
|
+
import { createEffect, createSignal, onCleanup, onMount, untrack } from "solid-js";
|
|
2
2
|
import { GenerationClient } from "@tanstack/ai-client";
|
|
3
3
|
import { createGenerationDevtoolsBridge } from "@tanstack/ai-client/devtools";
|
|
4
4
|
|
|
@@ -24,7 +24,6 @@ import { createGenerationDevtoolsBridge } from "@tanstack/ai-client/devtools";
|
|
|
24
24
|
* ```
|
|
25
25
|
*/
|
|
26
26
|
function useGeneration(options) {
|
|
27
|
-
const hookId = createUniqueId();
|
|
28
27
|
const [result, setResult] = createSignal(null);
|
|
29
28
|
const [isLoading, setIsLoading] = createSignal(false);
|
|
30
29
|
const [error, setError] = createSignal(void 0);
|
|
@@ -34,8 +33,6 @@ function useGeneration(options) {
|
|
|
34
33
|
const client = untrack(() => {
|
|
35
34
|
const clientOptions = {
|
|
36
35
|
body: options.body,
|
|
37
|
-
...options.threadId !== void 0 ? { threadId: options.threadId } : { id: options.id ?? hookId },
|
|
38
|
-
...options.persistence !== void 0 && { persistence: options.persistence },
|
|
39
36
|
...options.hydrateGeneration !== void 0 && { hydrateGeneration: options.hydrateGeneration },
|
|
40
37
|
...options.joinRun !== void 0 && { joinRun: options.joinRun },
|
|
41
38
|
...options.reconstructResult ? { reconstructResult: options.reconstructResult } : {},
|
|
@@ -71,12 +68,18 @@ function useGeneration(options) {
|
|
|
71
68
|
if (!disposed) setRunId(rs?.runId ?? null);
|
|
72
69
|
}
|
|
73
70
|
};
|
|
71
|
+
const persistenceProps = typeof options.threadId === "string" && options.persistence ? {
|
|
72
|
+
persistence: options.persistence,
|
|
73
|
+
threadId: options.threadId
|
|
74
|
+
} : { ...options.threadId !== void 0 && { threadId: options.threadId } };
|
|
74
75
|
if (options.connection) return new GenerationClient({
|
|
75
76
|
...clientOptions,
|
|
77
|
+
...persistenceProps,
|
|
76
78
|
connection: options.connection
|
|
77
79
|
});
|
|
78
80
|
if (options.fetcher) return new GenerationClient({
|
|
79
81
|
...clientOptions,
|
|
82
|
+
...persistenceProps,
|
|
80
83
|
fetcher: options.fetcher
|
|
81
84
|
});
|
|
82
85
|
throw new Error("useGeneration requires either a connection or fetcher option");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generation.js","names":["clientOptions: GenerationClientOptions<TInput, TResult, TOutput>"],"sources":["../src/use-generation.ts"],"sourcesContent":["import { GenerationClient } from '@tanstack/ai-client'\nimport { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n createEffect,\n createSignal,\n createUniqueId,\n onCleanup,\n onMount,\n untrack,\n} from 'solid-js'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientOptions,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n GenerationRestoredResult,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\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 transformed output type (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 /**\n * @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).\n */\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 * How this generation persists across reloads.\n * - Omit / `false`: ephemeral, in-memory only.\n * - `true`: server-driven — on mount the client hydrates the last generation\n * for its `threadId` from the server (needs a connection with a\n * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.\n */\n persistence?: boolean\n /**\n * The **scope** this generation belongs to: a stable, app-chosen name for the\n * slot successive runs fill — not a link to a chat conversation.\n *\n * The hook starts empty and produces many runs over its life; each gets its\n * own `runId`, but all belong to one scope. Persistence keys on this, so\n * derive it from your own domain and keep it identical across reloads (e.g.\n * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread\n * id on the wire, which the protocol requires.\n *\n * **Required whenever `persistence` is set** — an app that cannot name the\n * scope has nothing to restore to. Optional for ephemeral generations, where\n * it falls back to `id` purely to satisfy the wire.\n */\n threadId?: string\n /**\n * Server-driven hydration handler for `persistence: true` when the\n * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /\n * `rpcStream()` adapter built without handlers) — typically a one-line\n * server-function call. The connection's own handler takes precedence.\n */\n hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']\n /**\n * Re-attach handler that replays a run still generating to completion on\n * mount, when the connection doesn't carry one. Without it, a restored\n * `running` snapshot surfaces as an (interrupted) error. The connection's\n * own handler takes precedence.\n */\n joinRun?: ConnectConnectionAdapter['joinRun']\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 * @internal Rebuild a typed result from a restored snapshot, injected by each\n * specialized hook (image / speech / audio / transcription / summarize).\n * Forwarded to the client so a server-hydrate restore repaints `result`.\n */\n reconstructResult?: (restored: GenerationRestoredResult) => TResult | null\n}\n\n/**\n * Return type for the useGeneration hook.\n *\n * @template TOutput - The output type (possibly transformed from the raw result)\n * @template TInput - The input type accepted by `generate` (defaults to any object)\n */\nexport interface UseGenerationReturn<\n TOutput,\n TInput extends Record<string, any> = Record<string, any>,\n> {\n /** Trigger a generation request */\n generate: (input: TInput) => Promise<void>\n /** The generation result, or null if not yet generated */\n result: Accessor<TOutput | null>\n /** Whether a generation is currently in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation client */\n status: Accessor<GenerationClientState>\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n /**\n * The id of the generation job currently running, or `null` when nothing is in\n * flight. Each call to `generate` is one job with its own id. Pass it to your\n * own endpoint to cancel or poll the provider job — `stop()` only aborts the\n * local stream, it does not stop work already running on the provider.\n */\n runId: Accessor<string | null>\n}\n\n/**\n * Generic Solid 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 * @template TOutput - The transformed output type (defaults to TResult)\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<\n UseGenerationOptions<TInput, TResult>,\n 'onResult' | 'persistence' | 'threadId' | 'id'\n > & {\n onResult?: (result: TResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerationReturn<\n InferGenerationOutputFromReturn<TResult, TTransformed>,\n TInput\n> {\n type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>\n const hookId = createUniqueId()\n\n const [result, setResult] = createSignal<TOutput | null>(null)\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<GenerationClientState>('idle')\n const [runId, setRunId] = createSignal<string | null>(null)\n let disposed = false\n\n // Built once. `untrack` keeps the option reads below from subscribing\n // construction to `options.persistence` / `options.devtools` /\n // `options.body`: a re-run would build a second client\n // and orphan the first (only the live one is disposed on cleanup). Later\n // `options.body` changes are pushed through `updateOptions` instead.\n const client = untrack((): GenerationClient<TInput, TResult, TOutput> => {\n // Conditional spread on `body`: `GenerationClientOptions.body` is a\n // strict optional (`body?: Record<string, any>`) and EOPT forbids\n // assigning the source `T | undefined` directly.\n const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {\n body: options.body,\n // Identity: pass `threadId` alone when set (never also pass deprecated `id`).\n ...(options.threadId !== undefined\n ? { threadId: options.threadId }\n : { id: options.id ?? hookId }),\n ...(options.persistence !== undefined && {\n persistence: options.persistence,\n }),\n ...(options.hydrateGeneration !== undefined && {\n hydrateGeneration: options.hydrateGeneration,\n }),\n ...(options.joinRun !== undefined && { joinRun: options.joinRun }),\n ...(options.reconstructResult\n ? { reconstructResult: options.reconstructResult }\n : {}),\n devtoolsBridgeFactory: createGenerationDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useGeneration',\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) => options.onResult?.(r)) as (\n result: TResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n if (!disposed) options.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n if (!disposed) options.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n if (!disposed) options.onChunk?.(c)\n },\n onResultChange: (r) => {\n if (!disposed) setResult(() => r)\n },\n onLoadingChange: (l) => {\n if (!disposed) setIsLoading(l)\n },\n onErrorChange: (e) => {\n if (!disposed) setError(e)\n },\n onStatusChange: (s) => {\n if (!disposed) setStatus(s)\n },\n onResumeStateChange: (rs) => {\n if (!disposed) setRunId(rs?.runId ?? null)\n },\n }\n\n if (options.connection) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n connection: options.connection,\n })\n }\n\n if (options.fetcher) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n fetcher: options.fetcher,\n })\n }\n\n throw new Error(\n 'useGeneration requires either a connection or fetcher option',\n )\n })\n\n // Sync body changes without recreating client\n createEffect(() => {\n const currentBody = options.body\n client.updateOptions({\n ...(currentBody !== undefined && { body: currentBody }),\n })\n })\n\n // Mount devtools only. Generation runs are never auto-started on mount — a\n // persisted snapshot is hydrated for display, never replayed.\n onMount(() => {\n client.mountDevtools()\n })\n\n // Cleanup on unmount: stop any in-flight requests and unregister devtools\n onCleanup(() => {\n disposed = true\n client.dispose()\n })\n\n const generate = async (input: TInput) => {\n await client.generate(input)\n }\n\n const stop = () => {\n client.stop()\n }\n\n const reset = () => {\n client.reset()\n }\n\n return {\n generate,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n runId,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAmKA,SAAgB,cAKd,SASA;CAEA,MAAM,SAAS,gBAAgB;CAE/B,MAAM,CAAC,QAAQ,aAAa,aAA6B,KAAK;CAC9D,MAAM,CAAC,WAAW,gBAAgB,aAAa,MAAM;CACrD,MAAM,CAAC,OAAO,YAAY,aAAgC,OAAU;CACpE,MAAM,CAAC,QAAQ,aAAa,aAAoC,OAAO;CACvE,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,IAAI,WAAW;CAOf,MAAM,SAAS,cAA0D;EAIvE,MAAMA,gBAAmE;GACvE,MAAM,QAAQ;GAEd,GAAI,QAAQ,aAAa,SACrB,EAAE,UAAU,QAAQ,UAAU,GAC9B,EAAE,IAAI,QAAQ,MAAM,QAAQ;GAChC,GAAI,QAAQ,gBAAgB,UAAa,EACvC,aAAa,QAAQ,aACtB;GACD,GAAI,QAAQ,sBAAsB,UAAa,EAC7C,mBAAmB,QAAQ,mBAC5B;GACD,GAAI,QAAQ,YAAY,UAAa,EAAE,SAAS,QAAQ,SAAS;GACjE,GAAI,QAAQ,oBACR,EAAE,mBAAmB,QAAQ,mBAAmB,GAChD,EAAE;GACN,uBAAuB;GACvB,UAAU;IACR,GAAG,QAAQ;IACX,WAAW;IACX,UAAU;IACX;GAID,YAAY,MAAe,QAAQ,WAAW,EAAE;GAGhD,UAAU,MAAa;AACrB,QAAI,CAAC,SAAU,SAAQ,UAAU,EAAE;;GAErC,aAAa,GAAW,MAAe;AACrC,QAAI,CAAC,SAAU,SAAQ,aAAa,GAAG,EAAE;;GAE3C,UAAU,MAAmB;AAC3B,QAAI,CAAC,SAAU,SAAQ,UAAU,EAAE;;GAErC,iBAAiB,MAAM;AACrB,QAAI,CAAC,SAAU,iBAAgB,EAAE;;GAEnC,kBAAkB,MAAM;AACtB,QAAI,CAAC,SAAU,cAAa,EAAE;;GAEhC,gBAAgB,MAAM;AACpB,QAAI,CAAC,SAAU,UAAS,EAAE;;GAE5B,iBAAiB,MAAM;AACrB,QAAI,CAAC,SAAU,WAAU,EAAE;;GAE7B,sBAAsB,OAAO;AAC3B,QAAI,CAAC,SAAU,UAAS,IAAI,SAAS,KAAK;;GAE7C;AAED,MAAI,QAAQ,WACV,QAAO,IAAI,iBAA2C;GACpD,GAAG;GACH,YAAY,QAAQ;GACrB,CAAC;AAGJ,MAAI,QAAQ,QACV,QAAO,IAAI,iBAA2C;GACpD,GAAG;GACH,SAAS,QAAQ;GAClB,CAAC;AAGJ,QAAM,IAAI,MACR,+DACD;GACD;AAGF,oBAAmB;EACjB,MAAM,cAAc,QAAQ;AAC5B,SAAO,cAAc,EACnB,GAAI,gBAAgB,UAAa,EAAE,MAAM,aAAa,EACvD,CAAC;GACF;AAIF,eAAc;AACZ,SAAO,eAAe;GACtB;AAGF,iBAAgB;AACd,aAAW;AACX,SAAO,SAAS;GAChB;CAEF,MAAM,WAAW,OAAO,UAAkB;AACxC,QAAM,OAAO,SAAS,MAAM;;CAG9B,MAAM,aAAa;AACjB,SAAO,MAAM;;CAGf,MAAM,cAAc;AAClB,SAAO,OAAO;;AAGhB,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
|
|
1
|
+
{"version":3,"file":"use-generation.js","names":["clientOptions: Omit<\n GenerationClientOptions<TInput, TResult, TOutput>,\n 'persistence' | 'threadId'\n >"],"sources":["../src/use-generation.ts"],"sourcesContent":["import { GenerationClient } from '@tanstack/ai-client'\nimport { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n createEffect,\n createSignal,\n onCleanup,\n onMount,\n untrack,\n} from 'solid-js'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientOptions,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n GenerationRestoredResult,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\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 transformed output type (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 /** 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 * How this generation persists across reloads.\n * - Omit / `false`: ephemeral, in-memory only.\n * - `true`: server-driven — on mount the client hydrates the last generation\n * for its `threadId` from the server (needs a connection with a\n * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.\n */\n persistence?: boolean\n /**\n * The **scope** this generation belongs to: a stable, app-chosen name for the\n * slot successive runs fill — not a link to a chat conversation.\n *\n * The hook starts empty and produces many runs over its life; each gets its\n * own `runId`, but all belong to one scope. Persistence keys on this, so\n * derive it from your own domain and keep it identical across reloads (e.g.\n * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread\n * id on the wire, which the protocol requires.\n *\n * **Required whenever `persistence` is set** — an app that cannot name the\n * scope has nothing to restore to. Optional for ephemeral generations. If\n * omitted, the client mints a wire id after mount.\n */\n threadId?: string\n /**\n * Server-driven hydration handler for `persistence: true` when the\n * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /\n * `rpcStream()` adapter built without handlers) — typically a one-line\n * server-function call. The connection's own handler takes precedence.\n */\n hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']\n /**\n * Re-attach handler that replays a run still generating to completion on\n * mount, when the connection doesn't carry one. Without it, a restored\n * `running` snapshot surfaces as an (interrupted) error. The connection's\n * own handler takes precedence.\n */\n joinRun?: ConnectConnectionAdapter['joinRun']\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 * @internal Rebuild a typed result from a restored snapshot, injected by each\n * specialized hook (image / speech / audio / transcription / summarize).\n * Forwarded to the client so a server-hydrate restore repaints `result`.\n */\n reconstructResult?: (restored: GenerationRestoredResult) => TResult | null\n}\n\n/**\n * Return type for the useGeneration hook.\n *\n * @template TOutput - The output type (possibly transformed from the raw result)\n * @template TInput - The input type accepted by `generate` (defaults to any object)\n */\nexport interface UseGenerationReturn<\n TOutput,\n TInput extends Record<string, any> = Record<string, any>,\n> {\n /** Trigger a generation request */\n generate: (input: TInput) => Promise<void>\n /** The generation result, or null if not yet generated */\n result: Accessor<TOutput | null>\n /** Whether a generation is currently in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation client */\n status: Accessor<GenerationClientState>\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n /**\n * The id of the generation job currently running, or `null` when nothing is in\n * flight. Each call to `generate` is one job with its own id. Pass it to your\n * own endpoint to cancel or poll the provider job — `stop()` only aborts the\n * local stream, it does not stop work already running on the provider.\n */\n runId: Accessor<string | null>\n}\n\n/**\n * Generic Solid 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 * @template TOutput - The transformed output type (defaults to TResult)\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<\n UseGenerationOptions<TInput, TResult>,\n 'onResult' | 'persistence' | 'threadId'\n > & {\n onResult?: (result: TResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerationReturn<\n InferGenerationOutputFromReturn<TResult, TTransformed>,\n TInput\n> {\n type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>\n\n const [result, setResult] = createSignal<TOutput | null>(null)\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<GenerationClientState>('idle')\n const [runId, setRunId] = createSignal<string | null>(null)\n let disposed = false\n\n // Built once. `untrack` keeps the option reads below from subscribing\n // construction to `options.persistence` / `options.devtools` /\n // `options.body`: a re-run would build a second client\n // and orphan the first (only the live one is disposed on cleanup). Later\n // `options.body` changes are pushed through `updateOptions` instead.\n const client = untrack((): GenerationClient<TInput, TResult, TOutput> => {\n // Conditional spread on `body`: `GenerationClientOptions.body` is a\n // strict optional (`body?: Record<string, any>`) and EOPT forbids\n // assigning the source `T | undefined` directly.\n const clientOptions: Omit<\n GenerationClientOptions<TInput, TResult, TOutput>,\n 'persistence' | 'threadId'\n > = {\n body: options.body,\n ...(options.hydrateGeneration !== undefined && {\n hydrateGeneration: options.hydrateGeneration,\n }),\n ...(options.joinRun !== undefined && { joinRun: options.joinRun }),\n ...(options.reconstructResult\n ? { reconstructResult: options.reconstructResult }\n : {}),\n devtoolsBridgeFactory: createGenerationDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useGeneration',\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) => options.onResult?.(r)) as (\n result: TResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n if (!disposed) options.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n if (!disposed) options.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n if (!disposed) options.onChunk?.(c)\n },\n onResultChange: (r) => {\n if (!disposed) setResult(() => r)\n },\n onLoadingChange: (l) => {\n if (!disposed) setIsLoading(l)\n },\n onErrorChange: (e) => {\n if (!disposed) setError(e)\n },\n onStatusChange: (s) => {\n if (!disposed) setStatus(s)\n },\n onResumeStateChange: (rs) => {\n if (!disposed) setRunId(rs?.runId ?? null)\n },\n }\n\n const persistenceProps =\n typeof options.threadId === 'string' && options.persistence\n ? {\n persistence: options.persistence,\n threadId: options.threadId,\n }\n : {\n ...(options.threadId !== undefined && {\n threadId: options.threadId,\n }),\n }\n\n if (options.connection) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n ...persistenceProps,\n connection: options.connection,\n })\n }\n\n if (options.fetcher) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n ...persistenceProps,\n fetcher: options.fetcher,\n })\n }\n\n throw new Error(\n 'useGeneration requires either a connection or fetcher option',\n )\n })\n\n // Sync body changes without recreating client\n createEffect(() => {\n const currentBody = options.body\n client.updateOptions({\n ...(currentBody !== undefined && { body: currentBody }),\n })\n })\n\n // Mount devtools only. Generation runs are never auto-started on mount — a\n // persisted snapshot is hydrated for display, never replayed.\n onMount(() => {\n client.mountDevtools()\n })\n\n // Cleanup on unmount: stop any in-flight requests and unregister devtools\n onCleanup(() => {\n disposed = true\n client.dispose()\n })\n\n const generate = async (input: TInput) => {\n await client.generate(input)\n }\n\n const stop = () => {\n client.stop()\n }\n\n const reset = () => {\n client.reset()\n }\n\n return {\n generate,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n runId,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA8JA,SAAgB,cAKd,SASA;CAGA,MAAM,CAAC,QAAQ,aAAa,aAA6B,KAAK;CAC9D,MAAM,CAAC,WAAW,gBAAgB,aAAa,MAAM;CACrD,MAAM,CAAC,OAAO,YAAY,aAAgC,OAAU;CACpE,MAAM,CAAC,QAAQ,aAAa,aAAoC,OAAO;CACvE,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,IAAI,WAAW;CAOf,MAAM,SAAS,cAA0D;EAIvE,MAAMA,gBAGF;GACF,MAAM,QAAQ;GACd,GAAI,QAAQ,sBAAsB,UAAa,EAC7C,mBAAmB,QAAQ,mBAC5B;GACD,GAAI,QAAQ,YAAY,UAAa,EAAE,SAAS,QAAQ,SAAS;GACjE,GAAI,QAAQ,oBACR,EAAE,mBAAmB,QAAQ,mBAAmB,GAChD,EAAE;GACN,uBAAuB;GACvB,UAAU;IACR,GAAG,QAAQ;IACX,WAAW;IACX,UAAU;IACX;GAID,YAAY,MAAe,QAAQ,WAAW,EAAE;GAGhD,UAAU,MAAa;AACrB,QAAI,CAAC,SAAU,SAAQ,UAAU,EAAE;;GAErC,aAAa,GAAW,MAAe;AACrC,QAAI,CAAC,SAAU,SAAQ,aAAa,GAAG,EAAE;;GAE3C,UAAU,MAAmB;AAC3B,QAAI,CAAC,SAAU,SAAQ,UAAU,EAAE;;GAErC,iBAAiB,MAAM;AACrB,QAAI,CAAC,SAAU,iBAAgB,EAAE;;GAEnC,kBAAkB,MAAM;AACtB,QAAI,CAAC,SAAU,cAAa,EAAE;;GAEhC,gBAAgB,MAAM;AACpB,QAAI,CAAC,SAAU,UAAS,EAAE;;GAE5B,iBAAiB,MAAM;AACrB,QAAI,CAAC,SAAU,WAAU,EAAE;;GAE7B,sBAAsB,OAAO;AAC3B,QAAI,CAAC,SAAU,UAAS,IAAI,SAAS,KAAK;;GAE7C;EAED,MAAM,mBACJ,OAAO,QAAQ,aAAa,YAAY,QAAQ,cAC5C;GACE,aAAa,QAAQ;GACrB,UAAU,QAAQ;GACnB,GACD,EACE,GAAI,QAAQ,aAAa,UAAa,EACpC,UAAU,QAAQ,UACnB,EACF;AAEP,MAAI,QAAQ,WACV,QAAO,IAAI,iBAA2C;GACpD,GAAG;GACH,GAAG;GACH,YAAY,QAAQ;GACrB,CAAC;AAGJ,MAAI,QAAQ,QACV,QAAO,IAAI,iBAA2C;GACpD,GAAG;GACH,GAAG;GACH,SAAS,QAAQ;GAClB,CAAC;AAGJ,QAAM,IAAI,MACR,+DACD;GACD;AAGF,oBAAmB;EACjB,MAAM,cAAc,QAAQ;AAC5B,SAAO,cAAc,EACnB,GAAI,gBAAgB,UAAa,EAAE,MAAM,aAAa,EACvD,CAAC;GACF;AAIF,eAAc;AACZ,SAAO,eAAe;GACtB;AAGF,iBAAgB;AACd,aAAW;AACX,SAAO,SAAS;GAChB;CAEF,MAAM,WAAW,OAAO,UAAkB;AACxC,QAAM,OAAO,SAAS,MAAM;;CAG9B,MAAM,aAAa;AACjB,SAAO,MAAM;;CAGf,MAAM,cAAc;AAClB,SAAO,OAAO;;AAGhB,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
|
package/dist/use-summarize.d.ts
CHANGED
|
@@ -15,10 +15,6 @@ interface UseSummarizeOptions<TOutput = SummarizationResult> extends Pick<UseGen
|
|
|
15
15
|
connection?: ConnectConnectionAdapter;
|
|
16
16
|
/** Direct async function for summarization */
|
|
17
17
|
fetcher?: GenerationFetcher<SummarizeGenerateInput, SummarizationResult>;
|
|
18
|
-
/**
|
|
19
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
20
|
-
*/
|
|
21
|
-
id?: string;
|
|
22
18
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
23
19
|
body?: Record<string, any>;
|
|
24
20
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -84,7 +80,7 @@ interface UseSummarizeReturn<TOutput = SummarizationResult> extends Omit<UseGene
|
|
|
84
80
|
* }
|
|
85
81
|
* ```
|
|
86
82
|
*/
|
|
87
|
-
declare function useSummarize<TTransformed = void>(options: Omit<UseSummarizeOptions, 'onResult' | 'persistence' | 'threadId'
|
|
83
|
+
declare function useSummarize<TTransformed = void>(options: Omit<UseSummarizeOptions, 'onResult' | 'persistence' | 'threadId'> & {
|
|
88
84
|
onResult?: (result: SummarizationResult) => TTransformed;
|
|
89
85
|
} & GenerationPersistenceOptions): UseSummarizeReturn<InferGenerationOutputFromReturn<SummarizationResult, TTransformed>>;
|
|
90
86
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-summarize.js","names":[],"sources":["../src/use-summarize.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructSummarizeResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { StreamChunk, SummarizationResult } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n SummarizeGenerateInput,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useSummarize hook.\n *\n * @template TOutput - The transformed output type (defaults to SummarizationResult)\n */\nexport interface UseSummarizeOptions<\n TOutput = SummarizationResult,\n> extends Pick<\n UseGenerationOptions<SummarizeGenerateInput, SummarizationResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for summarization */\n fetcher?: GenerationFetcher<SummarizeGenerateInput, SummarizationResult>\n
|
|
1
|
+
{"version":3,"file":"use-summarize.js","names":[],"sources":["../src/use-summarize.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructSummarizeResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { StreamChunk, SummarizationResult } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n SummarizeGenerateInput,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useSummarize hook.\n *\n * @template TOutput - The transformed output type (defaults to SummarizationResult)\n */\nexport interface UseSummarizeOptions<\n TOutput = SummarizationResult,\n> extends Pick<\n UseGenerationOptions<SummarizeGenerateInput, SummarizationResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for summarization */\n fetcher?: GenerationFetcher<SummarizeGenerateInput, SummarizationResult>\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 summarization is complete. 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: SummarizationResult) => 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 useSummarize hook.\n *\n * @template TOutput - The transformed output type (defaults to SummarizationResult)\n */\nexport interface UseSummarizeReturn<TOutput = SummarizationResult> extends Omit<\n UseGenerationReturn<TOutput>,\n 'generate'\n> {\n /** Trigger summarization */\n generate: (input: SummarizeGenerateInput) => Promise<void>\n /** The summarization result, or null */\n result: Accessor<TOutput | null>\n /** Whether summarization is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<GenerationClientState>\n}\n\n/**\n * Solid hook for summarizing text using AI models.\n *\n * @example\n * ```tsx\n * import { useSummarize } from '@tanstack/ai-solid'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function Summarizer() {\n * const { generate, result, isLoading } = useSummarize({\n * connection: fetchServerSentEvents('/api/summarize'),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({\n * text: 'Long article text...',\n * style: 'bullet-points',\n * maxLength: 200,\n * })}>\n * Summarize\n * </button>\n * {isLoading() && <p>Summarizing...</p>}\n * {result() && <p>{result()!.summary}</p>}\n * </div>\n * )\n * }\n * ```\n */\nexport function useSummarize<TTransformed = void>(\n options: Omit<\n UseSummarizeOptions,\n 'onResult' | 'persistence' | 'threadId'\n > & {\n onResult?: (result: SummarizationResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseSummarizeReturn<\n InferGenerationOutputFromReturn<SummarizationResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useSummarize',\n outputKind: 'text' as const,\n }\n const generation = useGeneration<\n SummarizeGenerateInput,\n SummarizationResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructSummarizeResult,\n })\n\n return generation\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuGA,SAAgB,aACd,SAQA;CACA,MAAM,WAAW;EACf,GAAG,QAAQ;EACX,WAAW;EACX,UAAU;EACV,YAAY;EACb;AAWD,QAVmB,cAIjB;EACA,GAAG;EACH;EACA,mBAAmB;EACpB,CAAC"}
|
|
@@ -15,10 +15,6 @@ interface UseTranscriptionOptions<TOutput = TranscriptionResult> extends Pick<Us
|
|
|
15
15
|
connection?: ConnectConnectionAdapter;
|
|
16
16
|
/** Direct async function for transcription */
|
|
17
17
|
fetcher?: GenerationFetcher<TranscriptionGenerateInput, TranscriptionResult>;
|
|
18
|
-
/**
|
|
19
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
20
|
-
*/
|
|
21
|
-
id?: string;
|
|
22
18
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
23
19
|
body?: Record<string, any>;
|
|
24
20
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -90,7 +86,7 @@ interface UseTranscriptionReturn<TOutput = TranscriptionResult> extends Omit<Use
|
|
|
90
86
|
* }
|
|
91
87
|
* ```
|
|
92
88
|
*/
|
|
93
|
-
declare function useTranscription<TTransformed = void>(options: Omit<UseTranscriptionOptions, 'onResult' | 'persistence' | 'threadId'
|
|
89
|
+
declare function useTranscription<TTransformed = void>(options: Omit<UseTranscriptionOptions, 'onResult' | 'persistence' | 'threadId'> & {
|
|
94
90
|
onResult?: (result: TranscriptionResult) => TTransformed;
|
|
95
91
|
} & GenerationPersistenceOptions): UseTranscriptionReturn<InferGenerationOutputFromReturn<TranscriptionResult, TTransformed>>;
|
|
96
92
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-transcription.js","names":[],"sources":["../src/use-transcription.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructTranscriptionResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { StreamChunk, TranscriptionResult } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n TranscriptionGenerateInput,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useTranscription hook.\n *\n * @template TOutput - The transformed output type (defaults to TranscriptionResult)\n */\nexport interface UseTranscriptionOptions<\n TOutput = TranscriptionResult,\n> extends Pick<\n UseGenerationOptions<\n TranscriptionGenerateInput,\n TranscriptionResult,\n TOutput\n >,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for transcription */\n fetcher?: GenerationFetcher<TranscriptionGenerateInput, TranscriptionResult>\n
|
|
1
|
+
{"version":3,"file":"use-transcription.js","names":[],"sources":["../src/use-transcription.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructTranscriptionResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { StreamChunk, TranscriptionResult } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n TranscriptionGenerateInput,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useTranscription hook.\n *\n * @template TOutput - The transformed output type (defaults to TranscriptionResult)\n */\nexport interface UseTranscriptionOptions<\n TOutput = TranscriptionResult,\n> extends Pick<\n UseGenerationOptions<\n TranscriptionGenerateInput,\n TranscriptionResult,\n TOutput\n >,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for transcription */\n fetcher?: GenerationFetcher<TranscriptionGenerateInput, TranscriptionResult>\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 transcription is complete. 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: TranscriptionResult) => 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 useTranscription hook.\n *\n * @template TOutput - The transformed output type (defaults to TranscriptionResult)\n */\nexport interface UseTranscriptionReturn<\n TOutput = TranscriptionResult,\n> extends Omit<UseGenerationReturn<TOutput>, 'generate'> {\n /** Trigger transcription */\n generate: (input: TranscriptionGenerateInput) => Promise<void>\n /** The transcription result, or null */\n result: Accessor<TOutput | null>\n /** Whether transcription is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<GenerationClientState>\n}\n\n/**\n * Solid hook for transcribing audio to text using AI models.\n *\n * @example\n * ```tsx\n * import { useTranscription } from '@tanstack/ai-solid'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function Transcriber() {\n * const { generate, result, isLoading } = useTranscription({\n * connection: fetchServerSentEvents('/api/transcribe'),\n * })\n *\n * const handleFile = (e: Event) => {\n * const input = e.target as HTMLInputElement\n * const file = input.files?.[0]\n * if (file) {\n * const reader = new FileReader()\n * reader.onload = () => {\n * generate({ audio: reader.result as string, language: 'en' })\n * }\n * reader.readAsDataURL(file)\n * }\n * }\n *\n * return (\n * <div>\n * <input type=\"file\" accept=\"audio/*\" onChange={handleFile} />\n * {isLoading() && <p>Transcribing...</p>}\n * {result() && <p>{result()!.text}</p>}\n * </div>\n * )\n * }\n * ```\n */\nexport function useTranscription<TTransformed = void>(\n options: Omit<\n UseTranscriptionOptions,\n 'onResult' | 'persistence' | 'threadId'\n > & {\n onResult?: (result: TranscriptionResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseTranscriptionReturn<\n InferGenerationOutputFromReturn<TranscriptionResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useTranscription',\n outputKind: 'text' as const,\n }\n const generation = useGeneration<\n TranscriptionGenerateInput,\n TranscriptionResult,\n TTransformed\n >({ ...options, devtools, reconstructResult: reconstructTranscriptionResult })\n\n return generation\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgHA,SAAgB,iBACd,SAQA;CACA,MAAM,WAAW;EACf,GAAG,QAAQ;EACX,WAAW;EACX,UAAU;EACV,YAAY;EACb;AAOD,QANmB,cAIjB;EAAE,GAAG;EAAS;EAAU,mBAAmB;EAAgC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/ai-solid",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"description": "Solid hooks for TanStack AI streaming chat, structured outputs, and media generation.",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -45,23 +45,23 @@
|
|
|
45
45
|
"media-generation"
|
|
46
46
|
],
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@tanstack/ai-client": "^0.
|
|
48
|
+
"@tanstack/ai-client": "^0.24.0"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
51
|
"solid-js": ">=1.9.10",
|
|
52
|
-
"@tanstack/ai": "^0.
|
|
52
|
+
"@tanstack/ai": "^0.46.0"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"@solidjs/testing-library": "^0.8.10",
|
|
56
56
|
"@standard-schema/spec": "^1.1.0",
|
|
57
57
|
"@types/node": "^24.10.1",
|
|
58
|
-
"@vitest/coverage-v8": "4.
|
|
59
|
-
"jsdom": "^27.
|
|
58
|
+
"@vitest/coverage-v8": "4.1.10",
|
|
59
|
+
"jsdom": "^27.4.0",
|
|
60
60
|
"solid-js": "^1.9.10",
|
|
61
61
|
"tsdown": "^0.17.0-beta.6",
|
|
62
62
|
"typescript": "5.9.3",
|
|
63
63
|
"vitest": "^4.1.10",
|
|
64
|
-
"@tanstack/ai": "0.
|
|
64
|
+
"@tanstack/ai": "0.46.0"
|
|
65
65
|
},
|
|
66
66
|
"scripts": {
|
|
67
67
|
"clean": "premove ./build ./dist",
|
package/src/index.ts
CHANGED
|
@@ -77,6 +77,7 @@ export {
|
|
|
77
77
|
xhrHttpStream,
|
|
78
78
|
stream,
|
|
79
79
|
rpcStream,
|
|
80
|
+
webSocket,
|
|
80
81
|
createChatClientOptions,
|
|
81
82
|
type ConnectionAdapter,
|
|
82
83
|
type ConnectConnectionAdapter,
|
|
@@ -84,6 +85,7 @@ export {
|
|
|
84
85
|
type RunAgentInputContext,
|
|
85
86
|
type FetchConnectionOptions,
|
|
86
87
|
type XhrConnectionOptions,
|
|
88
|
+
type WebSocketConnectionOptions,
|
|
87
89
|
type InferChatMessages,
|
|
88
90
|
type GenerationClientState,
|
|
89
91
|
type ImageGenerateInput,
|
package/src/types.ts
CHANGED
|
@@ -93,10 +93,6 @@ export type UseChatOptions<
|
|
|
93
93
|
| 'onRunIdChange'
|
|
94
94
|
| 'context'
|
|
95
95
|
| 'devtools'
|
|
96
|
-
// `id` is not a hook option: the hook's identity is its `threadId`, which is
|
|
97
|
-
// also the persistence key. Persist across reloads by passing a stable
|
|
98
|
-
// `threadId`; there is no separate id to set.
|
|
99
|
-
| 'id'
|
|
100
96
|
> & {
|
|
101
97
|
/** Display options for TanStack AI Devtools. */
|
|
102
98
|
devtools?: AIDevtoolsDisplayOptions
|
package/src/use-chat.ts
CHANGED
|
@@ -50,10 +50,9 @@ export function useChat<
|
|
|
50
50
|
TContext
|
|
51
51
|
>,
|
|
52
52
|
): UseChatReturn<TTools, TSchema> {
|
|
53
|
-
// The hook's identity is its `threadId
|
|
54
|
-
//
|
|
55
|
-
//
|
|
56
|
-
// given (an ephemeral chat), never a persistence key.
|
|
53
|
+
// The hook's identity is its `threadId`. Reload with the same `threadId`
|
|
54
|
+
// restores the same conversation. `hookId` is only a recreation key when no
|
|
55
|
+
// `threadId` is given. It is never sent on the wire.
|
|
57
56
|
const hookId = createUniqueId()
|
|
58
57
|
const clientId = options.threadId ?? hookId
|
|
59
58
|
|
|
@@ -110,14 +109,20 @@ export function useChat<
|
|
|
110
109
|
...(options.initialMessages !== undefined && {
|
|
111
110
|
initialMessages: options.initialMessages,
|
|
112
111
|
}),
|
|
113
|
-
...(options.
|
|
114
|
-
|
|
115
|
-
|
|
112
|
+
...(typeof options.threadId === 'string' && options.persistence
|
|
113
|
+
? {
|
|
114
|
+
persistence: options.persistence,
|
|
115
|
+
threadId: options.threadId,
|
|
116
|
+
}
|
|
117
|
+
: {
|
|
118
|
+
...(options.threadId !== undefined && {
|
|
119
|
+
threadId: options.threadId,
|
|
120
|
+
}),
|
|
121
|
+
}),
|
|
116
122
|
...(options.initialResumeSnapshot !== undefined && {
|
|
117
123
|
initialResumeSnapshot: options.initialResumeSnapshot,
|
|
118
124
|
}),
|
|
119
125
|
body: options.body,
|
|
120
|
-
...(options.threadId !== undefined && { threadId: options.threadId }),
|
|
121
126
|
...(options.forwardedProps !== undefined && {
|
|
122
127
|
forwardedProps: options.forwardedProps,
|
|
123
128
|
}),
|
|
@@ -31,10 +31,6 @@ export interface UseGenerateAudioOptions<
|
|
|
31
31
|
connection?: ConnectConnectionAdapter
|
|
32
32
|
/** Direct async function for audio generation */
|
|
33
33
|
fetcher?: GenerationFetcher<AudioGenerateInput, AudioGenerationResult>
|
|
34
|
-
/**
|
|
35
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
36
|
-
*/
|
|
37
|
-
id?: string
|
|
38
34
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
39
35
|
body?: Record<string, any>
|
|
40
36
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -102,7 +98,7 @@ export interface UseGenerateAudioReturn<
|
|
|
102
98
|
export function useGenerateAudio<TTransformed = void>(
|
|
103
99
|
options: Omit<
|
|
104
100
|
UseGenerateAudioOptions,
|
|
105
|
-
'onResult' | 'persistence' | 'threadId'
|
|
101
|
+
'onResult' | 'persistence' | 'threadId'
|
|
106
102
|
> & {
|
|
107
103
|
onResult?: (result: AudioGenerationResult) => TTransformed
|
|
108
104
|
} & GenerationPersistenceOptions,
|
|
@@ -31,10 +31,6 @@ export interface UseGenerateImageOptions<
|
|
|
31
31
|
connection?: ConnectConnectionAdapter
|
|
32
32
|
/** Direct async function for image generation */
|
|
33
33
|
fetcher?: GenerationFetcher<ImageGenerateInput, ImageGenerationResult>
|
|
34
|
-
/**
|
|
35
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
36
|
-
*/
|
|
37
|
-
id?: string
|
|
38
34
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
39
35
|
body?: Record<string, any>
|
|
40
36
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -110,7 +106,7 @@ export interface UseGenerateImageReturn<
|
|
|
110
106
|
export function useGenerateImage<TTransformed = void>(
|
|
111
107
|
options: Omit<
|
|
112
108
|
UseGenerateImageOptions,
|
|
113
|
-
'onResult' | 'persistence' | 'threadId'
|
|
109
|
+
'onResult' | 'persistence' | 'threadId'
|
|
114
110
|
> & {
|
|
115
111
|
onResult?: (result: ImageGenerationResult) => TTransformed
|
|
116
112
|
} & GenerationPersistenceOptions,
|
|
@@ -29,10 +29,6 @@ export interface UseGenerateSpeechOptions<TOutput = TTSResult> extends Pick<
|
|
|
29
29
|
connection?: ConnectConnectionAdapter
|
|
30
30
|
/** Direct async function for speech generation */
|
|
31
31
|
fetcher?: GenerationFetcher<SpeechGenerateInput, TTSResult>
|
|
32
|
-
/**
|
|
33
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
34
|
-
*/
|
|
35
|
-
id?: string
|
|
36
32
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
37
33
|
body?: Record<string, any>
|
|
38
34
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -103,7 +99,7 @@ export interface UseGenerateSpeechReturn<TOutput = TTSResult> extends Omit<
|
|
|
103
99
|
export function useGenerateSpeech<TTransformed = void>(
|
|
104
100
|
options: Omit<
|
|
105
101
|
UseGenerateSpeechOptions,
|
|
106
|
-
'onResult' | 'persistence' | 'threadId'
|
|
102
|
+
'onResult' | 'persistence' | 'threadId'
|
|
107
103
|
> & {
|
|
108
104
|
onResult?: (result: TTSResult) => TTransformed
|
|
109
105
|
} & GenerationPersistenceOptions,
|
|
@@ -3,7 +3,6 @@ import { createVideoDevtoolsBridge } from '@tanstack/ai-client/devtools'
|
|
|
3
3
|
import {
|
|
4
4
|
createEffect,
|
|
5
5
|
createSignal,
|
|
6
|
-
createUniqueId,
|
|
7
6
|
onCleanup,
|
|
8
7
|
onMount,
|
|
9
8
|
untrack,
|
|
@@ -32,10 +31,6 @@ export interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {
|
|
|
32
31
|
connection?: ConnectConnectionAdapter
|
|
33
32
|
/** Direct async function that returns a completed video result */
|
|
34
33
|
fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>
|
|
35
|
-
/**
|
|
36
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
37
|
-
*/
|
|
38
|
-
id?: string
|
|
39
34
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
40
35
|
body?: Record<string, any>
|
|
41
36
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -59,8 +54,8 @@ export interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {
|
|
|
59
54
|
* id on the wire, which the protocol requires.
|
|
60
55
|
*
|
|
61
56
|
* **Required whenever `persistence` is set** — an app that cannot name the
|
|
62
|
-
* scope has nothing to restore to. Optional for ephemeral generations
|
|
63
|
-
*
|
|
57
|
+
* scope has nothing to restore to. Optional for ephemeral generations. If
|
|
58
|
+
* omitted, the client mints a wire id after mount.
|
|
64
59
|
*/
|
|
65
60
|
threadId?: string
|
|
66
61
|
/**
|
|
@@ -167,7 +162,7 @@ export interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {
|
|
|
167
162
|
export function useGenerateVideo<TTransformed = void>(
|
|
168
163
|
options: Omit<
|
|
169
164
|
UseGenerateVideoOptions,
|
|
170
|
-
'onResult' | 'persistence' | 'threadId'
|
|
165
|
+
'onResult' | 'persistence' | 'threadId'
|
|
171
166
|
> & {
|
|
172
167
|
onResult?: (result: VideoGenerateResult) => TTransformed
|
|
173
168
|
} & GenerationPersistenceOptions,
|
|
@@ -178,8 +173,6 @@ export function useGenerateVideo<TTransformed = void>(
|
|
|
178
173
|
VideoGenerateResult,
|
|
179
174
|
TTransformed
|
|
180
175
|
>
|
|
181
|
-
const hookId = createUniqueId()
|
|
182
|
-
|
|
183
176
|
const [result, setResult] = createSignal<TOutput | null>(null)
|
|
184
177
|
const [jobId, setJobId] = createSignal<string | null>(null)
|
|
185
178
|
const [videoStatus, setVideoStatus] = createSignal<VideoStatusInfo | null>(
|
|
@@ -201,13 +194,16 @@ export function useGenerateVideo<TTransformed = void>(
|
|
|
201
194
|
// is a strict optional; EOPT forbids passing `T | undefined`.
|
|
202
195
|
const baseOptions = {
|
|
203
196
|
body: options.body,
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
197
|
+
...(typeof options.threadId === 'string' && options.persistence
|
|
198
|
+
? {
|
|
199
|
+
persistence: options.persistence,
|
|
200
|
+
threadId: options.threadId,
|
|
201
|
+
}
|
|
202
|
+
: {
|
|
203
|
+
...(options.threadId !== undefined && {
|
|
204
|
+
threadId: options.threadId,
|
|
205
|
+
}),
|
|
206
|
+
}),
|
|
211
207
|
...(options.hydrateGeneration !== undefined && {
|
|
212
208
|
hydrateGeneration: options.hydrateGeneration,
|
|
213
209
|
}),
|
package/src/use-generation.ts
CHANGED
|
@@ -3,7 +3,6 @@ import { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'
|
|
|
3
3
|
import {
|
|
4
4
|
createEffect,
|
|
5
5
|
createSignal,
|
|
6
|
-
createUniqueId,
|
|
7
6
|
onCleanup,
|
|
8
7
|
onMount,
|
|
9
8
|
untrack,
|
|
@@ -35,10 +34,6 @@ export interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
|
|
|
35
34
|
connection?: ConnectConnectionAdapter
|
|
36
35
|
/** Direct async function for one-shot generation (no streaming protocol needed) */
|
|
37
36
|
fetcher?: GenerationFetcher<TInput, TResult>
|
|
38
|
-
/**
|
|
39
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
40
|
-
*/
|
|
41
|
-
id?: string
|
|
42
37
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
43
38
|
body?: Record<string, any>
|
|
44
39
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -62,8 +57,8 @@ export interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
|
|
|
62
57
|
* id on the wire, which the protocol requires.
|
|
63
58
|
*
|
|
64
59
|
* **Required whenever `persistence` is set** — an app that cannot name the
|
|
65
|
-
* scope has nothing to restore to. Optional for ephemeral generations
|
|
66
|
-
*
|
|
60
|
+
* scope has nothing to restore to. Optional for ephemeral generations. If
|
|
61
|
+
* omitted, the client mints a wire id after mount.
|
|
67
62
|
*/
|
|
68
63
|
threadId?: string
|
|
69
64
|
/**
|
|
@@ -168,7 +163,7 @@ export function useGeneration<
|
|
|
168
163
|
>(
|
|
169
164
|
options: Omit<
|
|
170
165
|
UseGenerationOptions<TInput, TResult>,
|
|
171
|
-
'onResult' | 'persistence' | 'threadId'
|
|
166
|
+
'onResult' | 'persistence' | 'threadId'
|
|
172
167
|
> & {
|
|
173
168
|
onResult?: (result: TResult) => TTransformed
|
|
174
169
|
} & GenerationPersistenceOptions,
|
|
@@ -177,7 +172,6 @@ export function useGeneration<
|
|
|
177
172
|
TInput
|
|
178
173
|
> {
|
|
179
174
|
type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>
|
|
180
|
-
const hookId = createUniqueId()
|
|
181
175
|
|
|
182
176
|
const [result, setResult] = createSignal<TOutput | null>(null)
|
|
183
177
|
const [isLoading, setIsLoading] = createSignal(false)
|
|
@@ -195,15 +189,11 @@ export function useGeneration<
|
|
|
195
189
|
// Conditional spread on `body`: `GenerationClientOptions.body` is a
|
|
196
190
|
// strict optional (`body?: Record<string, any>`) and EOPT forbids
|
|
197
191
|
// assigning the source `T | undefined` directly.
|
|
198
|
-
const clientOptions:
|
|
192
|
+
const clientOptions: Omit<
|
|
193
|
+
GenerationClientOptions<TInput, TResult, TOutput>,
|
|
194
|
+
'persistence' | 'threadId'
|
|
195
|
+
> = {
|
|
199
196
|
body: options.body,
|
|
200
|
-
// Identity: pass `threadId` alone when set (never also pass deprecated `id`).
|
|
201
|
-
...(options.threadId !== undefined
|
|
202
|
-
? { threadId: options.threadId }
|
|
203
|
-
: { id: options.id ?? hookId }),
|
|
204
|
-
...(options.persistence !== undefined && {
|
|
205
|
-
persistence: options.persistence,
|
|
206
|
-
}),
|
|
207
197
|
...(options.hydrateGeneration !== undefined && {
|
|
208
198
|
hydrateGeneration: options.hydrateGeneration,
|
|
209
199
|
}),
|
|
@@ -249,9 +239,22 @@ export function useGeneration<
|
|
|
249
239
|
},
|
|
250
240
|
}
|
|
251
241
|
|
|
242
|
+
const persistenceProps =
|
|
243
|
+
typeof options.threadId === 'string' && options.persistence
|
|
244
|
+
? {
|
|
245
|
+
persistence: options.persistence,
|
|
246
|
+
threadId: options.threadId,
|
|
247
|
+
}
|
|
248
|
+
: {
|
|
249
|
+
...(options.threadId !== undefined && {
|
|
250
|
+
threadId: options.threadId,
|
|
251
|
+
}),
|
|
252
|
+
}
|
|
253
|
+
|
|
252
254
|
if (options.connection) {
|
|
253
255
|
return new GenerationClient<TInput, TResult, TOutput>({
|
|
254
256
|
...clientOptions,
|
|
257
|
+
...persistenceProps,
|
|
255
258
|
connection: options.connection,
|
|
256
259
|
})
|
|
257
260
|
}
|
|
@@ -259,6 +262,7 @@ export function useGeneration<
|
|
|
259
262
|
if (options.fetcher) {
|
|
260
263
|
return new GenerationClient<TInput, TResult, TOutput>({
|
|
261
264
|
...clientOptions,
|
|
265
|
+
...persistenceProps,
|
|
262
266
|
fetcher: options.fetcher,
|
|
263
267
|
})
|
|
264
268
|
}
|
package/src/use-summarize.ts
CHANGED
|
@@ -31,10 +31,6 @@ export interface UseSummarizeOptions<
|
|
|
31
31
|
connection?: ConnectConnectionAdapter
|
|
32
32
|
/** Direct async function for summarization */
|
|
33
33
|
fetcher?: GenerationFetcher<SummarizeGenerateInput, SummarizationResult>
|
|
34
|
-
/**
|
|
35
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
36
|
-
*/
|
|
37
|
-
id?: string
|
|
38
34
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
39
35
|
body?: Record<string, any>
|
|
40
36
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -108,7 +104,7 @@ export interface UseSummarizeReturn<TOutput = SummarizationResult> extends Omit<
|
|
|
108
104
|
export function useSummarize<TTransformed = void>(
|
|
109
105
|
options: Omit<
|
|
110
106
|
UseSummarizeOptions,
|
|
111
|
-
'onResult' | 'persistence' | 'threadId'
|
|
107
|
+
'onResult' | 'persistence' | 'threadId'
|
|
112
108
|
> & {
|
|
113
109
|
onResult?: (result: SummarizationResult) => TTransformed
|
|
114
110
|
} & GenerationPersistenceOptions,
|
package/src/use-transcription.ts
CHANGED
|
@@ -35,10 +35,6 @@ export interface UseTranscriptionOptions<
|
|
|
35
35
|
connection?: ConnectConnectionAdapter
|
|
36
36
|
/** Direct async function for transcription */
|
|
37
37
|
fetcher?: GenerationFetcher<TranscriptionGenerateInput, TranscriptionResult>
|
|
38
|
-
/**
|
|
39
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
40
|
-
*/
|
|
41
|
-
id?: string
|
|
42
38
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
43
39
|
body?: Record<string, any>
|
|
44
40
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -117,7 +113,7 @@ export interface UseTranscriptionReturn<
|
|
|
117
113
|
export function useTranscription<TTransformed = void>(
|
|
118
114
|
options: Omit<
|
|
119
115
|
UseTranscriptionOptions,
|
|
120
|
-
'onResult' | 'persistence' | 'threadId'
|
|
116
|
+
'onResult' | 'persistence' | 'threadId'
|
|
121
117
|
> & {
|
|
122
118
|
onResult?: (result: TranscriptionResult) => TTransformed
|
|
123
119
|
} & GenerationPersistenceOptions,
|