{"version":3,"sources":["jsdelivr-header.js","/npm/@ai-sdk/react@3.0.23/src/index.ts","/npm/@ai-sdk/react@3.0.23/src/use-chat.ts","/npm/@ai-sdk/react@3.0.23/src/chat.react.ts","/npm/@ai-sdk/react@3.0.23/src/throttle.ts","/npm/@ai-sdk/react@3.0.23/src/use-completion.ts","/npm/@ai-sdk/react@3.0.23/src/use-object.ts"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,soCCNA,YAAA,GAAA,SAAA,YAAA,CAAA,KAAA,IAAA,KAAA,uBAAA,IAAA,uBAAA,QAAA,IAAA,QAAA,cAAA,IAAA,gBAAA,OAAA,QAAA,aAAA,aCMA,ICNA,UAAA,QAAA,OAAA,mBAAA,iBAAA,gBAAA,uBAAA,qBAAA,oBDMA,aAAqE,QAAA,SCNrE,UAAyE,QAAA,MCAzE,kBAA6B,QAAA,QAAA,eAEtB,SAAS,SACd,EACA,GAEA,OAAiB,MAAV,GAAU,EAAO,kBAAA,SAAiB,EAAI,GAAU,CACzD,CDJA,IAHA,OAGM,eAAN,MAWE,WAAA,CAAY,EAAgC,IAR5C,aAAA,KAAA,eAAA,GACA,aAAA,KAAA,QAAsB,SACtB,aAAA,KAAA,YAA4B,GAE5B,aAAA,KAAA,mBAAqB,IAAI,KACzB,aAAA,KAAA,iBAAmB,IAAI,KACvB,aAAA,KAAA,gBAAkB,IAAI,KAiCtB,KAAA,YAAe,IACb,aAAA,KAAK,UAAY,aAAA,KAAK,WAAU,OAAO,IACvC,aAAA,KAAK,wBAAL,KAAA,KAAA,EAGF,KAAA,WAAa,KACX,aAAA,KAAK,UAAY,aAAA,KAAK,WAAU,MAAM,GAAG,IACzC,aAAA,KAAK,wBAAL,KAAA,KAAA,EAGF,KAAA,eAAiB,CAAC,EAAe,KAC/B,aAAA,KAAK,UAAY,IACZ,aAAA,KAAK,WAAU,MAAM,EAAG,GAE3B,KAAK,SAAS,MACX,aAAA,KAAK,WAAU,MAAM,EAAQ,KAElC,aAA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.23/dist/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/@ai-sdk/react@3.0.23/dist/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","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  /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault 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  const chatRef = useRef<Chat<UI_MESSAGE>>(\n    'chat' in options ? options.chat : new Chat(options),\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 = 'chat' in options ? options.chat : new Chat(options);\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<UI_MESSAGE extends UIMessage>\n  implements ChatState<UI_MESSAGE>\n{\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  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  /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n    */\n  fetch?: FetchFunction;\n\n  /**\nCallback that is called when the stream has finished.\n     */\n  onFinish?: (event: {\n    /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n   */\n    object: RESULT | undefined;\n\n    /**\nOptional 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   */\n  headers?: 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 (ignored) {\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      const actualFetch = fetch ?? getOriginalFetch();\n      const response = await actualFetch(api, {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/json',\n          ...headers,\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"]}