@ai-sdk/vue 4.0.166 → 4.0.169

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # @ai-sdk/vue
2
2
 
3
+ ## 4.0.169
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [4311fa1]
8
+ - Updated dependencies [4311fa1]
9
+ - Updated dependencies [d9dd2b7]
10
+ - @ai-sdk/provider-utils@5.0.79
11
+ - ai@7.0.169
12
+
13
+ ## 4.0.168
14
+
15
+ ### Patch Changes
16
+
17
+ - 65aa669: add experimental_queue to useChat to queue messages sent while a response is in progress
18
+ - Updated dependencies [65aa669]
19
+ - Updated dependencies [8585d7e]
20
+ - Updated dependencies [88b9575]
21
+ - ai@7.0.168
22
+ - @ai-sdk/provider-utils@5.0.78
23
+
24
+ ## 4.0.167
25
+
26
+ ### Patch Changes
27
+
28
+ - Updated dependencies [9f37b45]
29
+ - Updated dependencies [404ce3b]
30
+ - @ai-sdk/provider-utils@5.0.77
31
+ - ai@7.0.167
32
+
3
33
  ## 4.0.166
4
34
 
5
35
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -92,7 +92,7 @@ export declare class Chat<UI_MESSAGE extends UIMessage> extends AbstractChat<UI_
92
92
  * Return type of the {@link useChat} composable, which includes the chat
93
93
  * instance methods and reactive properties for messages, status, and error.
94
94
  */
95
- interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<AbstractChat<UI_MESSAGE>, 'sendMessage' | 'regenerate' | 'stop' | 'resumeStream' | 'addToolOutput' | 'addToolApprovalResponse' | 'clearError'> {
95
+ interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<AbstractChat<UI_MESSAGE>, 'sendMessage' | 'regenerate' | 'stop' | 'resumeStream' | 'addToolOutput' | 'addToolApprovalResponse' | 'clearError' | 'experimental_removeQueuedMessage' | 'experimental_sendQueuedMessageNow'> {
96
96
  /**
97
97
  * The id of the chat.
98
98
  */
@@ -109,6 +109,11 @@ interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<AbstractChat
109
109
  * The list of messages in the chat, which can be updated by the chat instance methods or directly by setting this property.
110
110
  */
111
111
  messages: ShallowRef<UI_MESSAGE[]>;
112
+ /**
113
+ * Experimental. Messages that wait to be sent when `experimental_queue` is
114
+ * enabled, in the order they will be sent.
115
+ */
116
+ experimental_queuedMessages: ShallowRef<UI_MESSAGE[]>;
112
117
  }
113
118
  type UseChatOptions<UI_MESSAGE extends UIMessage> = ChatInit<UI_MESSAGE> & {
114
119
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["FlexibleSchema","BaseChatInit"],"sources":["../src/use-object.ts","../src/use-completion.ts","../src/chat.vue.ts","../src/use-chat.ts","../src/index.ts"],"mappings":";;;;YAoBY,iBAAiB,eAAeA,kBAAgB;;EAE1D;;EAGA,QAAQ;;EAGR;;EAGA,eAAe,YAAY;;EAG3B,QAAQ;;EAGR,YAAY;IACV,QAAQ;IACR,OAAO;QACH;;EAGN,WAAW,OAAO;;EAGlB,UAAU,yBAAyB;;EAGnC,cAAc;;YAGJ,iBAAiB,QAAQ;;EAEnC,SAAS,OAAO;;EAGhB,QAAQ,IAAI,YAAY;;EAGxB,OAAO,IAAI;;EAGX,WAAW;;EAGX;;EAGA;;wBASc,UACd,eAAeA,kBACf,SAAS,YAAY,SACrB,eAEA,KACA,IACA,QACA,cACA,OACA,SACA,UACA,SACA,eACC,iBAAiB,QAAQ,UAAU,iBAAiB,QAAQ;;;YClFnD,qBAAqB;;EAE/B,YAAY;;EAEZ,OAAO,gBAAgB;;;;EAIvB,WACE,gBACA,UAAU,yBAAyB,UAChC;;;;EAIL;;;;EAIA,gBAAgB;;EAEhB,OAAO;;;;;;;;;;EAUP,eAAe;IAAU;;;EAEzB,WAAW;;wBASG,cAAc,gCAC5B,KACA,IACA,mBACA,cACA,aACA,SACA,MACA,gBACA,UACA,SACA,UACC,qBAAqB,QAAQ,SAAc,qBAAqB;;;;;;;qBCDtD,KACX,mBAAmB,mBACX,aAAa;EACT,cAAE,aAAa,QAAQ,SAAS;;;;;;;;UC8N7B,eAAe,mBAAmB,mBAAmB,KACpE,aAAa;;;;EAYb,IAAI;;;;EAKJ,OAAO,WAAW;;;;EAKlB,QAAQ,WAAW;;;;EAKnB,UAAU,WAAW;;KAGX,eAAe,mBAAmB,aAC5CC,SAAa;;;;;;EAMX;;;;;;;;;;;;;;;;;;wBAmBY,QAAQ,mBAAmB,YAAY,WACrD,OAAO,iBAAiB,eAAe,eACtC,eAAe;;;;;;qBCxUL,+BAAsB;;;;YAKvB,8BACV,eAAe,gBACf,UACE,iBAAiB,QAAQ;;;;YAKjB,8BAA8B,QAAQ,SAAS,iBACzD,QACA"}
1
+ {"version":3,"file":"index.d.ts","names":["FlexibleSchema","BaseChatInit"],"sources":["../src/use-object.ts","../src/use-completion.ts","../src/chat.vue.ts","../src/use-chat.ts","../src/index.ts"],"mappings":";;;;YAoBY,iBAAiB,eAAeA,kBAAgB;;EAE1D;;EAGA,QAAQ;;EAGR;;EAGA,eAAe,YAAY;;EAG3B,QAAQ;;EAGR,YAAY;IACV,QAAQ;IACR,OAAO;QACH;;EAGN,WAAW,OAAO;;EAGlB,UAAU,yBAAyB;;EAGnC,cAAc;;YAGJ,iBAAiB,QAAQ;;EAEnC,SAAS,OAAO;;EAGhB,QAAQ,IAAI,YAAY;;EAGxB,OAAO,IAAI;;EAGX,WAAW;;EAGX;;EAGA;;wBASc,UACd,eAAeA,kBACf,SAAS,YAAY,SACrB,eAEA,KACA,IACA,QACA,cACA,OACA,SACA,UACA,SACA,eACC,iBAAiB,QAAQ,UAAU,iBAAiB,QAAQ;;;YClFnD,qBAAqB;;EAE/B,YAAY;;EAEZ,OAAO,gBAAgB;;;;EAIvB,WACE,gBACA,UAAU,yBAAyB,UAChC;;;;EAIL;;;;EAIA,gBAAgB;;EAEhB,OAAO;;;;;;;;;;EAUP,eAAe;IAAU;;;EAEzB,WAAW;;wBASG,cAAc,gCAC5B,KACA,IACA,mBACA,cACA,aACA,SACA,MACA,gBACA,UACA,SACA,UACC,qBAAqB,QAAQ,SAAc,qBAAqB;;;;;;;qBCQtD,KACX,mBAAmB,mBACX,aAAa;EACT,cAAE,aAAa,QAAQ,SAAS;;;;;;;;UCuO7B,eAAe,mBAAmB,mBAAmB,KACpE,aAAa;;;;EAcb,IAAI;;;;EAKJ,OAAO,WAAW;;;;EAKlB,QAAQ,WAAW;;;;EAKnB,UAAU,WAAW;;;;;EAMrB,6BAA6B,WAAW;;KAG9B,eAAe,mBAAmB,aAC5CC,SAAa;;;;;;EAMX;;;;;;;;;;;;;;;;;;wBAmBY,QAAQ,mBAAmB,YAAY,WACrD,OAAO,iBAAiB,eAAe,eACtC,eAAe;;;;;;qBClWL,+BAAsB;;;;YAKvB,8BACV,eAAe,gBACf,UACE,iBAAiB,QAAQ;;;;YAKjB,8BAA8B,QAAQ,SAAS,iBACzD,QACA"}
package/dist/index.js CHANGED
@@ -188,6 +188,7 @@ var VueChatState$1 = class {
188
188
  constructor(messages) {
189
189
  this.statusRef = ref("ready");
190
190
  this.errorRef = ref(void 0);
191
+ this.queuedMessagesRef = ref([]);
191
192
  this.pushMessage = (message) => {
192
193
  this.messagesRef.value = [...this.messagesRef.value, message];
193
194
  };
@@ -218,6 +219,12 @@ var VueChatState$1 = class {
218
219
  set error(error) {
219
220
  this.errorRef.value = error;
220
221
  }
222
+ get experimental_queuedMessages() {
223
+ return this.queuedMessagesRef.value;
224
+ }
225
+ set experimental_queuedMessages(experimental_queuedMessages) {
226
+ this.queuedMessagesRef.value = experimental_queuedMessages;
227
+ }
221
228
  };
222
229
  /**
223
230
  * @deprecated Use the {@link useChat} composable instead. It exposes reactive
@@ -249,11 +256,12 @@ function snapshotValue(value) {
249
256
  return snapshot;
250
257
  }
251
258
  var VueChatState = class {
252
- constructor({ initialMessages, messagesRef, statusRef, errorRef, throttleWaitMs }) {
259
+ constructor({ initialMessages, messagesRef, statusRef, errorRef, queuedMessagesRef, throttleWaitMs }) {
253
260
  this.publishedMessages = [];
254
261
  this.publishedMessageSources = [];
255
262
  this.dirtyMessageIndices = /* @__PURE__ */ new Set();
256
263
  this.statusValue = "ready";
264
+ this.queuedMessagesValue = [];
257
265
  this.hasPendingPublication = false;
258
266
  this.isActive = true;
259
267
  this.isPublishing = false;
@@ -283,6 +291,7 @@ var VueChatState = class {
283
291
  this.messagesRef = messagesRef;
284
292
  this.statusRef = statusRef;
285
293
  this.errorRef = errorRef;
294
+ this.queuedMessagesRef = queuedMessagesRef;
286
295
  this.throttleWaitMs = throttleWaitMs != null && Number.isFinite(throttleWaitMs) && throttleWaitMs > 0 ? throttleWaitMs : void 0;
287
296
  }
288
297
  get messages() {
@@ -310,10 +319,18 @@ var VueChatState = class {
310
319
  this.errorValue = error;
311
320
  if (this.isActive) this.errorRef.value = error;
312
321
  }
322
+ get experimental_queuedMessages() {
323
+ return this.queuedMessagesValue;
324
+ }
325
+ set experimental_queuedMessages(experimental_queuedMessages) {
326
+ this.queuedMessagesValue = experimental_queuedMessages;
327
+ if (this.isActive) this.queuedMessagesRef.value = experimental_queuedMessages;
328
+ }
313
329
  publishInitialState() {
314
330
  this.publishMessages();
315
331
  this.statusRef.value = this.statusValue;
316
332
  this.errorRef.value = this.errorValue;
333
+ this.queuedMessagesRef.value = this.queuedMessagesValue;
317
334
  }
318
335
  setMessagesFromConsumer(messages) {
319
336
  this.messagesValue = messages;
@@ -396,6 +413,7 @@ function useChat(init) {
396
413
  const messages = shallowRef([]);
397
414
  const status = shallowRef("ready");
398
415
  const error = shallowRef();
416
+ const experimental_queuedMessages = shallowRef([]);
399
417
  const chatInstance = shallowRef();
400
418
  let chatState;
401
419
  watch(messages, (messageList) => {
@@ -409,6 +427,7 @@ function useChat(init) {
409
427
  messagesRef: messages,
410
428
  statusRef: status,
411
429
  errorRef: error,
430
+ queuedMessagesRef: experimental_queuedMessages,
412
431
  throttleWaitMs: throttle
413
432
  });
414
433
  chatState = nextChatState;
@@ -432,7 +451,10 @@ function useChat(init) {
432
451
  regenerate: (opts) => chatInstance.value.regenerate(opts),
433
452
  sendMessage: (...args) => chatInstance.value.sendMessage(...args),
434
453
  stop: () => chatInstance.value.stop(),
435
- resumeStream: (opts) => chatInstance.value.resumeStream(opts)
454
+ resumeStream: (opts) => chatInstance.value.resumeStream(opts),
455
+ experimental_queuedMessages,
456
+ experimental_removeQueuedMessage: (id) => chatInstance.value.experimental_removeQueuedMessage(id),
457
+ experimental_sendQueuedMessageNow: (id) => chatInstance.value.experimental_sendQueuedMessageNow(id)
436
458
  };
437
459
  }
438
460
  //#endregion
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["uniqueId","useSWRV","store","VueChatState"],"sources":["../src/use-object.ts","../src/use-completion.ts","../src/chat.vue.ts","../src/use-chat.ts","../src/index.ts"],"sourcesContent":["import {\n isAbortError,\n normalizeHeaders,\n safeValidateTypes,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n isDeepEqualData,\n parsePartialJson,\n type DeepPartial,\n type FlexibleSchema,\n type InferSchema,\n} from 'ai';\nimport type * as SwrvModule from 'swrv';\nimport swrv from 'swrv';\nimport { ref, type Ref } from 'vue';\n// use function to allow for mocking in tests\nconst getOriginalFetch = () => fetch;\n\nexport type UseObjectOptions<SCHEMA extends FlexibleSchema, RESULT> = {\n /** API endpoint that streams JSON chunks matching the schema */\n api: string;\n\n /** Schema that defines the final object shape */\n schema: SCHEMA;\n\n /** Shared state key. If omitted a random one is generated */\n id?: string;\n\n /** Initial partial value */\n initialValue?: DeepPartial<RESULT>;\n\n /** Optional custom fetch implementation */\n fetch?: FetchFunction;\n\n /** Called when stream ends */\n onFinish?: (event: {\n object: RESULT | undefined;\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /** Called on error */\n onError?: (error: Error) => void;\n\n /** Extra request headers */\n headers?: Record<string, string> | Headers;\n\n /** Request credentials mode. Defaults to 'same-origin' if omitted */\n credentials?: RequestCredentials;\n};\n\nexport type UseObjectHelpers<RESULT, INPUT> = {\n /** POST the input and start streaming */\n submit: (input: INPUT) => void;\n\n /** Current partial object, updated as chunks arrive */\n object: Ref<DeepPartial<RESULT> | undefined>;\n\n /** Latest error if any */\n error: Ref<Error | undefined>;\n\n /** Loading flag for the in-flight request */\n isLoading: Ref<boolean | undefined>;\n\n /** Abort the current request. Keeps current partial object. */\n stop: () => void;\n\n /** Abort and clear all state */\n clear: () => void;\n};\n\nlet uniqueId = 0;\n\n// @ts-expect-error - some issues with the default export of useSWRV\nconst useSWRV = (swrv.default as (typeof SwrvModule)['default']) || swrv;\nconst store: Record<string, any> = {};\n\nexport function useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema,\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: UseObjectOptions<SCHEMA, RESULT>): UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id for the object if not provided.\n const completionId = id || `completion-${uniqueId++}`;\n\n const key = `${api}|${completionId}`;\n const { data, mutate: originalMutate } = useSWRV<\n DeepPartial<RESULT> | undefined\n >(key, () => (key in store ? store[key] : initialValue));\n\n const { data: isLoading, mutate: mutateLoading } = useSWRV<boolean>(\n `${completionId}-loading`,\n null,\n );\n\n isLoading.value ??= false;\n data.value ||= initialValue as DeepPartial<RESULT> | undefined;\n\n const mutateObject = (value: DeepPartial<RESULT> | undefined) => {\n store[key] = value;\n return originalMutate();\n };\n\n const error = ref<Error | undefined>(undefined);\n let abortController: AbortController | null = null;\n\n const stop = async () => {\n if (abortController) {\n try {\n abortController.abort();\n } catch {\n // ignore\n } finally {\n abortController = null;\n }\n }\n await mutateLoading(() => false);\n };\n\n const clearObject = async () => {\n error.value = undefined;\n await mutateLoading(() => false);\n await mutateObject(undefined);\n // Need to explicitly set the value to undefined to trigger a re-render\n data.value = undefined;\n };\n\n const clear = async () => {\n await stop();\n await clearObject();\n };\n\n const submit = async (input: INPUT) => {\n const currentAbortController = new AbortController();\n abortController = currentAbortController;\n\n try {\n await clearObject();\n\n if (currentAbortController.signal.aborted) {\n return;\n }\n\n await mutateLoading(() => true);\n\n if (currentAbortController.signal.aborted) {\n if (abortController === null) {\n await mutateLoading(() => false);\n }\n return;\n }\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...normalizeHeaders(headers),\n },\n credentials: credentials ?? 'same-origin',\n signal: currentAbortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) || 'Failed to fetch the response.',\n );\n }\n\n if (!response.body) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n await mutateObject(currentObject);\n }\n },\n async close() {\n if (abortController === currentAbortController) {\n abortController = null;\n await mutateLoading(() => false);\n }\n\n if (onFinish) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? {\n object: validationResult.value as RESULT,\n error: undefined,\n }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (err: unknown) {\n if (isAbortError(err)) return;\n\n if (onError && err instanceof Error) onError(err);\n\n await mutateLoading(() => false);\n error.value = err instanceof Error ? err : new Error(String(err));\n }\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n","import {\n callCompletionApi,\n type CompletionRequestOptions,\n type UseCompletionOptions,\n} from 'ai';\nimport type * as SwrvModule from 'swrv';\nimport swrv from 'swrv';\nimport { ref, unref, type Ref } from 'vue';\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers<BODY extends object = object> = {\n /** The current completion result */\n completion: Ref<string>;\n /** The error object of the API request */\n error: Ref<undefined | Error>;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions<BODY>,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: Ref<string>;\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form @submit=\"handleSubmit\">\n * <input @change=\"handleInputChange\" v-model=\"input\" />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n /** Whether the API request is in progress */\n isLoading: Ref<boolean | undefined>;\n};\n\nlet uniqueId = 0;\n\n// @ts-expect-error - some issues with the default export of useSWRV\nconst useSWRV = (swrv.default as (typeof SwrvModule)['default']) || swrv;\nconst store: Record<string, any> = {};\n\nexport function useCompletion<BODY extends object = object>({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol,\n onFinish,\n onError,\n fetch,\n}: UseCompletionOptions<NoInfer<BODY>> = {}): UseCompletionHelpers<BODY> {\n // Generate an unique id for the completion if not provided.\n const completionId = id || `completion-${uniqueId++}`;\n\n const key = `${api}|${completionId}`;\n const { data, mutate: originalMutate } = useSWRV<string>(\n key,\n () => store[key] ?? initialCompletion,\n );\n\n const { data: isLoading, mutate: mutateLoading } = useSWRV<boolean>(\n `${completionId}-loading`,\n null,\n );\n\n isLoading.value ??= false;\n\n // Force the `data` to be `initialCompletion` if it's `undefined`.\n data.value ??= initialCompletion;\n\n const mutate = (data: string) => {\n store[key] = data;\n return originalMutate();\n };\n\n // Because of the `initialData` option, the `data` will never be `undefined`.\n const completion = data as Ref<string>;\n\n const error = ref<undefined | Error>(undefined);\n\n let abortController: AbortController | null = null;\n\n async function triggerRequest(\n prompt: string,\n options?: CompletionRequestOptions<BODY>,\n ) {\n return callCompletionApi({\n api,\n prompt,\n credentials,\n headers: {\n ...headers,\n ...options?.headers,\n },\n body: {\n ...unref(body),\n ...options?.body,\n },\n streamProtocol,\n setCompletion: mutate,\n setLoading: loading => mutateLoading(() => loading),\n setError: err => {\n error.value = err;\n },\n setAbortController: controller => {\n abortController = controller;\n },\n getAbortController: () => abortController,\n onFinish,\n onError,\n fetch,\n });\n }\n\n const complete: UseCompletionHelpers<BODY>['complete'] = async (\n prompt,\n options,\n ) => {\n return triggerRequest(prompt, options);\n };\n\n const stop = () => {\n if (abortController) {\n abortController.abort();\n }\n };\n\n const setCompletion = (completion: string) => {\n mutate(completion);\n };\n\n const input = ref(initialInput);\n\n const handleSubmit = (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n const inputValue = input.value;\n return inputValue ? complete(inputValue) : undefined;\n };\n\n return {\n completion,\n complete,\n error,\n stop,\n setCompletion,\n input,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n AbstractChat,\n type ChatInit,\n type ChatState,\n type ChatStatus,\n type UIMessage,\n} from 'ai';\nimport { ref, type Ref } from 'vue';\nclass VueChatState<\n UI_MESSAGE extends UIMessage,\n> implements ChatState<UI_MESSAGE> {\n private messagesRef: Ref<UI_MESSAGE[]>;\n private statusRef = ref<ChatStatus>('ready');\n private errorRef = ref<Error | undefined>(undefined);\n\n constructor(messages?: UI_MESSAGE[]) {\n this.messagesRef = ref(messages ?? []) as Ref<UI_MESSAGE[]>;\n }\n\n get messages(): UI_MESSAGE[] {\n return this.messagesRef.value;\n }\n\n set messages(messages: UI_MESSAGE[]) {\n this.messagesRef.value = messages;\n }\n\n get status(): ChatStatus {\n return this.statusRef.value;\n }\n\n set status(status: ChatStatus) {\n this.statusRef.value = status;\n }\n\n get error(): Error | undefined {\n return this.errorRef.value;\n }\n\n set error(error: Error | undefined) {\n this.errorRef.value = error;\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.messagesRef.value = [...this.messagesRef.value, message];\n };\n\n popMessage = () => {\n this.messagesRef.value = this.messagesRef.value.slice(0, -1);\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n // message is cloned here because vue's deep reactivity shows unexpected behavior, particularly when updating tool invocation parts\n this.messagesRef.value[index] = { ...message };\n };\n\n snapshot = <T>(value: T): T => value;\n}\n\n/**\n * @deprecated Use the {@link useChat} composable instead. It exposes reactive\n * refs and automatically recreates the chat when its init object changes.\n */\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n super({\n ...init,\n state: new VueChatState(messages),\n });\n }\n}\n","import {\n AbstractChat,\n type ChatInit as BaseChatInit,\n type ChatInit,\n type ChatState,\n type ChatStatus,\n type UIMessage,\n} from 'ai';\nimport {\n computed,\n getCurrentScope,\n onScopeDispose,\n shallowRef,\n toValue,\n watch,\n type ComputedRef,\n type MaybeRefOrGetter,\n type ShallowRef,\n} from 'vue';\n\nfunction cloneMetadata<METADATA>(metadata: METADATA): METADATA {\n if (Array.isArray(metadata)) {\n return [...metadata] as METADATA;\n }\n\n if (\n metadata != null &&\n typeof metadata === 'object' &&\n (Object.getPrototypeOf(metadata) === Object.prototype ||\n Object.getPrototypeOf(metadata) === null)\n ) {\n return { ...metadata } as METADATA;\n }\n\n return metadata;\n}\n\nfunction snapshotValue<T>(value: T): T {\n if (\n value == null ||\n typeof value !== 'object' ||\n !('parts' in value) ||\n !Array.isArray(value.parts)\n ) {\n return value;\n }\n\n const message = value as unknown as UIMessage;\n const snapshot = {\n ...message,\n parts: message.parts.map(part => ({ ...part })),\n };\n\n if ('metadata' in message) {\n snapshot.metadata = cloneMetadata(message.metadata);\n }\n\n return snapshot as T;\n}\n\nclass VueChatState<\n UI_MESSAGE extends UIMessage,\n> implements ChatState<UI_MESSAGE> {\n private messagesValue: UI_MESSAGE[];\n private publishedMessages: UI_MESSAGE[] = [];\n private publishedMessageSources: UI_MESSAGE[] = [];\n private readonly dirtyMessageIndices = new Set<number>();\n private statusValue: ChatStatus = 'ready';\n private errorValue: Error | undefined;\n private readonly throttleWaitMs: number | undefined;\n private timeout: ReturnType<typeof setTimeout> | undefined;\n private hasPendingPublication = false;\n private isActive = true;\n\n isPublishing = false;\n\n constructor({\n initialMessages,\n messagesRef,\n statusRef,\n errorRef,\n throttleWaitMs,\n }: {\n initialMessages: UI_MESSAGE[];\n messagesRef: ShallowRef<UI_MESSAGE[]>;\n statusRef: ShallowRef<ChatStatus>;\n errorRef: ShallowRef<Error | undefined>;\n throttleWaitMs?: number;\n }) {\n this.messagesValue = initialMessages;\n this.messagesRef = messagesRef;\n this.statusRef = statusRef;\n this.errorRef = errorRef;\n this.throttleWaitMs =\n throttleWaitMs != null &&\n Number.isFinite(throttleWaitMs) &&\n throttleWaitMs > 0\n ? throttleWaitMs\n : undefined;\n }\n\n private readonly messagesRef: ShallowRef<UI_MESSAGE[]>;\n private readonly statusRef: ShallowRef<ChatStatus>;\n private readonly errorRef: ShallowRef<Error | undefined>;\n\n get messages(): UI_MESSAGE[] {\n return this.messagesValue;\n }\n\n set messages(messages: UI_MESSAGE[]) {\n const previousMessages = this.messagesValue;\n this.messagesValue = messages;\n\n for (let index = 0; index < messages.length; index++) {\n if (messages[index] !== previousMessages[index]) {\n this.dirtyMessageIndices.add(index);\n }\n }\n\n this.schedulePublication();\n }\n\n get status(): ChatStatus {\n return this.statusValue;\n }\n\n set status(status: ChatStatus) {\n this.statusValue = status;\n\n if (!this.isActive) {\n return;\n }\n\n if (status === 'ready' || status === 'error') {\n // Terminal states must never become observable before the final message.\n this.flushPublication();\n }\n\n this.statusRef.value = status;\n }\n\n get error(): Error | undefined {\n return this.errorValue;\n }\n\n set error(error: Error | undefined) {\n this.errorValue = error;\n\n if (this.isActive) {\n this.errorRef.value = error;\n }\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.messagesValue.push(message);\n this.dirtyMessageIndices.add(this.messagesValue.length - 1);\n this.schedulePublication();\n };\n\n popMessage = () => {\n this.messagesValue.pop();\n this.schedulePublication();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.messagesValue[index] = message;\n this.dirtyMessageIndices.add(index);\n this.schedulePublication();\n };\n\n snapshot = snapshotValue;\n\n publishInitialState() {\n this.publishMessages();\n this.statusRef.value = this.statusValue;\n this.errorRef.value = this.errorValue;\n }\n\n setMessagesFromConsumer(messages: UI_MESSAGE[]) {\n this.messagesValue = messages;\n this.publishedMessages = messages;\n this.publishedMessageSources = messages;\n this.dirtyMessageIndices.clear();\n }\n\n dispose() {\n this.isActive = false;\n this.hasPendingPublication = false;\n this.dirtyMessageIndices.clear();\n this.publishedMessages = [];\n this.publishedMessageSources = [];\n\n if (this.timeout != null) {\n clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n }\n\n private schedulePublication() {\n if (!this.isActive) {\n return;\n }\n\n if (this.throttleWaitMs == null) {\n this.publishMessages();\n return;\n }\n\n if (this.timeout == null) {\n // Publish the leading update immediately, then coalesce updates until\n // the next interval boundary.\n this.publishMessages();\n this.timeout = setTimeout(this.handleIntervalEnd, this.throttleWaitMs);\n } else {\n this.hasPendingPublication = true;\n }\n }\n\n private readonly handleIntervalEnd = () => {\n this.timeout = undefined;\n\n if (!this.isActive || !this.hasPendingPublication) {\n return;\n }\n\n this.hasPendingPublication = false;\n this.publishMessages();\n this.timeout = setTimeout(this.handleIntervalEnd, this.throttleWaitMs);\n };\n\n private flushPublication() {\n if (this.timeout != null) {\n clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n\n this.hasPendingPublication = false;\n this.publishMessages();\n }\n\n private publishMessages() {\n if (!this.isActive) {\n return;\n }\n\n const publishedMessages = this.messagesValue.map((message, index) =>\n this.dirtyMessageIndices.has(index) ||\n this.publishedMessageSources[index] !== message\n ? snapshotValue(message)\n : this.publishedMessages[index],\n );\n\n this.publishedMessages = publishedMessages;\n this.publishedMessageSources = [...this.messagesValue];\n this.dirtyMessageIndices.clear();\n\n this.isPublishing = true;\n try {\n this.messagesRef.value = publishedMessages;\n } finally {\n this.isPublishing = false;\n }\n }\n}\n\n/**\n * @internal\n */\nexport class VueChat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n constructor({\n state,\n ...init\n }: Omit<ChatInit<UI_MESSAGE>, 'messages'> & {\n state: ChatState<UI_MESSAGE>;\n }) {\n super({\n ...init,\n state,\n });\n }\n}\n\n/**\n * Return type of the {@link useChat} composable, which includes the chat\n * instance methods and reactive properties for messages, status, and error.\n */\nexport interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'clearError'\n> {\n /**\n * The id of the chat.\n */\n id: ComputedRef<string>;\n\n /**\n * The current error state of the chat, if any.\n */\n error: ShallowRef<Error | undefined>;\n\n /**\n * The current status of the chat, which can be 'ready', 'generating', 'streaming', or 'error'.\n */\n status: ShallowRef<ChatStatus>;\n\n /**\n * The list of messages in the chat, which can be updated by the chat instance methods or directly by setting this property.\n */\n messages: ShallowRef<UI_MESSAGE[]>;\n}\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> =\n BaseChatInit<UI_MESSAGE> & {\n /**\n * Custom throttle wait time in milliseconds for reactive message updates.\n * Positive values enable throttling. Defaults to undefined, which disables\n * throttling.\n */\n throttle?: number;\n };\n\n/**\n * Composable to access messages, status, and other chat properties and\n * methods. Accepts an optional reactive initial configuration object\n *\n * @example\n *\n * ```ts\n * // passing a getter if any reactive properties are used within\n * // the init object\n * const { messages, sendMessage } = useChat(() => ({\n * // ...\n * })\n * ```\n *\n * @see BaseChatInit\n */\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>(\n init?: MaybeRefOrGetter<UseChatOptions<UI_MESSAGE>>,\n): UseChatHelpers<UI_MESSAGE> {\n const messages = shallowRef<UI_MESSAGE[]>([]);\n const status = shallowRef<ChatStatus>('ready');\n const error = shallowRef<Error | undefined>();\n\n // the instance is created right away thanks to immediate: true. We do it this\n // way instead of a computed to ensure all changes to reactive state happen\n // in the same tick\n const chatInstance = shallowRef<VueChat<UI_MESSAGE>>() as ShallowRef<\n VueChat<UI_MESSAGE>\n >;\n let chatState: VueChatState<UI_MESSAGE> | undefined;\n\n watch(\n messages,\n messageList => {\n if (chatState != null && !chatState.isPublishing) {\n chatState.setMessagesFromConsumer(messageList);\n }\n },\n { flush: 'sync' },\n );\n\n watch(\n () => toValue(init),\n opts => {\n chatState?.dispose();\n\n const { throttle, ...chatInit } = opts ?? {};\n const nextChatState = new VueChatState<UI_MESSAGE>({\n initialMessages: chatInit.messages ?? [],\n messagesRef: messages,\n statusRef: status,\n errorRef: error,\n throttleWaitMs: throttle,\n });\n\n chatState = nextChatState;\n nextChatState.publishInitialState();\n\n chatInstance.value = new VueChat<UI_MESSAGE>({\n ...chatInit,\n state: nextChatState,\n });\n },\n { immediate: true },\n );\n\n if (getCurrentScope() != null) {\n onScopeDispose(() => {\n chatState?.dispose();\n });\n }\n\n return {\n id: computed(() => chatInstance.value.id),\n status,\n messages,\n error,\n addToolApprovalResponse: opts =>\n chatInstance.value.addToolApprovalResponse(opts),\n addToolOutput: opts => chatInstance.value.addToolOutput(opts),\n clearError: () => chatInstance.value.clearError(),\n regenerate: opts => chatInstance.value.regenerate(opts),\n sendMessage: (...args) => chatInstance.value.sendMessage(...args),\n stop: () => chatInstance.value.stop(),\n resumeStream: opts => chatInstance.value.resumeStream(opts),\n };\n}\n","import type { FlexibleSchema } from '@ai-sdk/provider-utils';\nimport {\n useObject,\n type UseObjectHelpers,\n type UseObjectOptions,\n} from './use-object';\n\nexport * from './use-completion';\nexport { Chat } from './chat.vue';\nexport { useChat, type UseChatHelpers, type UseChatOptions } from './use-chat';\nexport * from './use-object';\n\n// deprecated aliases\n// note: declared here (instead of export aliases) so that the `@deprecated`\n// tags are preserved in the bundled type declarations\n\n/**\n * @deprecated Use `useObject` instead.\n */\nexport const experimental_useObject = useObject;\n\n/**\n * @deprecated Use `UseObjectOptions` instead.\n */\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = UseObjectOptions<SCHEMA, RESULT>;\n\n/**\n * @deprecated Use `UseObjectHelpers` instead.\n */\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = UseObjectHelpers<\n RESULT,\n INPUT\n>;\n"],"mappings":";;;;;AAkBA,MAAM,yBAAyB;AAsD/B,IAAIA,aAAW;AAGf,MAAMC,YAAW,KAAK,WAA8C;AACpE,MAAMC,UAA6B,CAAC;AAEpC,SAAgB,UAId,EACA,KACA,IACA,QACA,cACA,OACA,SACA,UACA,SACA,eACoE;CAEpE,MAAM,eAAe,MAAM,cAAc;CAEzC,MAAM,MAAM,GAAG,IAAI,GAAG;CACtB,MAAM,EAAE,MAAM,QAAQ,mBAAmBD,UAEvC,WAAY,OAAOC,UAAQA,QAAM,OAAO,YAAa;CAEvD,MAAM,EAAE,MAAM,WAAW,QAAQ,kBAAkBD,UACjD,GAAG,aAAa,WAChB,IACF;CAEA,UAAU,UAAU;CACpB,KAAK,UAAU;CAEf,MAAM,gBAAgB,UAA2C;EAC/D,QAAM,OAAO;EACb,OAAO,eAAe;CACxB;CAEA,MAAM,QAAQ,IAAuB,KAAA,CAAS;CAC9C,IAAI,kBAA0C;CAE9C,MAAM,OAAO,YAAY;EACvB,IAAI,iBACF,IAAI;GACF,gBAAgB,MAAM;EACxB,QAAQ,CAER,UAAU;GACR,kBAAkB;EACpB;EAEF,MAAM,oBAAoB,KAAK;CACjC;CAEA,MAAM,cAAc,YAAY;EAC9B,MAAM,QAAQ,KAAA;EACd,MAAM,oBAAoB,KAAK;EAC/B,MAAM,aAAa,KAAA,CAAS;EAE5B,KAAK,QAAQ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,WAAyB,CAAC,CAAC;CAC5C,MAAM,SAAS,WAAuB,OAAO;CAC7C,MAAM,QAAQ,WAA8B;CAK5C,MAAM,eAAe,WAAgC;CAGrD,IAAI;CAEJ,MACE,WACA,gBAAe;EACb,IAAI,aAAa,QAAQ,CAAC,UAAU,cAClC,UAAU,wBAAwB,WAAW;CAEjD,GACA,EAAE,OAAO,OAAO,CAClB;CAEA,YACQ,QAAQ,IAAI,IAClB,SAAQ;EACN,WAAW,QAAQ;EAEnB,MAAM,EAAE,UAAU,GAAG,aAAa,QAAQ,CAAC;EAC3C,MAAM,gBAAgB,IAAI,aAAyB;GACjD,iBAAiB,SAAS,YAAY,CAAC;GACvC,aAAa;GACb,WAAW;GACX,UAAU;GACV,gBAAgB;EAClB,CAAC;EAED,YAAY;EACZ,cAAc,oBAAoB;EAElC,aAAa,QAAQ,IAAI,QAAoB;GAC3C,GAAG;GACH,OAAO;EACT,CAAC;CACH,GACA,EAAE,WAAW,KAAK,CACpB;CAEA,IAAI,gBAAgB,KAAK,MACvB,qBAAqB;EACnB,WAAW,QAAQ;CACrB,CAAC;CAGH,OAAO;EACL,IAAI,eAAe,aAAa,MAAM,EAAE;EACxC;EACA;EACA;EACA,0BAAyB,SACvB,aAAa,MAAM,wBAAwB,IAAI;EACjD,gBAAe,SAAQ,aAAa,MAAM,cAAc,IAAI;EAC5D,kBAAkB,aAAa,MAAM,WAAW;EAChD,aAAY,SAAQ,aAAa,MAAM,WAAW,IAAI;EACtD,cAAc,GAAG,SAAS,aAAa,MAAM,YAAY,GAAG,IAAI;EAChE,YAAY,aAAa,MAAM,KAAK;EACpC,eAAc,SAAQ,aAAa,MAAM,aAAa,IAAI;CAC5D;AACF;;;;;;AC5YA,MAAa,yBAAyB"}
1
+ {"version":3,"file":"index.js","names":["uniqueId","useSWRV","store","VueChatState"],"sources":["../src/use-object.ts","../src/use-completion.ts","../src/chat.vue.ts","../src/use-chat.ts","../src/index.ts"],"sourcesContent":["import {\n isAbortError,\n normalizeHeaders,\n safeValidateTypes,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n isDeepEqualData,\n parsePartialJson,\n type DeepPartial,\n type FlexibleSchema,\n type InferSchema,\n} from 'ai';\nimport type * as SwrvModule from 'swrv';\nimport swrv from 'swrv';\nimport { ref, type Ref } from 'vue';\n// use function to allow for mocking in tests\nconst getOriginalFetch = () => fetch;\n\nexport type UseObjectOptions<SCHEMA extends FlexibleSchema, RESULT> = {\n /** API endpoint that streams JSON chunks matching the schema */\n api: string;\n\n /** Schema that defines the final object shape */\n schema: SCHEMA;\n\n /** Shared state key. If omitted a random one is generated */\n id?: string;\n\n /** Initial partial value */\n initialValue?: DeepPartial<RESULT>;\n\n /** Optional custom fetch implementation */\n fetch?: FetchFunction;\n\n /** Called when stream ends */\n onFinish?: (event: {\n object: RESULT | undefined;\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /** Called on error */\n onError?: (error: Error) => void;\n\n /** Extra request headers */\n headers?: Record<string, string> | Headers;\n\n /** Request credentials mode. Defaults to 'same-origin' if omitted */\n credentials?: RequestCredentials;\n};\n\nexport type UseObjectHelpers<RESULT, INPUT> = {\n /** POST the input and start streaming */\n submit: (input: INPUT) => void;\n\n /** Current partial object, updated as chunks arrive */\n object: Ref<DeepPartial<RESULT> | undefined>;\n\n /** Latest error if any */\n error: Ref<Error | undefined>;\n\n /** Loading flag for the in-flight request */\n isLoading: Ref<boolean | undefined>;\n\n /** Abort the current request. Keeps current partial object. */\n stop: () => void;\n\n /** Abort and clear all state */\n clear: () => void;\n};\n\nlet uniqueId = 0;\n\n// @ts-expect-error - some issues with the default export of useSWRV\nconst useSWRV = (swrv.default as (typeof SwrvModule)['default']) || swrv;\nconst store: Record<string, any> = {};\n\nexport function useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema,\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: UseObjectOptions<SCHEMA, RESULT>): UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id for the object if not provided.\n const completionId = id || `completion-${uniqueId++}`;\n\n const key = `${api}|${completionId}`;\n const { data, mutate: originalMutate } = useSWRV<\n DeepPartial<RESULT> | undefined\n >(key, () => (key in store ? store[key] : initialValue));\n\n const { data: isLoading, mutate: mutateLoading } = useSWRV<boolean>(\n `${completionId}-loading`,\n null,\n );\n\n isLoading.value ??= false;\n data.value ||= initialValue as DeepPartial<RESULT> | undefined;\n\n const mutateObject = (value: DeepPartial<RESULT> | undefined) => {\n store[key] = value;\n return originalMutate();\n };\n\n const error = ref<Error | undefined>(undefined);\n let abortController: AbortController | null = null;\n\n const stop = async () => {\n if (abortController) {\n try {\n abortController.abort();\n } catch {\n // ignore\n } finally {\n abortController = null;\n }\n }\n await mutateLoading(() => false);\n };\n\n const clearObject = async () => {\n error.value = undefined;\n await mutateLoading(() => false);\n await mutateObject(undefined);\n // Need to explicitly set the value to undefined to trigger a re-render\n data.value = undefined;\n };\n\n const clear = async () => {\n await stop();\n await clearObject();\n };\n\n const submit = async (input: INPUT) => {\n const currentAbortController = new AbortController();\n abortController = currentAbortController;\n\n try {\n await clearObject();\n\n if (currentAbortController.signal.aborted) {\n return;\n }\n\n await mutateLoading(() => true);\n\n if (currentAbortController.signal.aborted) {\n if (abortController === null) {\n await mutateLoading(() => false);\n }\n return;\n }\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...normalizeHeaders(headers),\n },\n credentials: credentials ?? 'same-origin',\n signal: currentAbortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) || 'Failed to fetch the response.',\n );\n }\n\n if (!response.body) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n await mutateObject(currentObject);\n }\n },\n async close() {\n if (abortController === currentAbortController) {\n abortController = null;\n await mutateLoading(() => false);\n }\n\n if (onFinish) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? {\n object: validationResult.value as RESULT,\n error: undefined,\n }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (err: unknown) {\n if (isAbortError(err)) return;\n\n if (onError && err instanceof Error) onError(err);\n\n await mutateLoading(() => false);\n error.value = err instanceof Error ? err : new Error(String(err));\n }\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n","import {\n callCompletionApi,\n type CompletionRequestOptions,\n type UseCompletionOptions,\n} from 'ai';\nimport type * as SwrvModule from 'swrv';\nimport swrv from 'swrv';\nimport { ref, unref, type Ref } from 'vue';\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers<BODY extends object = object> = {\n /** The current completion result */\n completion: Ref<string>;\n /** The error object of the API request */\n error: Ref<undefined | Error>;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions<BODY>,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: Ref<string>;\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form @submit=\"handleSubmit\">\n * <input @change=\"handleInputChange\" v-model=\"input\" />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n /** Whether the API request is in progress */\n isLoading: Ref<boolean | undefined>;\n};\n\nlet uniqueId = 0;\n\n// @ts-expect-error - some issues with the default export of useSWRV\nconst useSWRV = (swrv.default as (typeof SwrvModule)['default']) || swrv;\nconst store: Record<string, any> = {};\n\nexport function useCompletion<BODY extends object = object>({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol,\n onFinish,\n onError,\n fetch,\n}: UseCompletionOptions<NoInfer<BODY>> = {}): UseCompletionHelpers<BODY> {\n // Generate an unique id for the completion if not provided.\n const completionId = id || `completion-${uniqueId++}`;\n\n const key = `${api}|${completionId}`;\n const { data, mutate: originalMutate } = useSWRV<string>(\n key,\n () => store[key] ?? initialCompletion,\n );\n\n const { data: isLoading, mutate: mutateLoading } = useSWRV<boolean>(\n `${completionId}-loading`,\n null,\n );\n\n isLoading.value ??= false;\n\n // Force the `data` to be `initialCompletion` if it's `undefined`.\n data.value ??= initialCompletion;\n\n const mutate = (data: string) => {\n store[key] = data;\n return originalMutate();\n };\n\n // Because of the `initialData` option, the `data` will never be `undefined`.\n const completion = data as Ref<string>;\n\n const error = ref<undefined | Error>(undefined);\n\n let abortController: AbortController | null = null;\n\n async function triggerRequest(\n prompt: string,\n options?: CompletionRequestOptions<BODY>,\n ) {\n return callCompletionApi({\n api,\n prompt,\n credentials,\n headers: {\n ...headers,\n ...options?.headers,\n },\n body: {\n ...unref(body),\n ...options?.body,\n },\n streamProtocol,\n setCompletion: mutate,\n setLoading: loading => mutateLoading(() => loading),\n setError: err => {\n error.value = err;\n },\n setAbortController: controller => {\n abortController = controller;\n },\n getAbortController: () => abortController,\n onFinish,\n onError,\n fetch,\n });\n }\n\n const complete: UseCompletionHelpers<BODY>['complete'] = async (\n prompt,\n options,\n ) => {\n return triggerRequest(prompt, options);\n };\n\n const stop = () => {\n if (abortController) {\n abortController.abort();\n }\n };\n\n const setCompletion = (completion: string) => {\n mutate(completion);\n };\n\n const input = ref(initialInput);\n\n const handleSubmit = (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n const inputValue = input.value;\n return inputValue ? complete(inputValue) : undefined;\n };\n\n return {\n completion,\n complete,\n error,\n stop,\n setCompletion,\n input,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n AbstractChat,\n type ChatInit,\n type ChatState,\n type ChatStatus,\n type UIMessage,\n} from 'ai';\nimport { ref, type Ref } from 'vue';\nclass VueChatState<\n UI_MESSAGE extends UIMessage,\n> implements ChatState<UI_MESSAGE> {\n private messagesRef: Ref<UI_MESSAGE[]>;\n private statusRef = ref<ChatStatus>('ready');\n private errorRef = ref<Error | undefined>(undefined);\n private queuedMessagesRef = ref([]) as Ref<UI_MESSAGE[]>;\n\n constructor(messages?: UI_MESSAGE[]) {\n this.messagesRef = ref(messages ?? []) as Ref<UI_MESSAGE[]>;\n }\n\n get messages(): UI_MESSAGE[] {\n return this.messagesRef.value;\n }\n\n set messages(messages: UI_MESSAGE[]) {\n this.messagesRef.value = messages;\n }\n\n get status(): ChatStatus {\n return this.statusRef.value;\n }\n\n set status(status: ChatStatus) {\n this.statusRef.value = status;\n }\n\n get error(): Error | undefined {\n return this.errorRef.value;\n }\n\n set error(error: Error | undefined) {\n this.errorRef.value = error;\n }\n\n get experimental_queuedMessages(): UI_MESSAGE[] {\n return this.queuedMessagesRef.value;\n }\n\n set experimental_queuedMessages(experimental_queuedMessages: UI_MESSAGE[]) {\n this.queuedMessagesRef.value = experimental_queuedMessages;\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.messagesRef.value = [...this.messagesRef.value, message];\n };\n\n popMessage = () => {\n this.messagesRef.value = this.messagesRef.value.slice(0, -1);\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n // message is cloned here because vue's deep reactivity shows unexpected behavior, particularly when updating tool invocation parts\n this.messagesRef.value[index] = { ...message };\n };\n\n snapshot = <T>(value: T): T => value;\n}\n\n/**\n * @deprecated Use the {@link useChat} composable instead. It exposes reactive\n * refs and automatically recreates the chat when its init object changes.\n */\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n super({\n ...init,\n state: new VueChatState(messages),\n });\n }\n}\n","import {\n AbstractChat,\n type ChatInit as BaseChatInit,\n type ChatInit,\n type ChatState,\n type ChatStatus,\n type UIMessage,\n} from 'ai';\nimport {\n computed,\n getCurrentScope,\n onScopeDispose,\n shallowRef,\n toValue,\n watch,\n type ComputedRef,\n type MaybeRefOrGetter,\n type ShallowRef,\n} from 'vue';\n\nfunction cloneMetadata<METADATA>(metadata: METADATA): METADATA {\n if (Array.isArray(metadata)) {\n return [...metadata] as METADATA;\n }\n\n if (\n metadata != null &&\n typeof metadata === 'object' &&\n (Object.getPrototypeOf(metadata) === Object.prototype ||\n Object.getPrototypeOf(metadata) === null)\n ) {\n return { ...metadata } as METADATA;\n }\n\n return metadata;\n}\n\nfunction snapshotValue<T>(value: T): T {\n if (\n value == null ||\n typeof value !== 'object' ||\n !('parts' in value) ||\n !Array.isArray(value.parts)\n ) {\n return value;\n }\n\n const message = value as unknown as UIMessage;\n const snapshot = {\n ...message,\n parts: message.parts.map(part => ({ ...part })),\n };\n\n if ('metadata' in message) {\n snapshot.metadata = cloneMetadata(message.metadata);\n }\n\n return snapshot as T;\n}\n\nclass VueChatState<\n UI_MESSAGE extends UIMessage,\n> implements ChatState<UI_MESSAGE> {\n private messagesValue: UI_MESSAGE[];\n private publishedMessages: UI_MESSAGE[] = [];\n private publishedMessageSources: UI_MESSAGE[] = [];\n private readonly dirtyMessageIndices = new Set<number>();\n private statusValue: ChatStatus = 'ready';\n private errorValue: Error | undefined;\n private queuedMessagesValue: UI_MESSAGE[] = [];\n private readonly throttleWaitMs: number | undefined;\n private timeout: ReturnType<typeof setTimeout> | undefined;\n private hasPendingPublication = false;\n private isActive = true;\n\n isPublishing = false;\n\n constructor({\n initialMessages,\n messagesRef,\n statusRef,\n errorRef,\n queuedMessagesRef,\n throttleWaitMs,\n }: {\n initialMessages: UI_MESSAGE[];\n messagesRef: ShallowRef<UI_MESSAGE[]>;\n statusRef: ShallowRef<ChatStatus>;\n errorRef: ShallowRef<Error | undefined>;\n queuedMessagesRef: ShallowRef<UI_MESSAGE[]>;\n throttleWaitMs?: number;\n }) {\n this.messagesValue = initialMessages;\n this.messagesRef = messagesRef;\n this.statusRef = statusRef;\n this.errorRef = errorRef;\n this.queuedMessagesRef = queuedMessagesRef;\n this.throttleWaitMs =\n throttleWaitMs != null &&\n Number.isFinite(throttleWaitMs) &&\n throttleWaitMs > 0\n ? throttleWaitMs\n : undefined;\n }\n\n private readonly messagesRef: ShallowRef<UI_MESSAGE[]>;\n private readonly statusRef: ShallowRef<ChatStatus>;\n private readonly errorRef: ShallowRef<Error | undefined>;\n private readonly queuedMessagesRef: ShallowRef<UI_MESSAGE[]>;\n\n get messages(): UI_MESSAGE[] {\n return this.messagesValue;\n }\n\n set messages(messages: UI_MESSAGE[]) {\n const previousMessages = this.messagesValue;\n this.messagesValue = messages;\n\n for (let index = 0; index < messages.length; index++) {\n if (messages[index] !== previousMessages[index]) {\n this.dirtyMessageIndices.add(index);\n }\n }\n\n this.schedulePublication();\n }\n\n get status(): ChatStatus {\n return this.statusValue;\n }\n\n set status(status: ChatStatus) {\n this.statusValue = status;\n\n if (!this.isActive) {\n return;\n }\n\n if (status === 'ready' || status === 'error') {\n // Terminal states must never become observable before the final message.\n this.flushPublication();\n }\n\n this.statusRef.value = status;\n }\n\n get error(): Error | undefined {\n return this.errorValue;\n }\n\n set error(error: Error | undefined) {\n this.errorValue = error;\n\n if (this.isActive) {\n this.errorRef.value = error;\n }\n }\n\n get experimental_queuedMessages(): UI_MESSAGE[] {\n return this.queuedMessagesValue;\n }\n\n set experimental_queuedMessages(experimental_queuedMessages: UI_MESSAGE[]) {\n this.queuedMessagesValue = experimental_queuedMessages;\n\n if (this.isActive) {\n this.queuedMessagesRef.value = experimental_queuedMessages;\n }\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.messagesValue.push(message);\n this.dirtyMessageIndices.add(this.messagesValue.length - 1);\n this.schedulePublication();\n };\n\n popMessage = () => {\n this.messagesValue.pop();\n this.schedulePublication();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.messagesValue[index] = message;\n this.dirtyMessageIndices.add(index);\n this.schedulePublication();\n };\n\n snapshot = snapshotValue;\n\n publishInitialState() {\n this.publishMessages();\n this.statusRef.value = this.statusValue;\n this.errorRef.value = this.errorValue;\n this.queuedMessagesRef.value = this.queuedMessagesValue;\n }\n\n setMessagesFromConsumer(messages: UI_MESSAGE[]) {\n this.messagesValue = messages;\n this.publishedMessages = messages;\n this.publishedMessageSources = messages;\n this.dirtyMessageIndices.clear();\n }\n\n dispose() {\n this.isActive = false;\n this.hasPendingPublication = false;\n this.dirtyMessageIndices.clear();\n this.publishedMessages = [];\n this.publishedMessageSources = [];\n\n if (this.timeout != null) {\n clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n }\n\n private schedulePublication() {\n if (!this.isActive) {\n return;\n }\n\n if (this.throttleWaitMs == null) {\n this.publishMessages();\n return;\n }\n\n if (this.timeout == null) {\n // Publish the leading update immediately, then coalesce updates until\n // the next interval boundary.\n this.publishMessages();\n this.timeout = setTimeout(this.handleIntervalEnd, this.throttleWaitMs);\n } else {\n this.hasPendingPublication = true;\n }\n }\n\n private readonly handleIntervalEnd = () => {\n this.timeout = undefined;\n\n if (!this.isActive || !this.hasPendingPublication) {\n return;\n }\n\n this.hasPendingPublication = false;\n this.publishMessages();\n this.timeout = setTimeout(this.handleIntervalEnd, this.throttleWaitMs);\n };\n\n private flushPublication() {\n if (this.timeout != null) {\n clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n\n this.hasPendingPublication = false;\n this.publishMessages();\n }\n\n private publishMessages() {\n if (!this.isActive) {\n return;\n }\n\n const publishedMessages = this.messagesValue.map((message, index) =>\n this.dirtyMessageIndices.has(index) ||\n this.publishedMessageSources[index] !== message\n ? snapshotValue(message)\n : this.publishedMessages[index],\n );\n\n this.publishedMessages = publishedMessages;\n this.publishedMessageSources = [...this.messagesValue];\n this.dirtyMessageIndices.clear();\n\n this.isPublishing = true;\n try {\n this.messagesRef.value = publishedMessages;\n } finally {\n this.isPublishing = false;\n }\n }\n}\n\n/**\n * @internal\n */\nexport class VueChat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n constructor({\n state,\n ...init\n }: Omit<ChatInit<UI_MESSAGE>, 'messages'> & {\n state: ChatState<UI_MESSAGE>;\n }) {\n super({\n ...init,\n state,\n });\n }\n}\n\n/**\n * Return type of the {@link useChat} composable, which includes the chat\n * instance methods and reactive properties for messages, status, and error.\n */\nexport interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'clearError'\n | 'experimental_removeQueuedMessage'\n | 'experimental_sendQueuedMessageNow'\n> {\n /**\n * The id of the chat.\n */\n id: ComputedRef<string>;\n\n /**\n * The current error state of the chat, if any.\n */\n error: ShallowRef<Error | undefined>;\n\n /**\n * The current status of the chat, which can be 'ready', 'generating', 'streaming', or 'error'.\n */\n status: ShallowRef<ChatStatus>;\n\n /**\n * The list of messages in the chat, which can be updated by the chat instance methods or directly by setting this property.\n */\n messages: ShallowRef<UI_MESSAGE[]>;\n\n /**\n * Experimental. Messages that wait to be sent when `experimental_queue` is\n * enabled, in the order they will be sent.\n */\n experimental_queuedMessages: ShallowRef<UI_MESSAGE[]>;\n}\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> =\n BaseChatInit<UI_MESSAGE> & {\n /**\n * Custom throttle wait time in milliseconds for reactive message updates.\n * Positive values enable throttling. Defaults to undefined, which disables\n * throttling.\n */\n throttle?: number;\n };\n\n/**\n * Composable to access messages, status, and other chat properties and\n * methods. Accepts an optional reactive initial configuration object\n *\n * @example\n *\n * ```ts\n * // passing a getter if any reactive properties are used within\n * // the init object\n * const { messages, sendMessage } = useChat(() => ({\n * // ...\n * })\n * ```\n *\n * @see BaseChatInit\n */\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>(\n init?: MaybeRefOrGetter<UseChatOptions<UI_MESSAGE>>,\n): UseChatHelpers<UI_MESSAGE> {\n const messages = shallowRef<UI_MESSAGE[]>([]);\n const status = shallowRef<ChatStatus>('ready');\n const error = shallowRef<Error | undefined>();\n const experimental_queuedMessages = shallowRef<UI_MESSAGE[]>([]);\n\n // the instance is created right away thanks to immediate: true. We do it this\n // way instead of a computed to ensure all changes to reactive state happen\n // in the same tick\n const chatInstance = shallowRef<VueChat<UI_MESSAGE>>() as ShallowRef<\n VueChat<UI_MESSAGE>\n >;\n let chatState: VueChatState<UI_MESSAGE> | undefined;\n\n watch(\n messages,\n messageList => {\n if (chatState != null && !chatState.isPublishing) {\n chatState.setMessagesFromConsumer(messageList);\n }\n },\n { flush: 'sync' },\n );\n\n watch(\n () => toValue(init),\n opts => {\n chatState?.dispose();\n\n const { throttle, ...chatInit } = opts ?? {};\n const nextChatState = new VueChatState<UI_MESSAGE>({\n initialMessages: chatInit.messages ?? [],\n messagesRef: messages,\n statusRef: status,\n errorRef: error,\n queuedMessagesRef: experimental_queuedMessages,\n throttleWaitMs: throttle,\n });\n\n chatState = nextChatState;\n nextChatState.publishInitialState();\n\n chatInstance.value = new VueChat<UI_MESSAGE>({\n ...chatInit,\n state: nextChatState,\n });\n },\n { immediate: true },\n );\n\n if (getCurrentScope() != null) {\n onScopeDispose(() => {\n chatState?.dispose();\n });\n }\n\n return {\n id: computed(() => chatInstance.value.id),\n status,\n messages,\n error,\n addToolApprovalResponse: opts =>\n chatInstance.value.addToolApprovalResponse(opts),\n addToolOutput: opts => chatInstance.value.addToolOutput(opts),\n clearError: () => chatInstance.value.clearError(),\n regenerate: opts => chatInstance.value.regenerate(opts),\n sendMessage: (...args) => chatInstance.value.sendMessage(...args),\n stop: () => chatInstance.value.stop(),\n resumeStream: opts => chatInstance.value.resumeStream(opts),\n experimental_queuedMessages,\n experimental_removeQueuedMessage: id =>\n chatInstance.value.experimental_removeQueuedMessage(id),\n experimental_sendQueuedMessageNow: id =>\n chatInstance.value.experimental_sendQueuedMessageNow(id),\n };\n}\n","import type { FlexibleSchema } from '@ai-sdk/provider-utils';\nimport {\n useObject,\n type UseObjectHelpers,\n type UseObjectOptions,\n} from './use-object';\n\nexport * from './use-completion';\nexport { Chat } from './chat.vue';\nexport { useChat, type UseChatHelpers, type UseChatOptions } from './use-chat';\nexport * from './use-object';\n\n// deprecated aliases\n// note: declared here (instead of export aliases) so that the `@deprecated`\n// tags are preserved in the bundled type declarations\n\n/**\n * @deprecated Use `useObject` instead.\n */\nexport const experimental_useObject = useObject;\n\n/**\n * @deprecated Use `UseObjectOptions` instead.\n */\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = UseObjectOptions<SCHEMA, RESULT>;\n\n/**\n * @deprecated Use `UseObjectHelpers` instead.\n */\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = UseObjectHelpers<\n RESULT,\n INPUT\n>;\n"],"mappings":";;;;;AAkBA,MAAM,yBAAyB;AAsD/B,IAAIA,aAAW;AAGf,MAAMC,YAAW,KAAK,WAA8C;AACpE,MAAMC,UAA6B,CAAC;AAEpC,SAAgB,UAId,EACA,KACA,IACA,QACA,cACA,OACA,SACA,UACA,SACA,eACoE;CAEpE,MAAM,eAAe,MAAM,cAAc;CAEzC,MAAM,MAAM,GAAG,IAAI,GAAG;CACtB,MAAM,EAAE,MAAM,QAAQ,mBAAmBD,UAEvC,WAAY,OAAOC,UAAQA,QAAM,OAAO,YAAa;CAEvD,MAAM,EAAE,MAAM,WAAW,QAAQ,kBAAkBD,UACjD,GAAG,aAAa,WAChB,IACF;CAEA,UAAU,UAAU;CACpB,KAAK,UAAU;CAEf,MAAM,gBAAgB,UAA2C;EAC/D,QAAM,OAAO;EACb,OAAO,eAAe;CACxB;CAEA,MAAM,QA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;EAED,YAAY;EACZ,cAAc,oBAAoB;EAElC,aAAa,QAAQ,IAAI,QAAoB;GAC3C,GAAG;GACH,OAAO;EACT,CAAC;CACH,GACA,EAAE,WAAW,KAAK,CACpB;CAEA,IAAI,gBAAgB,KAAK,MACvB,qBAAqB;EACnB,WAAW,QAAQ;CACrB,CAAC;CAGH,OAAO;EACL,IAAI,eAAe,aAAa,MAAM,EAAE;EACxC;EACA;EACA;EACA,0BAAyB,SACvB,aAAa,MAAM,wBAAwB,IAAI;EACjD,gBAAe,SAAQ,aAAa,MAAM,cAAc,IAAI;EAC5D,kBAAkB,aAAa,MAAM,WAAW;EAChD,aAAY,SAAQ,aAAa,MAAM,WAAW,IAAI;EACtD,cAAc,GAAG,SAAS,aAAa,MAAM,YAAY,GAAG,IAAI;EAChE,YAAY,aAAa,MAAM,KAAK;EACpC,eAAc,SAAQ,aAAa,MAAM,aAAa,IAAI;EAC1D;EACA,mCAAkC,OAChC,aAAa,MAAM,iCAAiC,EAAE;EACxD,oCAAmC,OACjC,aAAa,MAAM,kCAAkC,EAAE;CAC3D;AACF;;;;;;AC7aA,MAAa,yBAAyB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/vue",
3
- "version": "4.0.166",
3
+ "version": "4.0.169",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -26,8 +26,8 @@
26
26
  "README.md"
27
27
  ],
28
28
  "dependencies": {
29
- "@ai-sdk/provider-utils": "5.0.76",
30
- "ai": "7.0.166",
29
+ "@ai-sdk/provider-utils": "5.0.79",
30
+ "ai": "7.0.169",
31
31
  "swrv": "^1.2.0"
32
32
  },
33
33
  "devDependencies": {
@@ -44,7 +44,7 @@
44
44
  "tsdown": "^0.23.0",
45
45
  "typescript": "6.0.3",
46
46
  "vitest": "4.1.11",
47
- "zod": "3.25.76"
47
+ "zod": "4.6.7"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "vue": "^3.3.4"
package/src/chat.vue.ts CHANGED
@@ -12,6 +12,7 @@ class VueChatState<
12
12
  private messagesRef: Ref<UI_MESSAGE[]>;
13
13
  private statusRef = ref<ChatStatus>('ready');
14
14
  private errorRef = ref<Error | undefined>(undefined);
15
+ private queuedMessagesRef = ref([]) as Ref<UI_MESSAGE[]>;
15
16
 
16
17
  constructor(messages?: UI_MESSAGE[]) {
17
18
  this.messagesRef = ref(messages ?? []) as Ref<UI_MESSAGE[]>;
@@ -41,6 +42,14 @@ class VueChatState<
41
42
  this.errorRef.value = error;
42
43
  }
43
44
 
45
+ get experimental_queuedMessages(): UI_MESSAGE[] {
46
+ return this.queuedMessagesRef.value;
47
+ }
48
+
49
+ set experimental_queuedMessages(experimental_queuedMessages: UI_MESSAGE[]) {
50
+ this.queuedMessagesRef.value = experimental_queuedMessages;
51
+ }
52
+
44
53
  pushMessage = (message: UI_MESSAGE) => {
45
54
  this.messagesRef.value = [...this.messagesRef.value, message];
46
55
  };
package/src/use-chat.ts CHANGED
@@ -67,6 +67,7 @@ class VueChatState<
67
67
  private readonly dirtyMessageIndices = new Set<number>();
68
68
  private statusValue: ChatStatus = 'ready';
69
69
  private errorValue: Error | undefined;
70
+ private queuedMessagesValue: UI_MESSAGE[] = [];
70
71
  private readonly throttleWaitMs: number | undefined;
71
72
  private timeout: ReturnType<typeof setTimeout> | undefined;
72
73
  private hasPendingPublication = false;
@@ -79,18 +80,21 @@ class VueChatState<
79
80
  messagesRef,
80
81
  statusRef,
81
82
  errorRef,
83
+ queuedMessagesRef,
82
84
  throttleWaitMs,
83
85
  }: {
84
86
  initialMessages: UI_MESSAGE[];
85
87
  messagesRef: ShallowRef<UI_MESSAGE[]>;
86
88
  statusRef: ShallowRef<ChatStatus>;
87
89
  errorRef: ShallowRef<Error | undefined>;
90
+ queuedMessagesRef: ShallowRef<UI_MESSAGE[]>;
88
91
  throttleWaitMs?: number;
89
92
  }) {
90
93
  this.messagesValue = initialMessages;
91
94
  this.messagesRef = messagesRef;
92
95
  this.statusRef = statusRef;
93
96
  this.errorRef = errorRef;
97
+ this.queuedMessagesRef = queuedMessagesRef;
94
98
  this.throttleWaitMs =
95
99
  throttleWaitMs != null &&
96
100
  Number.isFinite(throttleWaitMs) &&
@@ -102,6 +106,7 @@ class VueChatState<
102
106
  private readonly messagesRef: ShallowRef<UI_MESSAGE[]>;
103
107
  private readonly statusRef: ShallowRef<ChatStatus>;
104
108
  private readonly errorRef: ShallowRef<Error | undefined>;
109
+ private readonly queuedMessagesRef: ShallowRef<UI_MESSAGE[]>;
105
110
 
106
111
  get messages(): UI_MESSAGE[] {
107
112
  return this.messagesValue;
@@ -151,6 +156,18 @@ class VueChatState<
151
156
  }
152
157
  }
153
158
 
159
+ get experimental_queuedMessages(): UI_MESSAGE[] {
160
+ return this.queuedMessagesValue;
161
+ }
162
+
163
+ set experimental_queuedMessages(experimental_queuedMessages: UI_MESSAGE[]) {
164
+ this.queuedMessagesValue = experimental_queuedMessages;
165
+
166
+ if (this.isActive) {
167
+ this.queuedMessagesRef.value = experimental_queuedMessages;
168
+ }
169
+ }
170
+
154
171
  pushMessage = (message: UI_MESSAGE) => {
155
172
  this.messagesValue.push(message);
156
173
  this.dirtyMessageIndices.add(this.messagesValue.length - 1);
@@ -174,6 +191,7 @@ class VueChatState<
174
191
  this.publishMessages();
175
192
  this.statusRef.value = this.statusValue;
176
193
  this.errorRef.value = this.errorValue;
194
+ this.queuedMessagesRef.value = this.queuedMessagesValue;
177
195
  }
178
196
 
179
197
  setMessagesFromConsumer(messages: UI_MESSAGE[]) {
@@ -295,6 +313,8 @@ export interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<
295
313
  | 'addToolOutput'
296
314
  | 'addToolApprovalResponse'
297
315
  | 'clearError'
316
+ | 'experimental_removeQueuedMessage'
317
+ | 'experimental_sendQueuedMessageNow'
298
318
  > {
299
319
  /**
300
320
  * The id of the chat.
@@ -315,6 +335,12 @@ export interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<
315
335
  * The list of messages in the chat, which can be updated by the chat instance methods or directly by setting this property.
316
336
  */
317
337
  messages: ShallowRef<UI_MESSAGE[]>;
338
+
339
+ /**
340
+ * Experimental. Messages that wait to be sent when `experimental_queue` is
341
+ * enabled, in the order they will be sent.
342
+ */
343
+ experimental_queuedMessages: ShallowRef<UI_MESSAGE[]>;
318
344
  }
319
345
 
320
346
  export type UseChatOptions<UI_MESSAGE extends UIMessage> =
@@ -349,6 +375,7 @@ export function useChat<UI_MESSAGE extends UIMessage = UIMessage>(
349
375
  const messages = shallowRef<UI_MESSAGE[]>([]);
350
376
  const status = shallowRef<ChatStatus>('ready');
351
377
  const error = shallowRef<Error | undefined>();
378
+ const experimental_queuedMessages = shallowRef<UI_MESSAGE[]>([]);
352
379
 
353
380
  // the instance is created right away thanks to immediate: true. We do it this
354
381
  // way instead of a computed to ensure all changes to reactive state happen
@@ -379,6 +406,7 @@ export function useChat<UI_MESSAGE extends UIMessage = UIMessage>(
379
406
  messagesRef: messages,
380
407
  statusRef: status,
381
408
  errorRef: error,
409
+ queuedMessagesRef: experimental_queuedMessages,
382
410
  throttleWaitMs: throttle,
383
411
  });
384
412
 
@@ -412,5 +440,10 @@ export function useChat<UI_MESSAGE extends UIMessage = UIMessage>(
412
440
  sendMessage: (...args) => chatInstance.value.sendMessage(...args),
413
441
  stop: () => chatInstance.value.stop(),
414
442
  resumeStream: opts => chatInstance.value.resumeStream(opts),
443
+ experimental_queuedMessages,
444
+ experimental_removeQueuedMessage: id =>
445
+ chatInstance.value.experimental_removeQueuedMessage(id),
446
+ experimental_sendQueuedMessageNow: id =>
447
+ chatInstance.value.experimental_sendQueuedMessageNow(id),
415
448
  };
416
449
  }