@ai-sdk/react 4.0.0-beta.86 → 4.0.0-beta.88

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,23 @@
1
1
  # @ai-sdk/react
2
2
 
3
+ ## 4.0.0-beta.88
4
+
5
+ ### Major Changes
6
+
7
+ - ef992f8: Remove CommonJS exports from all packages. All packages are now ESM-only (`"type": "module"`). Consumers using `require()` must switch to ESM `import` syntax.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [ef992f8]
12
+ - ai@7.0.0-beta.88
13
+ - @ai-sdk/provider-utils@5.0.0-beta.19
14
+
15
+ ## 4.0.0-beta.87
16
+
17
+ ### Patch Changes
18
+
19
+ - ai@7.0.0-beta.87
20
+
3
21
  ## 4.0.0-beta.86
4
22
 
5
23
  ### Patch Changes
package/dist/index.js CHANGED
@@ -1,31 +1,3 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
1
  var __accessCheck = (obj, member, msg) => {
30
2
  if (!member.has(obj))
31
3
  throw TypeError("Cannot " + msg);
@@ -45,26 +17,16 @@ var __privateSet = (obj, member, value, setter) => {
45
17
  return value;
46
18
  };
47
19
 
48
- // src/index.ts
49
- var src_exports = {};
50
- __export(src_exports, {
51
- Chat: () => Chat,
52
- experimental_useObject: () => experimental_useObject,
53
- useChat: () => useChat,
54
- useCompletion: () => useCompletion
55
- });
56
- module.exports = __toCommonJS(src_exports);
57
-
58
20
  // src/use-chat.ts
59
- var import_react = require("react");
21
+ import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";
60
22
 
61
23
  // src/chat.react.ts
62
- var import_ai = require("ai");
24
+ import { AbstractChat } from "ai";
63
25
 
64
26
  // src/throttle.ts
65
- var import_throttleit = __toESM(require("throttleit"));
27
+ import throttleFunction from "throttleit";
66
28
  function throttle(fn, waitMs) {
67
- return waitMs != null ? (0, import_throttleit.default)(fn, waitMs) : fn;
29
+ return waitMs != null ? throttleFunction(fn, waitMs) : fn;
68
30
  }
69
31
 
70
32
  // src/chat.react.ts
@@ -157,7 +119,7 @@ _callMessagesCallbacks = new WeakMap();
157
119
  _callStatusCallbacks = new WeakMap();
158
120
  _callErrorCallbacks = new WeakMap();
159
121
  var _state;
160
- var Chat = class extends import_ai.AbstractChat {
122
+ var Chat = class extends AbstractChat {
161
123
  constructor({ messages, ...init }) {
162
124
  const state = new ReactChatState(messages);
163
125
  super({ ...init, state });
@@ -176,7 +138,7 @@ function useChat({
176
138
  resume = false,
177
139
  ...options
178
140
  } = {}) {
179
- const callbacksRef = (0, import_react.useRef)(
141
+ const callbacksRef = useRef(
180
142
  !("chat" in options) ? {
181
143
  onToolCall: options.onToolCall,
182
144
  onData: options.onData,
@@ -217,35 +179,35 @@ function useChat({
217
179
  return (_c = (_b = (_a = callbacksRef.current).sendAutomaticallyWhen) == null ? void 0 : _b.call(_a, arg)) != null ? _c : false;
218
180
  }
219
181
  };
220
- const chatRef = (0, import_react.useRef)(
182
+ const chatRef = useRef(
221
183
  "chat" in options ? options.chat : new Chat(optionsWithCallbacks)
222
184
  );
223
185
  const shouldRecreateChat = "chat" in options && options.chat !== chatRef.current || "id" in options && chatRef.current.id !== options.id;
224
186
  if (shouldRecreateChat) {
225
187
  chatRef.current = "chat" in options ? options.chat : new Chat(optionsWithCallbacks);
226
188
  }
227
- const subscribeToMessages = (0, import_react.useCallback)(
189
+ const subscribeToMessages = useCallback(
228
190
  (update) => chatRef.current["~registerMessagesCallback"](update, throttleWaitMs),
229
191
  // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes
230
192
  // eslint-disable-next-line react-hooks/exhaustive-deps
231
193
  [throttleWaitMs, chatRef.current.id]
232
194
  );
233
- const messages = (0, import_react.useSyncExternalStore)(
195
+ const messages = useSyncExternalStore(
234
196
  subscribeToMessages,
235
197
  () => chatRef.current.messages,
236
198
  () => chatRef.current.messages
237
199
  );
238
- const status = (0, import_react.useSyncExternalStore)(
200
+ const status = useSyncExternalStore(
239
201
  chatRef.current["~registerStatusCallback"],
240
202
  () => chatRef.current.status,
241
203
  () => chatRef.current.status
242
204
  );
243
- const error = (0, import_react.useSyncExternalStore)(
205
+ const error = useSyncExternalStore(
244
206
  chatRef.current["~registerErrorCallback"],
245
207
  () => chatRef.current.error,
246
208
  () => chatRef.current.error
247
209
  );
248
- const setMessages = (0, import_react.useCallback)(
210
+ const setMessages = useCallback(
249
211
  (messagesParam) => {
250
212
  if (typeof messagesParam === "function") {
251
213
  messagesParam = messagesParam(chatRef.current.messages);
@@ -254,7 +216,7 @@ function useChat({
254
216
  },
255
217
  [chatRef]
256
218
  );
257
- (0, import_react.useEffect)(() => {
219
+ useEffect(() => {
258
220
  if (resume) {
259
221
  chatRef.current.resumeStream();
260
222
  }
@@ -280,9 +242,11 @@ function useChat({
280
242
  }
281
243
 
282
244
  // src/use-completion.ts
283
- var import_ai2 = require("ai");
284
- var import_react2 = require("react");
285
- var import_swr = __toESM(require("swr"));
245
+ import {
246
+ callCompletionApi
247
+ } from "ai";
248
+ import { useCallback as useCallback2, useEffect as useEffect2, useId, useRef as useRef2, useState } from "react";
249
+ import useSWR from "swr";
286
250
  function useCompletion({
287
251
  api = "/api/completion",
288
252
  id,
@@ -297,32 +261,32 @@ function useCompletion({
297
261
  onError,
298
262
  experimental_throttle: throttleWaitMs
299
263
  } = {}) {
300
- const hookId = (0, import_react2.useId)();
264
+ const hookId = useId();
301
265
  const completionId = id || hookId;
302
- const { data, mutate } = (0, import_swr.default)([api, completionId], null, {
266
+ const { data, mutate } = useSWR([api, completionId], null, {
303
267
  fallbackData: initialCompletion
304
268
  });
305
- const { data: isLoading = false, mutate: mutateLoading } = (0, import_swr.default)(
269
+ const { data: isLoading = false, mutate: mutateLoading } = useSWR(
306
270
  [completionId, "loading"],
307
271
  null
308
272
  );
309
- const [error, setError] = (0, import_react2.useState)(void 0);
273
+ const [error, setError] = useState(void 0);
310
274
  const completion = data;
311
- const [abortController, setAbortController] = (0, import_react2.useState)(null);
312
- const extraMetadataRef = (0, import_react2.useRef)({
275
+ const [abortController, setAbortController] = useState(null);
276
+ const extraMetadataRef = useRef2({
313
277
  credentials,
314
278
  headers,
315
279
  body
316
280
  });
317
- (0, import_react2.useEffect)(() => {
281
+ useEffect2(() => {
318
282
  extraMetadataRef.current = {
319
283
  credentials,
320
284
  headers,
321
285
  body
322
286
  };
323
287
  }, [credentials, headers, body]);
324
- const triggerRequest = (0, import_react2.useCallback)(
325
- async (prompt, options) => (0, import_ai2.callCompletionApi)({
288
+ const triggerRequest = useCallback2(
289
+ async (prompt, options) => callCompletionApi({
326
290
  api,
327
291
  prompt,
328
292
  credentials: extraMetadataRef.current.credentials,
@@ -358,26 +322,26 @@ function useCompletion({
358
322
  throttleWaitMs
359
323
  ]
360
324
  );
361
- const stop = (0, import_react2.useCallback)(() => {
325
+ const stop = useCallback2(() => {
362
326
  if (abortController) {
363
327
  abortController.abort();
364
328
  setAbortController(null);
365
329
  }
366
330
  }, [abortController]);
367
- const setCompletion = (0, import_react2.useCallback)(
331
+ const setCompletion = useCallback2(
368
332
  (completion2) => {
369
333
  mutate(completion2, false);
370
334
  },
371
335
  [mutate]
372
336
  );
373
- const complete = (0, import_react2.useCallback)(
337
+ const complete = useCallback2(
374
338
  async (prompt, options) => {
375
339
  return triggerRequest(prompt, options);
376
340
  },
377
341
  [triggerRequest]
378
342
  );
379
- const [input, setInput] = (0, import_react2.useState)(initialInput);
380
- const handleSubmit = (0, import_react2.useCallback)(
343
+ const [input, setInput] = useState(initialInput);
344
+ const handleSubmit = useCallback2(
381
345
  (event) => {
382
346
  var _a;
383
347
  (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
@@ -385,7 +349,7 @@ function useCompletion({
385
349
  },
386
350
  [input, complete]
387
351
  );
388
- const handleInputChange = (0, import_react2.useCallback)(
352
+ const handleInputChange = useCallback2(
389
353
  (e) => {
390
354
  setInput(e.target.value);
391
355
  },
@@ -406,10 +370,15 @@ function useCompletion({
406
370
  }
407
371
 
408
372
  // src/use-object.ts
409
- var import_provider_utils = require("@ai-sdk/provider-utils");
410
- var import_ai3 = require("ai");
411
- var import_react3 = require("react");
412
- var import_swr2 = __toESM(require("swr"));
373
+ import {
374
+ isAbortError,
375
+ resolve,
376
+ normalizeHeaders,
377
+ safeValidateTypes
378
+ } from "@ai-sdk/provider-utils";
379
+ import { asSchema, isDeepEqualData, parsePartialJson } from "ai";
380
+ import { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState2 } from "react";
381
+ import useSWR2 from "swr";
413
382
  var getOriginalFetch = () => fetch;
414
383
  function useObject({
415
384
  api,
@@ -423,17 +392,17 @@ function useObject({
423
392
  headers,
424
393
  credentials
425
394
  }) {
426
- const hookId = (0, import_react3.useId)();
395
+ const hookId = useId2();
427
396
  const completionId = id != null ? id : hookId;
428
- const { data, mutate } = (0, import_swr2.default)(
397
+ const { data, mutate } = useSWR2(
429
398
  [api, completionId],
430
399
  null,
431
400
  { fallbackData: initialValue }
432
401
  );
433
- const [error, setError] = (0, import_react3.useState)(void 0);
434
- const [isLoading, setIsLoading] = (0, import_react3.useState)(false);
435
- const abortControllerRef = (0, import_react3.useRef)(null);
436
- const stop = (0, import_react3.useCallback)(() => {
402
+ const [error, setError] = useState2(void 0);
403
+ const [isLoading, setIsLoading] = useState2(false);
404
+ const abortControllerRef = useRef3(null);
405
+ const stop = useCallback3(() => {
437
406
  var _a;
438
407
  try {
439
408
  (_a = abortControllerRef.current) == null ? void 0 : _a.abort();
@@ -450,13 +419,13 @@ function useObject({
450
419
  setIsLoading(true);
451
420
  const abortController = new AbortController();
452
421
  abortControllerRef.current = abortController;
453
- const resolvedHeaders = await (0, import_provider_utils.resolve)(headers);
422
+ const resolvedHeaders = await resolve(headers);
454
423
  const actualFetch = fetch2 != null ? fetch2 : getOriginalFetch();
455
424
  const response = await actualFetch(api, {
456
425
  method: "POST",
457
426
  headers: {
458
427
  "Content-Type": "application/json",
459
- ...(0, import_provider_utils.normalizeHeaders)(resolvedHeaders)
428
+ ...normalizeHeaders(resolvedHeaders)
460
429
  },
461
430
  credentials,
462
431
  signal: abortController.signal,
@@ -476,9 +445,9 @@ function useObject({
476
445
  new WritableStream({
477
446
  async write(chunk) {
478
447
  accumulatedText += chunk;
479
- const { value } = await (0, import_ai3.parsePartialJson)(accumulatedText);
448
+ const { value } = await parsePartialJson(accumulatedText);
480
449
  const currentObject = value;
481
- if (!(0, import_ai3.isDeepEqualData)(latestObject, currentObject)) {
450
+ if (!isDeepEqualData(latestObject, currentObject)) {
482
451
  latestObject = currentObject;
483
452
  mutate(currentObject);
484
453
  }
@@ -487,9 +456,9 @@ function useObject({
487
456
  setIsLoading(false);
488
457
  abortControllerRef.current = null;
489
458
  if (onFinish != null) {
490
- const validationResult = await (0, import_provider_utils.safeValidateTypes)({
459
+ const validationResult = await safeValidateTypes({
491
460
  value: latestObject,
492
- schema: (0, import_ai3.asSchema)(schema)
461
+ schema: asSchema(schema)
493
462
  });
494
463
  onFinish(
495
464
  validationResult.success ? { object: validationResult.value, error: void 0 } : { object: void 0, error: validationResult.error }
@@ -499,7 +468,7 @@ function useObject({
499
468
  })
500
469
  );
501
470
  } catch (error2) {
502
- if ((0, import_provider_utils.isAbortError)(error2)) {
471
+ if (isAbortError(error2)) {
503
472
  return;
504
473
  }
505
474
  if (onError && error2 instanceof Error) {
@@ -528,11 +497,10 @@ function useObject({
528
497
  };
529
498
  }
530
499
  var experimental_useObject = useObject;
531
- // Annotate the CommonJS export names for ESM import in node:
532
- 0 && (module.exports = {
500
+ export {
533
501
  Chat,
534
502
  experimental_useObject,
535
503
  useChat,
536
504
  useCompletion
537
- });
505
+ };
538
506
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/chat.react.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-chat';\nexport { Chat } from './chat.react';\nexport * from './use-completion';\nexport * from './use-object';\n","import {\n AbstractChat,\n ChatInit,\n type CreateUIMessage,\n type UIMessage,\n} from 'ai';\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { Chat } from './chat.react';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<UI_MESSAGE extends UIMessage> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolResult'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'status'\n | 'messages'\n | 'clearError'\n>;\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> = (\n | { chat: Chat<UI_MESSAGE> }\n | ChatInit<UI_MESSAGE>\n) & {\n /**\n * Custom throttle wait in ms for the chat messages and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n\n /**\n * Whether to resume an ongoing chat generation stream.\n */\n resume?: boolean;\n};\n\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>({\n experimental_throttle: throttleWaitMs,\n resume = false,\n ...options\n}: UseChatOptions<UI_MESSAGE> = {}): UseChatHelpers<UI_MESSAGE> {\n // Create a single ref for all callbacks to avoid stale closures\n const callbacksRef = useRef(\n !('chat' in options)\n ? {\n onToolCall: options.onToolCall,\n onData: options.onData,\n onFinish: options.onFinish,\n onError: options.onError,\n sendAutomaticallyWhen: options.sendAutomaticallyWhen,\n }\n : {},\n );\n\n // Update callbacks ref on each render to keep them current\n if (!('chat' in options)) {\n callbacksRef.current = {\n onToolCall: options.onToolCall,\n onData: options.onData,\n onFinish: options.onFinish,\n onError: options.onError,\n sendAutomaticallyWhen: options.sendAutomaticallyWhen,\n };\n }\n\n // Ensure the Chat instance has the latest callbacks\n const optionsWithCallbacks: typeof options = {\n ...options,\n onToolCall: arg => callbacksRef.current.onToolCall?.(arg),\n onData: arg => callbacksRef.current.onData?.(arg),\n onFinish: arg => callbacksRef.current.onFinish?.(arg),\n onError: arg => callbacksRef.current.onError?.(arg),\n sendAutomaticallyWhen: arg =>\n callbacksRef.current.sendAutomaticallyWhen?.(arg) ?? false,\n };\n\n const chatRef = useRef<Chat<UI_MESSAGE>>(\n 'chat' in options ? options.chat : new Chat(optionsWithCallbacks),\n );\n\n const shouldRecreateChat =\n ('chat' in options && options.chat !== chatRef.current) ||\n ('id' in options && chatRef.current.id !== options.id);\n\n if (shouldRecreateChat) {\n chatRef.current =\n 'chat' in options ? options.chat : new Chat(optionsWithCallbacks);\n }\n\n const subscribeToMessages = useCallback(\n (update: () => void) =>\n chatRef.current['~registerMessagesCallback'](update, throttleWaitMs),\n // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [throttleWaitMs, chatRef.current.id],\n );\n\n const messages = useSyncExternalStore(\n subscribeToMessages,\n () => chatRef.current.messages,\n () => chatRef.current.messages,\n );\n\n const status = useSyncExternalStore(\n chatRef.current['~registerStatusCallback'],\n () => chatRef.current.status,\n () => chatRef.current.status,\n );\n\n const error = useSyncExternalStore(\n chatRef.current['~registerErrorCallback'],\n () => chatRef.current.error,\n () => chatRef.current.error,\n );\n\n const setMessages = useCallback(\n (\n messagesParam: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(chatRef.current.messages);\n }\n chatRef.current.messages = messagesParam;\n },\n [chatRef],\n );\n\n useEffect(() => {\n if (resume) {\n chatRef.current.resumeStream();\n }\n }, [resume, chatRef]);\n\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n regenerate: chatRef.current.regenerate,\n clearError: chatRef.current.clearError,\n stop: chatRef.current.stop,\n error,\n resumeStream: chatRef.current.resumeStream,\n status,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: chatRef.current.addToolOutput,\n addToolOutput: chatRef.current.addToolOutput,\n addToolApprovalResponse: chatRef.current.addToolApprovalResponse,\n };\n}\n","import { AbstractChat, ChatInit, ChatState, ChatStatus, UIMessage } from 'ai';\nimport { throttle } from './throttle';\n\nclass ReactChatState<\n UI_MESSAGE extends UIMessage,\n> implements ChatState<UI_MESSAGE> {\n #messages: UI_MESSAGE[];\n #status: ChatStatus = 'ready';\n #error: Error | undefined = undefined;\n\n #messagesCallbacks = new Set<() => void>();\n #statusCallbacks = new Set<() => void>();\n #errorCallbacks = new Set<() => void>();\n\n constructor(initialMessages: UI_MESSAGE[] = []) {\n this.#messages = initialMessages;\n }\n\n get status(): ChatStatus {\n return this.#status;\n }\n\n set status(newStatus: ChatStatus) {\n this.#status = newStatus;\n this.#callStatusCallbacks();\n }\n\n get error(): Error | undefined {\n return this.#error;\n }\n\n set error(newError: Error | undefined) {\n this.#error = newError;\n this.#callErrorCallbacks();\n }\n\n get messages(): UI_MESSAGE[] {\n return this.#messages;\n }\n\n set messages(newMessages: UI_MESSAGE[]) {\n this.#messages = [...newMessages];\n this.#callMessagesCallbacks();\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.#messages = this.#messages.concat(message);\n this.#callMessagesCallbacks();\n };\n\n popMessage = () => {\n this.#messages = this.#messages.slice(0, -1);\n this.#callMessagesCallbacks();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:\n this.snapshot(message),\n ...this.#messages.slice(index + 1),\n ];\n this.#callMessagesCallbacks();\n };\n\n snapshot = <T>(value: T): T => structuredClone(value);\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) => {\n const callback = throttleWaitMs\n ? throttle(onChange, throttleWaitMs)\n : onChange;\n this.#messagesCallbacks.add(callback);\n return () => {\n this.#messagesCallbacks.delete(callback);\n };\n };\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) => {\n this.#statusCallbacks.add(onChange);\n return () => {\n this.#statusCallbacks.delete(onChange);\n };\n };\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) => {\n this.#errorCallbacks.add(onChange);\n return () => {\n this.#errorCallbacks.delete(onChange);\n };\n };\n\n #callMessagesCallbacks = () => {\n this.#messagesCallbacks.forEach(callback => callback());\n };\n\n #callStatusCallbacks = () => {\n this.#statusCallbacks.forEach(callback => callback());\n };\n\n #callErrorCallbacks = () => {\n this.#errorCallbacks.forEach(callback => callback());\n };\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n #state: ReactChatState<UI_MESSAGE>;\n\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n this.#state = state;\n }\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) =>\n this.#state['~registerMessagesCallback'](onChange, throttleWaitMs);\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerStatusCallback'](onChange);\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerErrorCallback'](onChange);\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\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: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n FlexibleSchema,\n InferSchema,\n isAbortError,\n Resolvable,\n resolve,\n normalizeHeaders,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport { asSchema, DeepPartial, isDeepEqualData, parsePartialJson } from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\n * Callback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\n * The generated object (typed according to the schema).\n * Can be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\n * Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n * Can be a static object, a function that returns headers, or an async function\n * for dynamic auth tokens.\n */\n headers?: Resolvable<Record<string, string> | Headers>;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n\n /**\n * Clear the object state.\n */\n clear: () => void;\n};\n\nfunction useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n clearObject();\n\n setIsLoading(true);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n // Resolve headers at request time (supports async functions for dynamic auth tokens)\n const resolvedHeaders = await resolve(headers);\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...normalizeHeaders(resolvedHeaders),\n },\n credentials,\n signal: abortController.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 == null) {\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\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n const clear = () => {\n stop();\n clearObject();\n };\n\n const clearObject = () => {\n setError(undefined);\n setIsLoading(false);\n mutate(undefined);\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n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CAAC;AAAA,IACpE;AAAA,EACF;AAEA,QAAM,QAAQ,MAAM;AAClB,SAAK;AACL,gBAAY;AAAA,EACd;AAEA,QAAM,cAAc,MAAM;AACxB,aAAS,MAAS;AAClB,iBAAa,KAAK;AAClB,WAAO,MAAS;AAAA,EAClB;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["throttleFunction","import_ai","import_react","fetch","useSWR","completion","import_ai","import_react","import_swr","fetch","useSWR","error"]}
1
+ {"version":3,"sources":["../src/use-chat.ts","../src/chat.react.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["import {\n AbstractChat,\n ChatInit,\n type CreateUIMessage,\n type UIMessage,\n} from 'ai';\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { Chat } from './chat.react';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<UI_MESSAGE extends UIMessage> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolResult'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'status'\n | 'messages'\n | 'clearError'\n>;\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> = (\n | { chat: Chat<UI_MESSAGE> }\n | ChatInit<UI_MESSAGE>\n) & {\n /**\n * Custom throttle wait in ms for the chat messages and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n\n /**\n * Whether to resume an ongoing chat generation stream.\n */\n resume?: boolean;\n};\n\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>({\n experimental_throttle: throttleWaitMs,\n resume = false,\n ...options\n}: UseChatOptions<UI_MESSAGE> = {}): UseChatHelpers<UI_MESSAGE> {\n // Create a single ref for all callbacks to avoid stale closures\n const callbacksRef = useRef(\n !('chat' in options)\n ? {\n onToolCall: options.onToolCall,\n onData: options.onData,\n onFinish: options.onFinish,\n onError: options.onError,\n sendAutomaticallyWhen: options.sendAutomaticallyWhen,\n }\n : {},\n );\n\n // Update callbacks ref on each render to keep them current\n if (!('chat' in options)) {\n callbacksRef.current = {\n onToolCall: options.onToolCall,\n onData: options.onData,\n onFinish: options.onFinish,\n onError: options.onError,\n sendAutomaticallyWhen: options.sendAutomaticallyWhen,\n };\n }\n\n // Ensure the Chat instance has the latest callbacks\n const optionsWithCallbacks: typeof options = {\n ...options,\n onToolCall: arg => callbacksRef.current.onToolCall?.(arg),\n onData: arg => callbacksRef.current.onData?.(arg),\n onFinish: arg => callbacksRef.current.onFinish?.(arg),\n onError: arg => callbacksRef.current.onError?.(arg),\n sendAutomaticallyWhen: arg =>\n callbacksRef.current.sendAutomaticallyWhen?.(arg) ?? false,\n };\n\n const chatRef = useRef<Chat<UI_MESSAGE>>(\n 'chat' in options ? options.chat : new Chat(optionsWithCallbacks),\n );\n\n const shouldRecreateChat =\n ('chat' in options && options.chat !== chatRef.current) ||\n ('id' in options && chatRef.current.id !== options.id);\n\n if (shouldRecreateChat) {\n chatRef.current =\n 'chat' in options ? options.chat : new Chat(optionsWithCallbacks);\n }\n\n const subscribeToMessages = useCallback(\n (update: () => void) =>\n chatRef.current['~registerMessagesCallback'](update, throttleWaitMs),\n // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [throttleWaitMs, chatRef.current.id],\n );\n\n const messages = useSyncExternalStore(\n subscribeToMessages,\n () => chatRef.current.messages,\n () => chatRef.current.messages,\n );\n\n const status = useSyncExternalStore(\n chatRef.current['~registerStatusCallback'],\n () => chatRef.current.status,\n () => chatRef.current.status,\n );\n\n const error = useSyncExternalStore(\n chatRef.current['~registerErrorCallback'],\n () => chatRef.current.error,\n () => chatRef.current.error,\n );\n\n const setMessages = useCallback(\n (\n messagesParam: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(chatRef.current.messages);\n }\n chatRef.current.messages = messagesParam;\n },\n [chatRef],\n );\n\n useEffect(() => {\n if (resume) {\n chatRef.current.resumeStream();\n }\n }, [resume, chatRef]);\n\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n regenerate: chatRef.current.regenerate,\n clearError: chatRef.current.clearError,\n stop: chatRef.current.stop,\n error,\n resumeStream: chatRef.current.resumeStream,\n status,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: chatRef.current.addToolOutput,\n addToolOutput: chatRef.current.addToolOutput,\n addToolApprovalResponse: chatRef.current.addToolApprovalResponse,\n };\n}\n","import { AbstractChat, ChatInit, ChatState, ChatStatus, UIMessage } from 'ai';\nimport { throttle } from './throttle';\n\nclass ReactChatState<\n UI_MESSAGE extends UIMessage,\n> implements ChatState<UI_MESSAGE> {\n #messages: UI_MESSAGE[];\n #status: ChatStatus = 'ready';\n #error: Error | undefined = undefined;\n\n #messagesCallbacks = new Set<() => void>();\n #statusCallbacks = new Set<() => void>();\n #errorCallbacks = new Set<() => void>();\n\n constructor(initialMessages: UI_MESSAGE[] = []) {\n this.#messages = initialMessages;\n }\n\n get status(): ChatStatus {\n return this.#status;\n }\n\n set status(newStatus: ChatStatus) {\n this.#status = newStatus;\n this.#callStatusCallbacks();\n }\n\n get error(): Error | undefined {\n return this.#error;\n }\n\n set error(newError: Error | undefined) {\n this.#error = newError;\n this.#callErrorCallbacks();\n }\n\n get messages(): UI_MESSAGE[] {\n return this.#messages;\n }\n\n set messages(newMessages: UI_MESSAGE[]) {\n this.#messages = [...newMessages];\n this.#callMessagesCallbacks();\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.#messages = this.#messages.concat(message);\n this.#callMessagesCallbacks();\n };\n\n popMessage = () => {\n this.#messages = this.#messages.slice(0, -1);\n this.#callMessagesCallbacks();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:\n this.snapshot(message),\n ...this.#messages.slice(index + 1),\n ];\n this.#callMessagesCallbacks();\n };\n\n snapshot = <T>(value: T): T => structuredClone(value);\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) => {\n const callback = throttleWaitMs\n ? throttle(onChange, throttleWaitMs)\n : onChange;\n this.#messagesCallbacks.add(callback);\n return () => {\n this.#messagesCallbacks.delete(callback);\n };\n };\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) => {\n this.#statusCallbacks.add(onChange);\n return () => {\n this.#statusCallbacks.delete(onChange);\n };\n };\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) => {\n this.#errorCallbacks.add(onChange);\n return () => {\n this.#errorCallbacks.delete(onChange);\n };\n };\n\n #callMessagesCallbacks = () => {\n this.#messagesCallbacks.forEach(callback => callback());\n };\n\n #callStatusCallbacks = () => {\n this.#statusCallbacks.forEach(callback => callback());\n };\n\n #callErrorCallbacks = () => {\n this.#errorCallbacks.forEach(callback => callback());\n };\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n #state: ReactChatState<UI_MESSAGE>;\n\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n this.#state = state;\n }\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) =>\n this.#state['~registerMessagesCallback'](onChange, throttleWaitMs);\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerStatusCallback'](onChange);\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerErrorCallback'](onChange);\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\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: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n FlexibleSchema,\n InferSchema,\n isAbortError,\n Resolvable,\n resolve,\n normalizeHeaders,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport { asSchema, DeepPartial, isDeepEqualData, parsePartialJson } from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\n * Callback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\n * The generated object (typed according to the schema).\n * Can be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\n * Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n * Can be a static object, a function that returns headers, or an async function\n * for dynamic auth tokens.\n */\n headers?: Resolvable<Record<string, string> | Headers>;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n\n /**\n * Clear the object state.\n */\n clear: () => void;\n};\n\nfunction useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n clearObject();\n\n setIsLoading(true);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n // Resolve headers at request time (supports async functions for dynamic auth tokens)\n const resolvedHeaders = await resolve(headers);\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...normalizeHeaders(resolvedHeaders),\n },\n credentials,\n signal: abortController.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 == null) {\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\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n const clear = () => {\n stop();\n clearObject();\n };\n\n const clearObject = () => {\n setError(undefined);\n setIsLoading(false);\n mutate(undefined);\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA,SAAS,aAAa,WAAW,QAAQ,4BAA4B;;;ACNrE,SAAS,oBAAgE;;;ACAzE,OAAO,sBAAsB;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,OAAO,iBAAiB,IAAI,MAAM,IAAI;AACzD;;;ADPA;AAGA,IAAM,iBAAN,MAEmC;AAAA,EASjC,YAAY,kBAAgC,CAAC,GAAG;AARhD;AACA,gCAAsB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AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["useCallback","useEffect","useRef","fetch","useRef","useEffect","useCallback","completion","useCallback","useId","useRef","useState","useSWR","fetch","error"]}
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@ai-sdk/react",
3
- "version": "4.0.0-beta.86",
3
+ "version": "4.0.0-beta.88",
4
+ "type": "module",
4
5
  "license": "Apache-2.0",
5
6
  "sideEffects": false,
6
7
  "main": "./dist/index.js",
7
- "module": "./dist/index.mjs",
8
8
  "types": "./dist/index.d.ts",
9
9
  "exports": {
10
10
  "./package.json": "./package.json",
11
11
  ".": {
12
12
  "types": "./dist/index.d.ts",
13
- "import": "./dist/index.mjs",
14
- "require": "./dist/index.js"
13
+ "import": "./dist/index.js",
14
+ "default": "./dist/index.js"
15
15
  }
16
16
  },
17
17
  "files": [
@@ -28,23 +28,24 @@
28
28
  "dependencies": {
29
29
  "swr": "^2.2.5",
30
30
  "throttleit": "2.1.0",
31
- "@ai-sdk/provider-utils": "5.0.0-beta.18",
32
- "ai": "7.0.0-beta.86"
31
+ "@ai-sdk/provider-utils": "5.0.0-beta.19",
32
+ "ai": "7.0.0-beta.88"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@testing-library/jest-dom": "^6.6.3",
36
- "@testing-library/user-event": "^14.5.2",
37
36
  "@testing-library/react": "^16.0.1",
37
+ "@testing-library/user-event": "^14.5.2",
38
38
  "@types/node": "20.17.24",
39
39
  "@types/react": "^18",
40
40
  "@types/react-dom": "^18",
41
+ "@vitejs/plugin-react": "4.3.3",
41
42
  "jsdom": "^24.0.0",
42
43
  "msw": "2.6.4",
43
44
  "react-dom": "^18 || ^19",
44
45
  "tsup": "^7.2.0",
45
46
  "typescript": "5.8.3",
46
47
  "zod": "3.25.76",
47
- "@ai-sdk/test-server": "2.0.0-beta.0",
48
+ "@ai-sdk/test-server": "2.0.0-beta.1",
48
49
  "@vercel/ai-tsconfig": "0.0.0"
49
50
  },
50
51
  "peerDependencies": {
package/dist/index.d.mts DELETED
@@ -1,178 +0,0 @@
1
- import { UIMessage, AbstractChat, ChatInit, CompletionRequestOptions, UseCompletionOptions, DeepPartial } from 'ai';
2
- export { CreateUIMessage, UIMessage, UseCompletionOptions } from 'ai';
3
- import { FlexibleSchema, FetchFunction, Resolvable, InferSchema } from '@ai-sdk/provider-utils';
4
-
5
- declare class Chat<UI_MESSAGE extends UIMessage> extends AbstractChat<UI_MESSAGE> {
6
- #private;
7
- constructor({ messages, ...init }: ChatInit<UI_MESSAGE>);
8
- '~registerMessagesCallback': (onChange: () => void, throttleWaitMs?: number) => (() => void);
9
- '~registerStatusCallback': (onChange: () => void) => (() => void);
10
- '~registerErrorCallback': (onChange: () => void) => (() => void);
11
- }
12
-
13
- type UseChatHelpers<UI_MESSAGE extends UIMessage> = {
14
- /**
15
- * The id of the chat.
16
- */
17
- readonly id: string;
18
- /**
19
- * Update the `messages` state locally. This is useful when you want to
20
- * edit the messages on the client, and then trigger the `reload` method
21
- * manually to regenerate the AI response.
22
- */
23
- setMessages: (messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[])) => void;
24
- error: Error | undefined;
25
- } & Pick<AbstractChat<UI_MESSAGE>, 'sendMessage' | 'regenerate' | 'stop' | 'resumeStream' | 'addToolResult' | 'addToolOutput' | 'addToolApprovalResponse' | 'status' | 'messages' | 'clearError'>;
26
- type UseChatOptions<UI_MESSAGE extends UIMessage> = ({
27
- chat: Chat<UI_MESSAGE>;
28
- } | ChatInit<UI_MESSAGE>) & {
29
- /**
30
- * Custom throttle wait in ms for the chat messages and data updates.
31
- * Default is undefined, which disables throttling.
32
- */
33
- experimental_throttle?: number;
34
- /**
35
- * Whether to resume an ongoing chat generation stream.
36
- */
37
- resume?: boolean;
38
- };
39
- declare function useChat<UI_MESSAGE extends UIMessage = UIMessage>({ experimental_throttle: throttleWaitMs, resume, ...options }?: UseChatOptions<UI_MESSAGE>): UseChatHelpers<UI_MESSAGE>;
40
-
41
- type UseCompletionHelpers = {
42
- /** The current completion result */
43
- completion: string;
44
- /**
45
- * Send a new prompt to the API endpoint and update the completion state.
46
- */
47
- complete: (prompt: string, options?: CompletionRequestOptions) => Promise<string | null | undefined>;
48
- /** The error object of the API request */
49
- error: undefined | Error;
50
- /**
51
- * Abort the current API request but keep the generated tokens.
52
- */
53
- stop: () => void;
54
- /**
55
- * Update the `completion` state locally.
56
- */
57
- setCompletion: (completion: string) => void;
58
- /** The current value of the input */
59
- input: string;
60
- /** setState-powered method to update the input value */
61
- setInput: React.Dispatch<React.SetStateAction<string>>;
62
- /**
63
- * An input/textarea-ready onChange handler to control the value of the input
64
- * @example
65
- * ```jsx
66
- * <input onChange={handleInputChange} value={input} />
67
- * ```
68
- */
69
- handleInputChange: (event: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => void;
70
- /**
71
- * Form submission handler to automatically reset input and append a user message
72
- * @example
73
- * ```jsx
74
- * <form onSubmit={handleSubmit}>
75
- * <input onChange={handleInputChange} value={input} />
76
- * </form>
77
- * ```
78
- */
79
- handleSubmit: (event?: {
80
- preventDefault?: () => void;
81
- }) => void;
82
- /** Whether the API request is in progress */
83
- isLoading: boolean;
84
- };
85
- declare function useCompletion({ api, id, initialCompletion, initialInput, credentials, headers, body, streamProtocol, fetch, onFinish, onError, experimental_throttle: throttleWaitMs, }?: UseCompletionOptions & {
86
- /**
87
- * Custom throttle wait in ms for the completion and data updates.
88
- * Default is undefined, which disables throttling.
89
- */
90
- experimental_throttle?: number;
91
- }): UseCompletionHelpers;
92
-
93
- type Experimental_UseObjectOptions<SCHEMA extends FlexibleSchema, RESULT> = {
94
- /**
95
- * The API endpoint. It should stream JSON that matches the schema as chunked text.
96
- */
97
- api: string;
98
- /**
99
- * A schema that defines the shape of the complete object.
100
- */
101
- schema: SCHEMA;
102
- /**
103
- * An unique identifier. If not provided, a random one will be
104
- * generated. When provided, the `useObject` hook with the same `id` will
105
- * have shared states across components.
106
- */
107
- id?: string;
108
- /**
109
- * An optional value for the initial object.
110
- */
111
- initialValue?: DeepPartial<RESULT>;
112
- /**
113
- * Custom fetch implementation. You can use it as a middleware to intercept requests,
114
- * or to provide a custom fetch implementation for e.g. testing.
115
- */
116
- fetch?: FetchFunction;
117
- /**
118
- * Callback that is called when the stream has finished.
119
- */
120
- onFinish?: (event: {
121
- /**
122
- * The generated object (typed according to the schema).
123
- * Can be undefined if the final object does not match the schema.
124
- */
125
- object: RESULT | undefined;
126
- /**
127
- * Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.
128
- */
129
- error: Error | undefined;
130
- }) => Promise<void> | void;
131
- /**
132
- * Callback function to be called when an error is encountered.
133
- */
134
- onError?: (error: Error) => void;
135
- /**
136
- * Additional HTTP headers to be included in the request.
137
- * Can be a static object, a function that returns headers, or an async function
138
- * for dynamic auth tokens.
139
- */
140
- headers?: Resolvable<Record<string, string> | Headers>;
141
- /**
142
- * The credentials mode to be used for the fetch request.
143
- * Possible values are: 'omit', 'same-origin', 'include'.
144
- * Defaults to 'same-origin'.
145
- */
146
- credentials?: RequestCredentials;
147
- };
148
- type Experimental_UseObjectHelpers<RESULT, INPUT> = {
149
- /**
150
- * Calls the API with the provided input as JSON body.
151
- */
152
- submit: (input: INPUT) => void;
153
- /**
154
- * The current value for the generated object. Updated as the API streams JSON chunks.
155
- */
156
- object: DeepPartial<RESULT> | undefined;
157
- /**
158
- * The error object of the API request if any.
159
- */
160
- error: Error | undefined;
161
- /**
162
- * Flag that indicates whether an API request is in progress.
163
- */
164
- isLoading: boolean;
165
- /**
166
- * Abort the current request immediately, keep the current partial object if any.
167
- */
168
- stop: () => void;
169
- /**
170
- * Clear the object state.
171
- */
172
- clear: () => void;
173
- };
174
- declare function useObject<SCHEMA extends FlexibleSchema, RESULT = InferSchema<SCHEMA>, INPUT = any>({ api, id, schema, // required, in the future we will use it for validation
175
- initialValue, fetch, onError, onFinish, headers, credentials, }: Experimental_UseObjectOptions<SCHEMA, RESULT>): Experimental_UseObjectHelpers<RESULT, INPUT>;
176
- declare const experimental_useObject: typeof useObject;
177
-
178
- export { Chat, Experimental_UseObjectHelpers, Experimental_UseObjectOptions, UseChatHelpers, UseChatOptions, UseCompletionHelpers, experimental_useObject, useChat, useCompletion };
package/dist/index.mjs DELETED
@@ -1,506 +0,0 @@
1
- var __accessCheck = (obj, member, msg) => {
2
- if (!member.has(obj))
3
- throw TypeError("Cannot " + msg);
4
- };
5
- var __privateGet = (obj, member, getter) => {
6
- __accessCheck(obj, member, "read from private field");
7
- return getter ? getter.call(obj) : member.get(obj);
8
- };
9
- var __privateAdd = (obj, member, value) => {
10
- if (member.has(obj))
11
- throw TypeError("Cannot add the same private member more than once");
12
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
13
- };
14
- var __privateSet = (obj, member, value, setter) => {
15
- __accessCheck(obj, member, "write to private field");
16
- setter ? setter.call(obj, value) : member.set(obj, value);
17
- return value;
18
- };
19
-
20
- // src/use-chat.ts
21
- import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";
22
-
23
- // src/chat.react.ts
24
- import { AbstractChat } from "ai";
25
-
26
- // src/throttle.ts
27
- import throttleFunction from "throttleit";
28
- function throttle(fn, waitMs) {
29
- return waitMs != null ? throttleFunction(fn, waitMs) : fn;
30
- }
31
-
32
- // src/chat.react.ts
33
- var _messages, _status, _error, _messagesCallbacks, _statusCallbacks, _errorCallbacks, _callMessagesCallbacks, _callStatusCallbacks, _callErrorCallbacks;
34
- var ReactChatState = class {
35
- constructor(initialMessages = []) {
36
- __privateAdd(this, _messages, void 0);
37
- __privateAdd(this, _status, "ready");
38
- __privateAdd(this, _error, void 0);
39
- __privateAdd(this, _messagesCallbacks, /* @__PURE__ */ new Set());
40
- __privateAdd(this, _statusCallbacks, /* @__PURE__ */ new Set());
41
- __privateAdd(this, _errorCallbacks, /* @__PURE__ */ new Set());
42
- this.pushMessage = (message) => {
43
- __privateSet(this, _messages, __privateGet(this, _messages).concat(message));
44
- __privateGet(this, _callMessagesCallbacks).call(this);
45
- };
46
- this.popMessage = () => {
47
- __privateSet(this, _messages, __privateGet(this, _messages).slice(0, -1));
48
- __privateGet(this, _callMessagesCallbacks).call(this);
49
- };
50
- this.replaceMessage = (index, message) => {
51
- __privateSet(this, _messages, [
52
- ...__privateGet(this, _messages).slice(0, index),
53
- // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:
54
- this.snapshot(message),
55
- ...__privateGet(this, _messages).slice(index + 1)
56
- ]);
57
- __privateGet(this, _callMessagesCallbacks).call(this);
58
- };
59
- this.snapshot = (value) => structuredClone(value);
60
- this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => {
61
- const callback = throttleWaitMs ? throttle(onChange, throttleWaitMs) : onChange;
62
- __privateGet(this, _messagesCallbacks).add(callback);
63
- return () => {
64
- __privateGet(this, _messagesCallbacks).delete(callback);
65
- };
66
- };
67
- this["~registerStatusCallback"] = (onChange) => {
68
- __privateGet(this, _statusCallbacks).add(onChange);
69
- return () => {
70
- __privateGet(this, _statusCallbacks).delete(onChange);
71
- };
72
- };
73
- this["~registerErrorCallback"] = (onChange) => {
74
- __privateGet(this, _errorCallbacks).add(onChange);
75
- return () => {
76
- __privateGet(this, _errorCallbacks).delete(onChange);
77
- };
78
- };
79
- __privateAdd(this, _callMessagesCallbacks, () => {
80
- __privateGet(this, _messagesCallbacks).forEach((callback) => callback());
81
- });
82
- __privateAdd(this, _callStatusCallbacks, () => {
83
- __privateGet(this, _statusCallbacks).forEach((callback) => callback());
84
- });
85
- __privateAdd(this, _callErrorCallbacks, () => {
86
- __privateGet(this, _errorCallbacks).forEach((callback) => callback());
87
- });
88
- __privateSet(this, _messages, initialMessages);
89
- }
90
- get status() {
91
- return __privateGet(this, _status);
92
- }
93
- set status(newStatus) {
94
- __privateSet(this, _status, newStatus);
95
- __privateGet(this, _callStatusCallbacks).call(this);
96
- }
97
- get error() {
98
- return __privateGet(this, _error);
99
- }
100
- set error(newError) {
101
- __privateSet(this, _error, newError);
102
- __privateGet(this, _callErrorCallbacks).call(this);
103
- }
104
- get messages() {
105
- return __privateGet(this, _messages);
106
- }
107
- set messages(newMessages) {
108
- __privateSet(this, _messages, [...newMessages]);
109
- __privateGet(this, _callMessagesCallbacks).call(this);
110
- }
111
- };
112
- _messages = new WeakMap();
113
- _status = new WeakMap();
114
- _error = new WeakMap();
115
- _messagesCallbacks = new WeakMap();
116
- _statusCallbacks = new WeakMap();
117
- _errorCallbacks = new WeakMap();
118
- _callMessagesCallbacks = new WeakMap();
119
- _callStatusCallbacks = new WeakMap();
120
- _callErrorCallbacks = new WeakMap();
121
- var _state;
122
- var Chat = class extends AbstractChat {
123
- constructor({ messages, ...init }) {
124
- const state = new ReactChatState(messages);
125
- super({ ...init, state });
126
- __privateAdd(this, _state, void 0);
127
- this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => __privateGet(this, _state)["~registerMessagesCallback"](onChange, throttleWaitMs);
128
- this["~registerStatusCallback"] = (onChange) => __privateGet(this, _state)["~registerStatusCallback"](onChange);
129
- this["~registerErrorCallback"] = (onChange) => __privateGet(this, _state)["~registerErrorCallback"](onChange);
130
- __privateSet(this, _state, state);
131
- }
132
- };
133
- _state = new WeakMap();
134
-
135
- // src/use-chat.ts
136
- function useChat({
137
- experimental_throttle: throttleWaitMs,
138
- resume = false,
139
- ...options
140
- } = {}) {
141
- const callbacksRef = useRef(
142
- !("chat" in options) ? {
143
- onToolCall: options.onToolCall,
144
- onData: options.onData,
145
- onFinish: options.onFinish,
146
- onError: options.onError,
147
- sendAutomaticallyWhen: options.sendAutomaticallyWhen
148
- } : {}
149
- );
150
- if (!("chat" in options)) {
151
- callbacksRef.current = {
152
- onToolCall: options.onToolCall,
153
- onData: options.onData,
154
- onFinish: options.onFinish,
155
- onError: options.onError,
156
- sendAutomaticallyWhen: options.sendAutomaticallyWhen
157
- };
158
- }
159
- const optionsWithCallbacks = {
160
- ...options,
161
- onToolCall: (arg) => {
162
- var _a, _b;
163
- return (_b = (_a = callbacksRef.current).onToolCall) == null ? void 0 : _b.call(_a, arg);
164
- },
165
- onData: (arg) => {
166
- var _a, _b;
167
- return (_b = (_a = callbacksRef.current).onData) == null ? void 0 : _b.call(_a, arg);
168
- },
169
- onFinish: (arg) => {
170
- var _a, _b;
171
- return (_b = (_a = callbacksRef.current).onFinish) == null ? void 0 : _b.call(_a, arg);
172
- },
173
- onError: (arg) => {
174
- var _a, _b;
175
- return (_b = (_a = callbacksRef.current).onError) == null ? void 0 : _b.call(_a, arg);
176
- },
177
- sendAutomaticallyWhen: (arg) => {
178
- var _a, _b, _c;
179
- return (_c = (_b = (_a = callbacksRef.current).sendAutomaticallyWhen) == null ? void 0 : _b.call(_a, arg)) != null ? _c : false;
180
- }
181
- };
182
- const chatRef = useRef(
183
- "chat" in options ? options.chat : new Chat(optionsWithCallbacks)
184
- );
185
- const shouldRecreateChat = "chat" in options && options.chat !== chatRef.current || "id" in options && chatRef.current.id !== options.id;
186
- if (shouldRecreateChat) {
187
- chatRef.current = "chat" in options ? options.chat : new Chat(optionsWithCallbacks);
188
- }
189
- const subscribeToMessages = useCallback(
190
- (update) => chatRef.current["~registerMessagesCallback"](update, throttleWaitMs),
191
- // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes
192
- // eslint-disable-next-line react-hooks/exhaustive-deps
193
- [throttleWaitMs, chatRef.current.id]
194
- );
195
- const messages = useSyncExternalStore(
196
- subscribeToMessages,
197
- () => chatRef.current.messages,
198
- () => chatRef.current.messages
199
- );
200
- const status = useSyncExternalStore(
201
- chatRef.current["~registerStatusCallback"],
202
- () => chatRef.current.status,
203
- () => chatRef.current.status
204
- );
205
- const error = useSyncExternalStore(
206
- chatRef.current["~registerErrorCallback"],
207
- () => chatRef.current.error,
208
- () => chatRef.current.error
209
- );
210
- const setMessages = useCallback(
211
- (messagesParam) => {
212
- if (typeof messagesParam === "function") {
213
- messagesParam = messagesParam(chatRef.current.messages);
214
- }
215
- chatRef.current.messages = messagesParam;
216
- },
217
- [chatRef]
218
- );
219
- useEffect(() => {
220
- if (resume) {
221
- chatRef.current.resumeStream();
222
- }
223
- }, [resume, chatRef]);
224
- return {
225
- id: chatRef.current.id,
226
- messages,
227
- setMessages,
228
- sendMessage: chatRef.current.sendMessage,
229
- regenerate: chatRef.current.regenerate,
230
- clearError: chatRef.current.clearError,
231
- stop: chatRef.current.stop,
232
- error,
233
- resumeStream: chatRef.current.resumeStream,
234
- status,
235
- /**
236
- * @deprecated Use `addToolOutput` instead.
237
- */
238
- addToolResult: chatRef.current.addToolOutput,
239
- addToolOutput: chatRef.current.addToolOutput,
240
- addToolApprovalResponse: chatRef.current.addToolApprovalResponse
241
- };
242
- }
243
-
244
- // src/use-completion.ts
245
- import {
246
- callCompletionApi
247
- } from "ai";
248
- import { useCallback as useCallback2, useEffect as useEffect2, useId, useRef as useRef2, useState } from "react";
249
- import useSWR from "swr";
250
- function useCompletion({
251
- api = "/api/completion",
252
- id,
253
- initialCompletion = "",
254
- initialInput = "",
255
- credentials,
256
- headers,
257
- body,
258
- streamProtocol = "data",
259
- fetch: fetch2,
260
- onFinish,
261
- onError,
262
- experimental_throttle: throttleWaitMs
263
- } = {}) {
264
- const hookId = useId();
265
- const completionId = id || hookId;
266
- const { data, mutate } = useSWR([api, completionId], null, {
267
- fallbackData: initialCompletion
268
- });
269
- const { data: isLoading = false, mutate: mutateLoading } = useSWR(
270
- [completionId, "loading"],
271
- null
272
- );
273
- const [error, setError] = useState(void 0);
274
- const completion = data;
275
- const [abortController, setAbortController] = useState(null);
276
- const extraMetadataRef = useRef2({
277
- credentials,
278
- headers,
279
- body
280
- });
281
- useEffect2(() => {
282
- extraMetadataRef.current = {
283
- credentials,
284
- headers,
285
- body
286
- };
287
- }, [credentials, headers, body]);
288
- const triggerRequest = useCallback2(
289
- async (prompt, options) => callCompletionApi({
290
- api,
291
- prompt,
292
- credentials: extraMetadataRef.current.credentials,
293
- headers: { ...extraMetadataRef.current.headers, ...options == null ? void 0 : options.headers },
294
- body: {
295
- ...extraMetadataRef.current.body,
296
- ...options == null ? void 0 : options.body
297
- },
298
- streamProtocol,
299
- fetch: fetch2,
300
- // throttle streamed ui updates:
301
- setCompletion: throttle(
302
- (completion2) => mutate(completion2, false),
303
- throttleWaitMs
304
- ),
305
- setLoading: mutateLoading,
306
- setError,
307
- setAbortController,
308
- onFinish,
309
- onError
310
- }),
311
- [
312
- mutate,
313
- mutateLoading,
314
- api,
315
- extraMetadataRef,
316
- setAbortController,
317
- onFinish,
318
- onError,
319
- setError,
320
- streamProtocol,
321
- fetch2,
322
- throttleWaitMs
323
- ]
324
- );
325
- const stop = useCallback2(() => {
326
- if (abortController) {
327
- abortController.abort();
328
- setAbortController(null);
329
- }
330
- }, [abortController]);
331
- const setCompletion = useCallback2(
332
- (completion2) => {
333
- mutate(completion2, false);
334
- },
335
- [mutate]
336
- );
337
- const complete = useCallback2(
338
- async (prompt, options) => {
339
- return triggerRequest(prompt, options);
340
- },
341
- [triggerRequest]
342
- );
343
- const [input, setInput] = useState(initialInput);
344
- const handleSubmit = useCallback2(
345
- (event) => {
346
- var _a;
347
- (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
348
- return input ? complete(input) : void 0;
349
- },
350
- [input, complete]
351
- );
352
- const handleInputChange = useCallback2(
353
- (e) => {
354
- setInput(e.target.value);
355
- },
356
- [setInput]
357
- );
358
- return {
359
- completion,
360
- complete,
361
- error,
362
- setCompletion,
363
- stop,
364
- input,
365
- setInput,
366
- handleInputChange,
367
- handleSubmit,
368
- isLoading
369
- };
370
- }
371
-
372
- // src/use-object.ts
373
- import {
374
- isAbortError,
375
- resolve,
376
- normalizeHeaders,
377
- safeValidateTypes
378
- } from "@ai-sdk/provider-utils";
379
- import { asSchema, isDeepEqualData, parsePartialJson } from "ai";
380
- import { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState2 } from "react";
381
- import useSWR2 from "swr";
382
- var getOriginalFetch = () => fetch;
383
- function useObject({
384
- api,
385
- id,
386
- schema,
387
- // required, in the future we will use it for validation
388
- initialValue,
389
- fetch: fetch2,
390
- onError,
391
- onFinish,
392
- headers,
393
- credentials
394
- }) {
395
- const hookId = useId2();
396
- const completionId = id != null ? id : hookId;
397
- const { data, mutate } = useSWR2(
398
- [api, completionId],
399
- null,
400
- { fallbackData: initialValue }
401
- );
402
- const [error, setError] = useState2(void 0);
403
- const [isLoading, setIsLoading] = useState2(false);
404
- const abortControllerRef = useRef3(null);
405
- const stop = useCallback3(() => {
406
- var _a;
407
- try {
408
- (_a = abortControllerRef.current) == null ? void 0 : _a.abort();
409
- } catch (e) {
410
- } finally {
411
- setIsLoading(false);
412
- abortControllerRef.current = null;
413
- }
414
- }, []);
415
- const submit = async (input) => {
416
- var _a;
417
- try {
418
- clearObject();
419
- setIsLoading(true);
420
- const abortController = new AbortController();
421
- abortControllerRef.current = abortController;
422
- const resolvedHeaders = await resolve(headers);
423
- const actualFetch = fetch2 != null ? fetch2 : getOriginalFetch();
424
- const response = await actualFetch(api, {
425
- method: "POST",
426
- headers: {
427
- "Content-Type": "application/json",
428
- ...normalizeHeaders(resolvedHeaders)
429
- },
430
- credentials,
431
- signal: abortController.signal,
432
- body: JSON.stringify(input)
433
- });
434
- if (!response.ok) {
435
- throw new Error(
436
- (_a = await response.text()) != null ? _a : "Failed to fetch the response."
437
- );
438
- }
439
- if (response.body == null) {
440
- throw new Error("The response body is empty.");
441
- }
442
- let accumulatedText = "";
443
- let latestObject = void 0;
444
- await response.body.pipeThrough(new TextDecoderStream()).pipeTo(
445
- new WritableStream({
446
- async write(chunk) {
447
- accumulatedText += chunk;
448
- const { value } = await parsePartialJson(accumulatedText);
449
- const currentObject = value;
450
- if (!isDeepEqualData(latestObject, currentObject)) {
451
- latestObject = currentObject;
452
- mutate(currentObject);
453
- }
454
- },
455
- async close() {
456
- setIsLoading(false);
457
- abortControllerRef.current = null;
458
- if (onFinish != null) {
459
- const validationResult = await safeValidateTypes({
460
- value: latestObject,
461
- schema: asSchema(schema)
462
- });
463
- onFinish(
464
- validationResult.success ? { object: validationResult.value, error: void 0 } : { object: void 0, error: validationResult.error }
465
- );
466
- }
467
- }
468
- })
469
- );
470
- } catch (error2) {
471
- if (isAbortError(error2)) {
472
- return;
473
- }
474
- if (onError && error2 instanceof Error) {
475
- onError(error2);
476
- }
477
- setIsLoading(false);
478
- setError(error2 instanceof Error ? error2 : new Error(String(error2)));
479
- }
480
- };
481
- const clear = () => {
482
- stop();
483
- clearObject();
484
- };
485
- const clearObject = () => {
486
- setError(void 0);
487
- setIsLoading(false);
488
- mutate(void 0);
489
- };
490
- return {
491
- submit,
492
- object: data,
493
- error,
494
- isLoading,
495
- stop,
496
- clear
497
- };
498
- }
499
- var experimental_useObject = useObject;
500
- export {
501
- Chat,
502
- experimental_useObject,
503
- useChat,
504
- useCompletion
505
- };
506
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/use-chat.ts","../src/chat.react.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["import {\n AbstractChat,\n ChatInit,\n type CreateUIMessage,\n type UIMessage,\n} from 'ai';\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { Chat } from './chat.react';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<UI_MESSAGE extends UIMessage> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolResult'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'status'\n | 'messages'\n | 'clearError'\n>;\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> = (\n | { chat: Chat<UI_MESSAGE> }\n | ChatInit<UI_MESSAGE>\n) & {\n /**\n * Custom throttle wait in ms for the chat messages and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n\n /**\n * Whether to resume an ongoing chat generation stream.\n */\n resume?: boolean;\n};\n\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>({\n experimental_throttle: throttleWaitMs,\n resume = false,\n ...options\n}: UseChatOptions<UI_MESSAGE> = {}): UseChatHelpers<UI_MESSAGE> {\n // Create a single ref for all callbacks to avoid stale closures\n const callbacksRef = useRef(\n !('chat' in options)\n ? {\n onToolCall: options.onToolCall,\n onData: options.onData,\n onFinish: options.onFinish,\n onError: options.onError,\n sendAutomaticallyWhen: options.sendAutomaticallyWhen,\n }\n : {},\n );\n\n // Update callbacks ref on each render to keep them current\n if (!('chat' in options)) {\n callbacksRef.current = {\n onToolCall: options.onToolCall,\n onData: options.onData,\n onFinish: options.onFinish,\n onError: options.onError,\n sendAutomaticallyWhen: options.sendAutomaticallyWhen,\n };\n }\n\n // Ensure the Chat instance has the latest callbacks\n const optionsWithCallbacks: typeof options = {\n ...options,\n onToolCall: arg => callbacksRef.current.onToolCall?.(arg),\n onData: arg => callbacksRef.current.onData?.(arg),\n onFinish: arg => callbacksRef.current.onFinish?.(arg),\n onError: arg => callbacksRef.current.onError?.(arg),\n sendAutomaticallyWhen: arg =>\n callbacksRef.current.sendAutomaticallyWhen?.(arg) ?? false,\n };\n\n const chatRef = useRef<Chat<UI_MESSAGE>>(\n 'chat' in options ? options.chat : new Chat(optionsWithCallbacks),\n );\n\n const shouldRecreateChat =\n ('chat' in options && options.chat !== chatRef.current) ||\n ('id' in options && chatRef.current.id !== options.id);\n\n if (shouldRecreateChat) {\n chatRef.current =\n 'chat' in options ? options.chat : new Chat(optionsWithCallbacks);\n }\n\n const subscribeToMessages = useCallback(\n (update: () => void) =>\n chatRef.current['~registerMessagesCallback'](update, throttleWaitMs),\n // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [throttleWaitMs, chatRef.current.id],\n );\n\n const messages = useSyncExternalStore(\n subscribeToMessages,\n () => chatRef.current.messages,\n () => chatRef.current.messages,\n );\n\n const status = useSyncExternalStore(\n chatRef.current['~registerStatusCallback'],\n () => chatRef.current.status,\n () => chatRef.current.status,\n );\n\n const error = useSyncExternalStore(\n chatRef.current['~registerErrorCallback'],\n () => chatRef.current.error,\n () => chatRef.current.error,\n );\n\n const setMessages = useCallback(\n (\n messagesParam: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(chatRef.current.messages);\n }\n chatRef.current.messages = messagesParam;\n },\n [chatRef],\n );\n\n useEffect(() => {\n if (resume) {\n chatRef.current.resumeStream();\n }\n }, [resume, chatRef]);\n\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n regenerate: chatRef.current.regenerate,\n clearError: chatRef.current.clearError,\n stop: chatRef.current.stop,\n error,\n resumeStream: chatRef.current.resumeStream,\n status,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: chatRef.current.addToolOutput,\n addToolOutput: chatRef.current.addToolOutput,\n addToolApprovalResponse: chatRef.current.addToolApprovalResponse,\n };\n}\n","import { AbstractChat, ChatInit, ChatState, ChatStatus, UIMessage } from 'ai';\nimport { throttle } from './throttle';\n\nclass ReactChatState<\n UI_MESSAGE extends UIMessage,\n> implements ChatState<UI_MESSAGE> {\n #messages: UI_MESSAGE[];\n #status: ChatStatus = 'ready';\n #error: Error | undefined = undefined;\n\n #messagesCallbacks = new Set<() => void>();\n #statusCallbacks = new Set<() => void>();\n #errorCallbacks = new Set<() => void>();\n\n constructor(initialMessages: UI_MESSAGE[] = []) {\n this.#messages = initialMessages;\n }\n\n get status(): ChatStatus {\n return this.#status;\n }\n\n set status(newStatus: ChatStatus) {\n this.#status = newStatus;\n this.#callStatusCallbacks();\n }\n\n get error(): Error | undefined {\n return this.#error;\n }\n\n set error(newError: Error | undefined) {\n this.#error = newError;\n this.#callErrorCallbacks();\n }\n\n get messages(): UI_MESSAGE[] {\n return this.#messages;\n }\n\n set messages(newMessages: UI_MESSAGE[]) {\n this.#messages = [...newMessages];\n this.#callMessagesCallbacks();\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.#messages = this.#messages.concat(message);\n this.#callMessagesCallbacks();\n };\n\n popMessage = () => {\n this.#messages = this.#messages.slice(0, -1);\n this.#callMessagesCallbacks();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:\n this.snapshot(message),\n ...this.#messages.slice(index + 1),\n ];\n this.#callMessagesCallbacks();\n };\n\n snapshot = <T>(value: T): T => structuredClone(value);\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) => {\n const callback = throttleWaitMs\n ? throttle(onChange, throttleWaitMs)\n : onChange;\n this.#messagesCallbacks.add(callback);\n return () => {\n this.#messagesCallbacks.delete(callback);\n };\n };\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) => {\n this.#statusCallbacks.add(onChange);\n return () => {\n this.#statusCallbacks.delete(onChange);\n };\n };\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) => {\n this.#errorCallbacks.add(onChange);\n return () => {\n this.#errorCallbacks.delete(onChange);\n };\n };\n\n #callMessagesCallbacks = () => {\n this.#messagesCallbacks.forEach(callback => callback());\n };\n\n #callStatusCallbacks = () => {\n this.#statusCallbacks.forEach(callback => callback());\n };\n\n #callErrorCallbacks = () => {\n this.#errorCallbacks.forEach(callback => callback());\n };\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n #state: ReactChatState<UI_MESSAGE>;\n\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n this.#state = state;\n }\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) =>\n this.#state['~registerMessagesCallback'](onChange, throttleWaitMs);\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerStatusCallback'](onChange);\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerErrorCallback'](onChange);\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\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: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n FlexibleSchema,\n InferSchema,\n isAbortError,\n Resolvable,\n resolve,\n normalizeHeaders,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport { asSchema, DeepPartial, isDeepEqualData, parsePartialJson } from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\n * Callback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\n * The generated object (typed according to the schema).\n * Can be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\n * Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n * Can be a static object, a function that returns headers, or an async function\n * for dynamic auth tokens.\n */\n headers?: Resolvable<Record<string, string> | Headers>;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n\n /**\n * Clear the object state.\n */\n clear: () => void;\n};\n\nfunction useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n clearObject();\n\n setIsLoading(true);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n // Resolve headers at request time (supports async functions for dynamic auth tokens)\n const resolvedHeaders = await resolve(headers);\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...normalizeHeaders(resolvedHeaders),\n },\n credentials,\n signal: abortController.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 == null) {\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\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n const clear = () => {\n stop();\n clearObject();\n };\n\n const clearObject = () => {\n setError(undefined);\n setIsLoading(false);\n mutate(undefined);\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA,SAAS,aAAa,WAAW,QAAQ,4BAA4B;;;ACNrE,SAA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,EACF;AAEA,QAAM,QAAQ,MAAM;AAClB,SAAK;AACL,gBAAY;AAAA,EACd;AAEA,QAAM,cAAc,MAAM;AACxB,aAAS,MAAS;AAClB,iBAAa,KAAK;AAClB,WAAO,MAAS;AAAA,EAClB;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["useCallback","useEffect","useRef","fetch","useRef","useEffect","useCallback","completion","useCallback","useId","useRef","useState","useSWR","fetch","error"]}