@copilotkit/react-textarea 1.0.9-pre-async-submit-message.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +18 -5
  2. package/dist/{chunk-PNNCL732.mjs → chunk-23Q6A46J.mjs} +2 -2
  3. package/dist/{chunk-PNNCL732.mjs.map → chunk-23Q6A46J.mjs.map} +1 -1
  4. package/dist/{chunk-2XUEWZC3.mjs → chunk-2JDQ4WX4.mjs} +2 -2
  5. package/dist/{chunk-OJXLHIYQ.mjs → chunk-4CVSOOJY.mjs} +2 -2
  6. package/dist/{chunk-OJXLHIYQ.mjs.map → chunk-4CVSOOJY.mjs.map} +1 -1
  7. package/dist/{chunk-NZI35NYE.mjs → chunk-5EDG5WL3.mjs} +3 -3
  8. package/dist/{chunk-TTOZXUEA.mjs → chunk-BHSXGMP7.mjs} +3 -2
  9. package/dist/{chunk-TTOZXUEA.mjs.map → chunk-BHSXGMP7.mjs.map} +1 -1
  10. package/dist/{chunk-WDV7S66U.mjs → chunk-MUAPKB7X.mjs} +5 -3
  11. package/dist/chunk-MUAPKB7X.mjs.map +1 -0
  12. package/dist/{chunk-WV7RRJEN.mjs → chunk-ZGE5QSUF.mjs} +5 -5
  13. package/dist/components/base-copilot-textarea/base-copilot-textarea.js +2 -2
  14. package/dist/components/base-copilot-textarea/base-copilot-textarea.js.map +1 -1
  15. package/dist/components/base-copilot-textarea/base-copilot-textarea.mjs +3 -3
  16. package/dist/components/copilot-textarea/copilot-textarea.js +8 -5
  17. package/dist/components/copilot-textarea/copilot-textarea.js.map +1 -1
  18. package/dist/components/copilot-textarea/copilot-textarea.mjs +7 -7
  19. package/dist/components/index.js +8 -5
  20. package/dist/components/index.js.map +1 -1
  21. package/dist/components/index.mjs +7 -7
  22. package/dist/hooks/base-copilot-textarea-implementation/use-autosuggestions.js +1 -1
  23. package/dist/hooks/base-copilot-textarea-implementation/use-autosuggestions.js.map +1 -1
  24. package/dist/hooks/base-copilot-textarea-implementation/use-autosuggestions.mjs +1 -1
  25. package/dist/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.js +2 -1
  26. package/dist/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.js.map +1 -1
  27. package/dist/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.mjs +1 -1
  28. package/dist/hooks/make-autosuggestions-function/use-make-standard-insertion-function.js +4 -2
  29. package/dist/hooks/make-autosuggestions-function/use-make-standard-insertion-function.js.map +1 -1
  30. package/dist/hooks/make-autosuggestions-function/use-make-standard-insertion-function.mjs +1 -1
  31. package/dist/index.js +8 -5
  32. package/dist/index.js.map +1 -1
  33. package/dist/index.mjs +7 -7
  34. package/dist/types/autosuggestions-config/autosuggestions-config.js +1 -1
  35. package/dist/types/autosuggestions-config/autosuggestions-config.js.map +1 -1
  36. package/dist/types/autosuggestions-config/autosuggestions-config.mjs +2 -2
  37. package/dist/types/autosuggestions-config/index.js +1 -1
  38. package/dist/types/autosuggestions-config/index.js.map +1 -1
  39. package/dist/types/autosuggestions-config/index.mjs +2 -2
  40. package/dist/types/base/base-autosuggestions-config.js +1 -1
  41. package/dist/types/base/base-autosuggestions-config.js.map +1 -1
  42. package/dist/types/base/base-autosuggestions-config.mjs +1 -1
  43. package/dist/types/base/index.js +1 -1
  44. package/dist/types/base/index.js.map +1 -1
  45. package/dist/types/base/index.mjs +1 -1
  46. package/dist/types/index.js +1 -1
  47. package/dist/types/index.js.map +1 -1
  48. package/dist/types/index.mjs +2 -2
  49. package/package.json +10 -8
  50. package/src/hooks/base-copilot-textarea-implementation/use-autosuggestions.ts +4 -3
  51. package/src/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.tsx +1 -0
  52. package/src/hooks/make-autosuggestions-function/use-make-standard-insertion-function.tsx +2 -0
  53. package/src/types/base/base-autosuggestions-config.tsx +1 -1
  54. package/tsconfig.json +1 -1
  55. package/dist/chunk-WDV7S66U.mjs.map +0 -1
  56. /package/dist/{chunk-2XUEWZC3.mjs.map → chunk-2JDQ4WX4.mjs.map} +0 -0
  57. /package/dist/{chunk-NZI35NYE.mjs.map → chunk-5EDG5WL3.mjs.map} +0 -0
  58. /package/dist/{chunk-WV7RRJEN.mjs.map → chunk-ZGE5QSUF.mjs.map} +0 -0
@@ -1,20 +1,20 @@
1
1
  import "../chunk-MMVDU6DF.mjs";
2
2
  import {
3
3
  CopilotTextarea
4
- } from "../chunk-WV7RRJEN.mjs";
5
- import "../chunk-WDV7S66U.mjs";
6
- import "../chunk-TTOZXUEA.mjs";
4
+ } from "../chunk-ZGE5QSUF.mjs";
5
+ import "../chunk-MUAPKB7X.mjs";
6
+ import "../chunk-BHSXGMP7.mjs";
7
7
  import "../chunk-RUV6NBIF.mjs";
8
- import "../chunk-2XUEWZC3.mjs";
8
+ import "../chunk-2JDQ4WX4.mjs";
9
9
  import "../chunk-EJGGLWWR.mjs";
10
10
  import "../chunk-MCNXIA4Q.mjs";
11
11
  import "../chunk-XA2TLAXU.mjs";
12
12
  import {
13
13
  BaseCopilotTextarea
14
- } from "../chunk-NZI35NYE.mjs";
14
+ } from "../chunk-5EDG5WL3.mjs";
15
15
  import "../chunk-2C7O2EVM.mjs";
16
16
  import "../chunk-GQN2HYFJ.mjs";
17
- import "../chunk-PNNCL732.mjs";
17
+ import "../chunk-23Q6A46J.mjs";
18
18
  import "../chunk-AJ5OMEXM.mjs";
19
19
  import "../chunk-DRV2FOHZ.mjs";
20
20
  import "../chunk-4NHVQZ67.mjs";
@@ -38,7 +38,7 @@ import "../chunk-QQLDM3AI.mjs";
38
38
  import "../chunk-2QDCE7PD.mjs";
39
39
  import "../chunk-YLFAIYRY.mjs";
40
40
  import "../chunk-WJHSY5T6.mjs";
41
- import "../chunk-OJXLHIYQ.mjs";
41
+ import "../chunk-4CVSOOJY.mjs";
42
42
  import "../chunk-224UKA7C.mjs";
43
43
  import "../chunk-XW3ICO4S.mjs";
44
44
  import "../chunk-DFTV4TST.mjs";
@@ -151,7 +151,7 @@ function useAutosuggestions(debounceTime, shouldAcceptAutosuggestionOnKeyPress,
151
151
  const keyDownOrTouchHandler = (0, import_react.useCallback)(
152
152
  (event) => {
153
153
  if (currentAutocompleteSuggestion) {
154
- const shouldAcceptSuggestion = event instanceof KeyboardEvent ? shouldAcceptAutosuggestionOnKeyPress(event) : shouldAcceptAutosuggestionOnTouch(event);
154
+ const shouldAcceptSuggestion = event.type === "touchstart" ? shouldAcceptAutosuggestionOnTouch(event) : shouldAcceptAutosuggestionOnKeyPress(event);
155
155
  if (shouldAcceptSuggestion) {
156
156
  event.preventDefault();
157
157
  insertAutocompleteSuggestion(currentAutocompleteSuggestion);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/hooks/base-copilot-textarea-implementation/use-autosuggestions.ts","../../../src/lib/debouncer.ts","../../../src/lib/utils.ts","../../../src/types/base/editor-autocomplete-state.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { Debouncer } from \"../../lib/debouncer\";\nimport { nullableCompatibleEqualityCheck } from \"../../lib/utils\";\nimport { AutosuggestionsBareFunction } from \"../../types/base\";\nimport { AutosuggestionState } from \"../../types/base/autosuggestion-state\";\nimport {\n EditorAutocompleteState,\n areEqual_autocompleteState,\n} from \"../../types/base/editor-autocomplete-state\";\n\nexport interface UseAutosuggestionsResult {\n currentAutocompleteSuggestion: AutosuggestionState | null;\n onChangeHandler: (newEditorState: EditorAutocompleteState | null) => void;\n onKeyDownHandler: (event: React.KeyboardEvent<HTMLDivElement>) => void;\n onTouchStartHandler: (event: React.TouchEvent<HTMLDivElement>) => void;\n}\n\nexport function useAutosuggestions(\n debounceTime: number,\n shouldAcceptAutosuggestionOnKeyPress: (event: React.KeyboardEvent<HTMLDivElement>) => boolean,\n shouldAcceptAutosuggestionOnTouch: (event: React.TouchEvent<HTMLDivElement>) => boolean,\n autosuggestionFunction: AutosuggestionsBareFunction,\n insertAutocompleteSuggestion: (suggestion: AutosuggestionState) => void,\n disableWhenEmpty: boolean,\n disabled: boolean,\n): UseAutosuggestionsResult {\n const [previousAutocompleteState, setPreviousAutocompleteState] =\n useState<EditorAutocompleteState | null>(null);\n\n const [currentAutocompleteSuggestion, setCurrentAutocompleteSuggestion] =\n useState<AutosuggestionState | null>(null);\n\n const awaitForAndAppendSuggestion: (\n editorAutocompleteState: EditorAutocompleteState,\n abortSignal: AbortSignal,\n ) => Promise<void> = useCallback(\n async (editorAutocompleteState: EditorAutocompleteState, abortSignal: AbortSignal) => {\n // early return if disabled\n if (disabled) {\n return;\n }\n\n if (\n disableWhenEmpty &&\n editorAutocompleteState.textBeforeCursor === \"\" &&\n editorAutocompleteState.textAfterCursor === \"\"\n ) {\n return;\n }\n\n // fetch the suggestion\n const suggestion = await autosuggestionFunction(editorAutocompleteState, abortSignal);\n\n // We'll assume for now that the autocomplete function might or might not respect the abort signal.\n if (!suggestion || abortSignal.aborted) {\n throw new DOMException(\"Aborted\", \"AbortError\");\n }\n\n setCurrentAutocompleteSuggestion({\n text: suggestion,\n point: editorAutocompleteState.cursorPoint,\n });\n },\n [autosuggestionFunction, setCurrentAutocompleteSuggestion, disableWhenEmpty, disabled],\n );\n\n const debouncedFunction = useMemo(\n () => new Debouncer<[editorAutocompleteState: EditorAutocompleteState]>(debounceTime),\n [debounceTime],\n );\n\n // clean current state when unmounting or disabling\n useEffect(() => {\n return () => {\n debouncedFunction.cancel();\n setCurrentAutocompleteSuggestion(null);\n };\n }, [debouncedFunction, disabled]);\n\n const onChange = useCallback(\n (newEditorState: EditorAutocompleteState | null) => {\n const editorStateHasChanged = !nullableCompatibleEqualityCheck(\n areEqual_autocompleteState,\n previousAutocompleteState,\n newEditorState,\n );\n setPreviousAutocompleteState(newEditorState);\n\n // if no change, do nothing\n if (!editorStateHasChanged) {\n return;\n }\n\n // if change, then first null out the current suggestion\n setCurrentAutocompleteSuggestion(null);\n\n // then try to get a new suggestion, debouncing to avoid too many requests while typing\n if (newEditorState) {\n debouncedFunction.debounce(awaitForAndAppendSuggestion, newEditorState);\n } else {\n debouncedFunction.cancel();\n }\n },\n [\n previousAutocompleteState,\n setPreviousAutocompleteState,\n debouncedFunction,\n awaitForAndAppendSuggestion,\n setCurrentAutocompleteSuggestion,\n ],\n );\n\n const keyDownOrTouchHandler = useCallback(\n (event: React.KeyboardEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>) => {\n if (currentAutocompleteSuggestion) {\n const shouldAcceptSuggestion =\n event instanceof KeyboardEvent\n ? shouldAcceptAutosuggestionOnKeyPress(event as React.KeyboardEvent<HTMLDivElement>)\n : shouldAcceptAutosuggestionOnTouch(event as React.TouchEvent<HTMLDivElement>);\n if (shouldAcceptSuggestion) {\n event.preventDefault();\n insertAutocompleteSuggestion(currentAutocompleteSuggestion);\n setCurrentAutocompleteSuggestion(null);\n }\n }\n },\n [\n currentAutocompleteSuggestion,\n setCurrentAutocompleteSuggestion,\n insertAutocompleteSuggestion,\n shouldAcceptAutosuggestionOnKeyPress,\n ],\n );\n\n return {\n currentAutocompleteSuggestion,\n onChangeHandler: onChange,\n onKeyDownHandler: keyDownOrTouchHandler,\n onTouchStartHandler: keyDownOrTouchHandler,\n };\n}\n","export type AsyncFunction<T extends any[]> = (...args: [...T, AbortSignal]) => Promise<void>;\n\nexport class Debouncer<T extends any[]> {\n private timeoutId?: ReturnType<typeof setTimeout>;\n private activeAbortController?: AbortController;\n\n constructor(private wait: number) {}\n\n debounce = async (func: AsyncFunction<T>, ...args: T) => {\n // Abort the previous promise immediately\n this.cancel();\n\n this.timeoutId = setTimeout(async () => {\n try {\n this.activeAbortController = new AbortController();\n\n // Pass the signal to the async function, assuming it supports it\n await func(...args, this.activeAbortController.signal);\n\n this.activeAbortController = undefined;\n } catch (error) {}\n }, this.wait);\n };\n\n cancel = () => {\n if (this.activeAbortController) {\n this.activeAbortController.abort();\n this.activeAbortController = undefined;\n }\n\n if (this.timeoutId !== undefined) {\n clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n }\n };\n}\n","import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\nexport async function fetcher<JSON = any>(input: RequestInfo, init?: RequestInit): Promise<JSON> {\n const res = await fetch(input, init);\n\n if (!res.ok) {\n const json = await res.json();\n if (json.error) {\n const error = new Error(json.error) as Error & {\n status: number;\n };\n error.status = res.status;\n throw error;\n } else {\n throw new Error(\"An unexpected error occurred\");\n }\n }\n\n return res.json();\n}\n\nexport function formatDate(input: string | number | Date): string {\n const date = new Date(input);\n return date.toLocaleDateString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n });\n}\n\nexport const arraysAreEqual = (arr1: number[], arr2: number[]): boolean =>\n arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);\n\nexport function nullableCompatibleEqualityCheck<T>(\n naiveEqualityCheck: (a: T, b: T) => boolean,\n a: T | null | undefined,\n b: T | null | undefined,\n): boolean {\n if (a === null || a === undefined || b === null || b === undefined) {\n return a === b;\n }\n\n return naiveEqualityCheck(a, b);\n}\n","import { BasePoint } from \"slate\";\nimport { arraysAreEqual } from \"../../lib/utils\";\n\nexport interface EditorAutocompleteState {\n cursorPoint: BasePoint;\n textBeforeCursor: string;\n textAfterCursor: string;\n}\n\nexport function areEqual_autocompleteState(\n prev: EditorAutocompleteState,\n next: EditorAutocompleteState,\n) {\n return (\n prev.cursorPoint.offset === next.cursorPoint.offset &&\n arraysAreEqual(prev.cursorPoint.path, next.cursorPoint.path) &&\n prev.textBeforeCursor === next.textBeforeCursor &&\n prev.textAfterCursor === next.textAfterCursor\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA0D;;;ACEnD,IAAM,YAAN,MAAiC;AAAA,EAItC,YAAoB,MAAc;AAAd;AAEpB,oBAAW,CAAO,SAA2B,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I;AAAA,QACvC;AAAA,MACF;AAAA,IACF;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB;AAAA,IACjB,kBAAkB;AAAA,IAClB,qBAAqB;AAAA,EACvB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/hooks/base-copilot-textarea-implementation/use-autosuggestions.ts","../../../src/lib/debouncer.ts","../../../src/lib/utils.ts","../../../src/types/base/editor-autocomplete-state.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { Debouncer } from \"../../lib/debouncer\";\nimport { nullableCompatibleEqualityCheck } from \"../../lib/utils\";\nimport { AutosuggestionsBareFunction } from \"../../types/base\";\nimport { AutosuggestionState } from \"../../types/base/autosuggestion-state\";\nimport {\n EditorAutocompleteState,\n areEqual_autocompleteState,\n} from \"../../types/base/editor-autocomplete-state\";\n\nexport interface UseAutosuggestionsResult {\n currentAutocompleteSuggestion: AutosuggestionState | null;\n onChangeHandler: (newEditorState: EditorAutocompleteState | null) => void;\n onKeyDownHandler: (event: React.KeyboardEvent<HTMLDivElement>) => void;\n onTouchStartHandler: (event: React.TouchEvent<HTMLDivElement>) => void;\n}\n\nexport function useAutosuggestions(\n debounceTime: number,\n shouldAcceptAutosuggestionOnKeyPress: (event: React.KeyboardEvent<HTMLDivElement>) => boolean,\n shouldAcceptAutosuggestionOnTouch: (event: React.TouchEvent<HTMLDivElement>) => boolean,\n autosuggestionFunction: AutosuggestionsBareFunction,\n insertAutocompleteSuggestion: (suggestion: AutosuggestionState) => void,\n disableWhenEmpty: boolean,\n disabled: boolean,\n): UseAutosuggestionsResult {\n const [previousAutocompleteState, setPreviousAutocompleteState] =\n useState<EditorAutocompleteState | null>(null);\n\n const [currentAutocompleteSuggestion, setCurrentAutocompleteSuggestion] =\n useState<AutosuggestionState | null>(null);\n\n const awaitForAndAppendSuggestion: (\n editorAutocompleteState: EditorAutocompleteState,\n abortSignal: AbortSignal,\n ) => Promise<void> = useCallback(\n async (editorAutocompleteState: EditorAutocompleteState, abortSignal: AbortSignal) => {\n // early return if disabled\n if (disabled) {\n return;\n }\n\n if (\n disableWhenEmpty &&\n editorAutocompleteState.textBeforeCursor === \"\" &&\n editorAutocompleteState.textAfterCursor === \"\"\n ) {\n return;\n }\n\n // fetch the suggestion\n const suggestion = await autosuggestionFunction(editorAutocompleteState, abortSignal);\n\n // We'll assume for now that the autocomplete function might or might not respect the abort signal.\n if (!suggestion || abortSignal.aborted) {\n throw new DOMException(\"Aborted\", \"AbortError\");\n }\n\n setCurrentAutocompleteSuggestion({\n text: suggestion,\n point: editorAutocompleteState.cursorPoint,\n });\n },\n [autosuggestionFunction, setCurrentAutocompleteSuggestion, disableWhenEmpty, disabled],\n );\n\n const debouncedFunction = useMemo(\n () => new Debouncer<[editorAutocompleteState: EditorAutocompleteState]>(debounceTime),\n [debounceTime],\n );\n\n // clean current state when unmounting or disabling\n useEffect(() => {\n return () => {\n debouncedFunction.cancel();\n setCurrentAutocompleteSuggestion(null);\n };\n }, [debouncedFunction, disabled]);\n\n const onChange = useCallback(\n (newEditorState: EditorAutocompleteState | null) => {\n const editorStateHasChanged = !nullableCompatibleEqualityCheck(\n areEqual_autocompleteState,\n previousAutocompleteState,\n newEditorState,\n );\n setPreviousAutocompleteState(newEditorState);\n\n // if no change, do nothing\n if (!editorStateHasChanged) {\n return;\n }\n\n // if change, then first null out the current suggestion\n setCurrentAutocompleteSuggestion(null);\n\n // then try to get a new suggestion, debouncing to avoid too many requests while typing\n if (newEditorState) {\n debouncedFunction.debounce(awaitForAndAppendSuggestion, newEditorState);\n } else {\n debouncedFunction.cancel();\n }\n },\n [\n previousAutocompleteState,\n setPreviousAutocompleteState,\n debouncedFunction,\n awaitForAndAppendSuggestion,\n setCurrentAutocompleteSuggestion,\n ],\n );\n\n const keyDownOrTouchHandler = useCallback(\n (event: React.KeyboardEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>) => {\n if (currentAutocompleteSuggestion) {\n const shouldAcceptSuggestion =\n event.type === \"touchstart\"\n ? shouldAcceptAutosuggestionOnTouch(event as React.TouchEvent<HTMLDivElement>)\n : shouldAcceptAutosuggestionOnKeyPress(event as React.KeyboardEvent<HTMLDivElement>);\n\n if (shouldAcceptSuggestion) {\n event.preventDefault();\n insertAutocompleteSuggestion(currentAutocompleteSuggestion);\n setCurrentAutocompleteSuggestion(null);\n }\n }\n },\n [\n currentAutocompleteSuggestion,\n setCurrentAutocompleteSuggestion,\n insertAutocompleteSuggestion,\n shouldAcceptAutosuggestionOnKeyPress,\n ],\n );\n\n return {\n currentAutocompleteSuggestion,\n onChangeHandler: onChange,\n onKeyDownHandler: keyDownOrTouchHandler,\n onTouchStartHandler: keyDownOrTouchHandler,\n };\n}\n","export type AsyncFunction<T extends any[]> = (...args: [...T, AbortSignal]) => Promise<void>;\n\nexport class Debouncer<T extends any[]> {\n private timeoutId?: ReturnType<typeof setTimeout>;\n private activeAbortController?: AbortController;\n\n constructor(private wait: number) {}\n\n debounce = async (func: AsyncFunction<T>, ...args: T) => {\n // Abort the previous promise immediately\n this.cancel();\n\n this.timeoutId = setTimeout(async () => {\n try {\n this.activeAbortController = new AbortController();\n\n // Pass the signal to the async function, assuming it supports it\n await func(...args, this.activeAbortController.signal);\n\n this.activeAbortController = undefined;\n } catch (error) {}\n }, this.wait);\n };\n\n cancel = () => {\n if (this.activeAbortController) {\n this.activeAbortController.abort();\n this.activeAbortController = undefined;\n }\n\n if (this.timeoutId !== undefined) {\n clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n }\n };\n}\n","import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\nexport async function fetcher<JSON = any>(input: RequestInfo, init?: RequestInit): Promise<JSON> {\n const res = await fetch(input, init);\n\n if (!res.ok) {\n const json = await res.json();\n if (json.error) {\n const error = new Error(json.error) as Error & {\n status: number;\n };\n error.status = res.status;\n throw error;\n } else {\n throw new Error(\"An unexpected error occurred\");\n }\n }\n\n return res.json();\n}\n\nexport function formatDate(input: string | number | Date): string {\n const date = new Date(input);\n return date.toLocaleDateString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n });\n}\n\nexport const arraysAreEqual = (arr1: number[], arr2: number[]): boolean =>\n arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);\n\nexport function nullableCompatibleEqualityCheck<T>(\n naiveEqualityCheck: (a: T, b: T) => boolean,\n a: T | null | undefined,\n b: T | null | undefined,\n): boolean {\n if (a === null || a === undefined || b === null || b === undefined) {\n return a === b;\n }\n\n return naiveEqualityCheck(a, b);\n}\n","import { BasePoint } from \"slate\";\nimport { arraysAreEqual } from \"../../lib/utils\";\n\nexport interface EditorAutocompleteState {\n cursorPoint: BasePoint;\n textBeforeCursor: string;\n textAfterCursor: string;\n}\n\nexport function areEqual_autocompleteState(\n prev: EditorAutocompleteState,\n next: EditorAutocompleteState,\n) {\n return (\n prev.cursorPoint.offset === next.cursorPoint.offset &&\n arraysAreEqual(prev.cursorPoint.path, next.cursorPoint.path) &&\n prev.textBeforeCursor === next.textBeforeCursor &&\n prev.textAfterCursor === next.textAfterCursor\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA0D;;;ACEnD,IAAM,YAAN,MAAiC;AAAA,EAItC,YAAoB,MAAc;AAAd;AAEpB,oBAAW,CAAO,SAA2B,SAAY;AAEvD,WAAK,OAAO;AAEZ,WAAK,YAAY,WAAW,MAAY;AACtC,YAAI;AACF,eAAK,wBAAwB,IAAI,gBAAgB;AAGjD,gBAAM,KAAK,GAAG,MAAM,KAAK,sBAAsB,MAAM;AAErD,eAAK,wBAAwB;AAAA,QAC/B,SAAS,OAAP;AAAA,QAAe;AAAA,MAC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]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useAutosuggestions
3
- } from "../../chunk-PNNCL732.mjs";
3
+ } from "../../chunk-23Q6A46J.mjs";
4
4
  import "../../chunk-AJ5OMEXM.mjs";
5
5
  import "../../chunk-YLFAIYRY.mjs";
6
6
  import "../../chunk-DFTV4TST.mjs";
@@ -111,7 +111,8 @@ function useMakeStandardAutosuggestionFunction(textareaPurpose, contextCategorie
111
111
  const runtimeClient = new import_runtime_client_gql.CopilotRuntimeClient({
112
112
  url: copilotApiConfig.chatApiEndpoint,
113
113
  publicApiKey: copilotApiConfig.publicApiKey,
114
- headers: copilotApiConfig.headers
114
+ headers: copilotApiConfig.headers,
115
+ credentials: copilotApiConfig.credentials
115
116
  });
116
117
  const response = yield runtimeClient.generateCopilotResponse({
117
118
  data: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.tsx","../../../src/lib/retry.tsx"],"sourcesContent":["import { COPILOT_CLOUD_PUBLIC_API_KEY_HEADER } from \"@copilotkit/shared\";\nimport { CopilotContext } from \"@copilotkit/react-core\";\nimport { useCallback, useContext } from \"react\";\nimport { AutosuggestionsBareFunction } from \"../../types\";\nimport { retry } from \"../../lib/retry\";\nimport { InsertionEditorState } from \"../../types/base/autosuggestions-bare-function\";\nimport { SuggestionsApiConfig } from \"../../types/autosuggestions-config/suggestions-api-config\";\nimport {\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n CopilotRequestType,\n} from \"@copilotkit/runtime-client-gql\";\n\n/**\n * Returns a memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n * The function takes in the text before and after the cursor, and an abort signal.\n * It sends a POST request to the API endpoint with the messages array containing the system message, few shot messages, and user messages.\n * The function returns the suggestion from the API response.\n *\n * @param textareaPurpose - The purpose of the textarea. This is included in the system message.\n * @param apiEndpoint - The API endpoint to send the autosuggestion request to.\n * @param makeSystemMessage - A function that takes in a context string and returns a system message to include in the autosuggestion request.\n * @param fewShotMessages - An array of few shot messages to include in the autosuggestion request.\n * @param contextCategories - The categories of context strings we want to include. By default, we include the (default) \"global\" context category.\n * @returns A memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n */\nexport function useMakeStandardAutosuggestionFunction(\n textareaPurpose: string,\n contextCategories: string[],\n apiConfig: SuggestionsApiConfig,\n): AutosuggestionsBareFunction {\n const { getContextString, copilotApiConfig } = useContext(CopilotContext);\n const publicApiKey = copilotApiConfig.publicApiKey;\n const headers = {\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n return useCallback(\n async (editorState: InsertionEditorState, abortSignal: AbortSignal) => {\n const res = await retry(async () => {\n const messages: Message[] = [\n new TextMessage({\n role: Role.System,\n content: apiConfig.makeSystemPrompt(\n textareaPurpose,\n getContextString([], contextCategories),\n ),\n }),\n ...apiConfig.fewShotMessages,\n new TextMessage({\n role: Role.User,\n content: editorState.textAfterCursor,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`,\n }),\n ];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers: copilotApiConfig.headers,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: [],\n },\n messages: convertMessagesToGqlInput(messages),\n metadata: {\n requestType: CopilotRequestType.TextareaCompletion,\n },\n },\n properties: copilotApiConfig.properties,\n signal: abortSignal,\n })\n .toPromise();\n\n let result = \"\";\n for (const message of convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages ?? [],\n )) {\n if (abortSignal.aborted) {\n break;\n }\n if (message instanceof TextMessage) {\n result += message.content;\n console.log(message.content);\n }\n }\n\n return result;\n });\n\n return res;\n },\n [apiConfig, getContextString, contextCategories, textareaPurpose],\n );\n}\n","export function retry<T>(\n fn: () => Promise<T>,\n retriesLeft: number = 2,\n interval: number = 200,\n backoff: number = 1.5,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n fn()\n .then(resolve)\n .catch((error) => {\n if (retriesLeft === 1) {\n reject(error);\n return;\n }\n\n setTimeout(() => {\n retry(fn, retriesLeft - 1, interval * backoff, backoff)\n .then(resolve)\n .catch(reject);\n }, interval);\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAoD;AACpD,wBAA+B;AAC/B,mBAAwC;;;ACFjC,SAAS,MACd,IACA,cAAsB,GACtB,WAAmB,KACnB,UAAkB,KACN;AACZ,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,OAAG,EACA,KAAK,OAAO,EACZ,MAAM,CAAC,UAAU;AAChB,UAAI,gBAAgB,GAAG;AACrB,eAAO,KAAK;AACZ;AAAA,MACF;AAEA,iBAAW,MAAM;AACf,cAAM,IAAI,cAAc,GAAG,WAAW,SAAS,OAAO,EACnD,KAAK,OAAO,EACZ,MAAM,MAAM;AAAA,MACjB,GAAG,QAAQ;AAAA,IACb,CAAC;AAAA,EACL,CAAC;AACH;;;ADfA,gCAQO;AAeA,SAAS,sCACd,iBACA,mBACA,WAC6B;AAC7B,QAAM,EAAE,kBAAkB,iBAAiB,QAAI,yBAAW,gCAAc;AACxE,QAAM,eAAe,iBAAiB;AACtC,QAAM,UAAU,mBACV,eAAe,EAAE,CAAC,iDAAmC,GAAG,aAAa,IAAI,CAAC;AAGhF,aAAO;AAAA,IACL,CAAO,aAAmC,gBAA6B;AACrE,YAAM,MAAM,MAAM,MAAM,MAAY;AA3C1C;AA4CQ,cAAM,WAAsB;AAAA,UAC1B,IAA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eAAe;AAAA,EAClE;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.tsx","../../../src/lib/retry.tsx"],"sourcesContent":["import { COPILOT_CLOUD_PUBLIC_API_KEY_HEADER } from \"@copilotkit/shared\";\nimport { CopilotContext } from \"@copilotkit/react-core\";\nimport { useCallback, useContext } from \"react\";\nimport { AutosuggestionsBareFunction } from \"../../types\";\nimport { retry } from \"../../lib/retry\";\nimport { InsertionEditorState } from \"../../types/base/autosuggestions-bare-function\";\nimport { SuggestionsApiConfig } from \"../../types/autosuggestions-config/suggestions-api-config\";\nimport {\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n CopilotRequestType,\n} from \"@copilotkit/runtime-client-gql\";\n\n/**\n * Returns a memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n * The function takes in the text before and after the cursor, and an abort signal.\n * It sends a POST request to the API endpoint with the messages array containing the system message, few shot messages, and user messages.\n * The function returns the suggestion from the API response.\n *\n * @param textareaPurpose - The purpose of the textarea. This is included in the system message.\n * @param apiEndpoint - The API endpoint to send the autosuggestion request to.\n * @param makeSystemMessage - A function that takes in a context string and returns a system message to include in the autosuggestion request.\n * @param fewShotMessages - An array of few shot messages to include in the autosuggestion request.\n * @param contextCategories - The categories of context strings we want to include. By default, we include the (default) \"global\" context category.\n * @returns A memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n */\nexport function useMakeStandardAutosuggestionFunction(\n textareaPurpose: string,\n contextCategories: string[],\n apiConfig: SuggestionsApiConfig,\n): AutosuggestionsBareFunction {\n const { getContextString, copilotApiConfig } = useContext(CopilotContext);\n const publicApiKey = copilotApiConfig.publicApiKey;\n const headers = {\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n return useCallback(\n async (editorState: InsertionEditorState, abortSignal: AbortSignal) => {\n const res = await retry(async () => {\n const messages: Message[] = [\n new TextMessage({\n role: Role.System,\n content: apiConfig.makeSystemPrompt(\n textareaPurpose,\n getContextString([], contextCategories),\n ),\n }),\n ...apiConfig.fewShotMessages,\n new TextMessage({\n role: Role.User,\n content: editorState.textAfterCursor,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`,\n }),\n ];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers: copilotApiConfig.headers,\n credentials: copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: [],\n },\n messages: convertMessagesToGqlInput(messages),\n metadata: {\n requestType: CopilotRequestType.TextareaCompletion,\n },\n },\n properties: copilotApiConfig.properties,\n signal: abortSignal,\n })\n .toPromise();\n\n let result = \"\";\n for (const message of convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages ?? [],\n )) {\n if (abortSignal.aborted) {\n break;\n }\n if (message instanceof TextMessage) {\n result += message.content;\n console.log(message.content);\n }\n }\n\n return result;\n });\n\n return res;\n },\n [apiConfig, getContextString, contextCategories, textareaPurpose],\n );\n}\n","export function retry<T>(\n fn: () => Promise<T>,\n retriesLeft: number = 2,\n interval: number = 200,\n backoff: number = 1.5,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n fn()\n .then(resolve)\n .catch((error) => {\n if (retriesLeft === 1) {\n reject(error);\n return;\n }\n\n setTimeout(() => {\n retry(fn, retriesLeft - 1, interval * backoff, backoff)\n .then(resolve)\n .catch(reject);\n }, interval);\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA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cAAM,gBAAgB,IAAI,+CAAqB;AAAA,UAC7C,KAAK,iBAAiB;AAAA,UACtB,cAAc,iBAAiB;AAAA,UAC/B,SAAS,iBAAiB;AAAA,UAC1B,aAAa,iBAAiB;AAAA,QAChC,CAAC;AAED,cAAM,WAAW,MAAM,cACpB,wBAAwB;AAAA,UACvB,MAAM;AAAA,YACJ,UAAU;AAAA,cACR,SAAS,CAAC;AAAA,YACZ;AAAA,YACA,cAAU,qDAA0B,QAAQ;AAAA,YAC5C,UAAU;AAAA,cACR,aAAa,6CAAmB;AAAA,YAClC;AAAA,UACF;AAAA,UACA,YAAY,iBAAiB;AAAA,UAC7B,QAAQ;AAAA,QACV,CAAC,EACA,UAAU;AAEb,YAAI,SAAS;AACb,mBAAW,eAAW;AAAA,WACpB,0BAAS,SAAT,mBAAe,4BAAf,mBAAwC,aAAxC,YAAoD,CAAC;AAAA,QACvD,GAAG;AACD,cAAI,YAAY,SAAS;AACvB;AAAA,UACF;AACA,cAAI,mBAAmB,uCAAa;AAClC,sBAAU,QAAQ;AAClB,oBAAQ,IAAI,QAAQ,OAAO;AAAA,UAC7B;AAAA,QACF;AAEA,eAAO;AAAA,MACT,EAAC;AAED,aAAO;AAAA,IACT;AAAA,IACA,CAAC,WAAW,kBAAkB,mBAAmB,eAAe;AAAA,EAClE;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useMakeStandardAutosuggestionFunction
3
- } from "../../chunk-TTOZXUEA.mjs";
3
+ } from "../../chunk-BHSXGMP7.mjs";
4
4
  import "../../chunk-KNQIEOFP.mjs";
5
5
  import "../../chunk-MRXNTQOX.mjs";
6
6
  export {
@@ -84,7 +84,8 @@ function useMakeStandardInsertionOrEditingFunction(textareaPurpose, contextCateg
84
84
  const runtimeClient = new import_runtime_client_gql.CopilotRuntimeClient({
85
85
  url: copilotApiConfig.chatApiEndpoint,
86
86
  publicApiKey: copilotApiConfig.publicApiKey,
87
- headers
87
+ headers,
88
+ credentials: copilotApiConfig.credentials
88
89
  });
89
90
  function runtimeClientResponseToStringStream(responsePromise) {
90
91
  return __async(this, null, function* () {
@@ -195,7 +196,8 @@ function useMakeStandardInsertionOrEditingFunction(textareaPurpose, contextCateg
195
196
  const runtimeClient2 = new import_runtime_client_gql.CopilotRuntimeClient({
196
197
  url: copilotApiConfig.chatApiEndpoint,
197
198
  publicApiKey: copilotApiConfig.publicApiKey,
198
- headers
199
+ headers,
200
+ credentials: copilotApiConfig.credentials
199
201
  });
200
202
  return runtimeClientResponseToStringStream(
201
203
  runtimeClient2.generateCopilotResponse({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/hooks/make-autosuggestions-function/use-make-standard-insertion-function.tsx","../../../src/lib/retry.tsx"],"sourcesContent":["import { COPILOT_CLOUD_PUBLIC_API_KEY_HEADER } from \"@copilotkit/shared\";\nimport { CopilotContext } from \"@copilotkit/react-core\";\nimport { useCallback, useContext } from \"react\";\nimport {\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n CopilotRequestType,\n} from \"@copilotkit/runtime-client-gql\";\nimport { retry } from \"../../lib/retry\";\nimport {\n EditingEditorState,\n Generator_InsertionOrEditingSuggestion,\n} from \"../../types/base/autosuggestions-bare-function\";\nimport { InsertionsApiConfig } from \"../../types/autosuggestions-config/insertions-api-config\";\nimport { EditingApiConfig } from \"../../types/autosuggestions-config/editing-api-config\";\nimport { DocumentPointer } from \"@copilotkit/react-core\";\nimport { randomId } from \"@copilotkit/shared\";\n\n/**\n * Returns a memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n * The function takes in the text before and after the cursor, and an abort signal.\n * It sends a POST request to the API endpoint with the messages array containing the system message, few shot messages, and user messages.\n * The function returns the suggestion from the API response.\n *\n * @param textareaPurpose - The purpose of the textarea. This is included in the system message.\n * @param apiEndpoint - The API endpoint to send the autosuggestion request to.\n * @param makeSystemMessage - A function that takes in a context string and returns a system message to include in the autosuggestion request.\n * @param fewShotMessages - An array of few shot messages to include in the autosuggestion request.\n * @param contextCategories - The categories of context strings we want to include. By default, we include the (default) \"global\" context category.\n * @returns A memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n */\nexport function useMakeStandardInsertionOrEditingFunction(\n textareaPurpose: string,\n contextCategories: string[],\n insertionApiConfig: InsertionsApiConfig,\n editingApiConfig: EditingApiConfig,\n): Generator_InsertionOrEditingSuggestion {\n const { getContextString, copilotApiConfig } = useContext(CopilotContext);\n const headers = {\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n });\n\n async function runtimeClientResponseToStringStream(\n responsePromise: ReturnType<typeof runtimeClient.generateCopilotResponse>,\n ) {\n const messagesStream = await CopilotRuntimeClient.asStream(responsePromise);\n\n return new ReadableStream({\n async start(controller) {\n const reader = messagesStream.getReader();\n let sentContent = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n const messages = convertGqlOutputToMessages(value.generateCopilotResponse.messages);\n\n let newContent = \"\";\n\n for (const message of messages) {\n if (message instanceof TextMessage) {\n newContent += message.content;\n }\n }\n if (newContent) {\n const contentToSend = newContent.slice(sentContent.length);\n controller.enqueue(contentToSend);\n sentContent += contentToSend;\n }\n }\n controller.close();\n },\n });\n }\n\n const insertionFunction = useCallback(\n async (\n editorState: EditingEditorState,\n insertionPrompt: string,\n documents: DocumentPointer[],\n abortSignal: AbortSignal,\n ) => {\n const res = await retry(async () => {\n const messages: Message[] = [\n new TextMessage({\n role: Role.System,\n content: insertionApiConfig.makeSystemPrompt(\n textareaPurpose,\n getContextString(documents, contextCategories),\n ),\n }),\n ...insertionApiConfig.fewShotMessages,\n new TextMessage({\n role: Role.User,\n content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<InsertionPrompt>${insertionPrompt}</InsertionPrompt>`,\n }),\n ];\n\n return runtimeClientResponseToStringStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [],\n },\n messages: convertMessagesToGqlInput(messages),\n metadata: {\n requestType: CopilotRequestType.TextareaCompletion,\n },\n },\n properties: copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n });\n\n return res;\n },\n [insertionApiConfig, getContextString, contextCategories, textareaPurpose],\n );\n\n const editingFunction = useCallback(\n async (\n editorState: EditingEditorState,\n editingPrompt: string,\n documents: DocumentPointer[],\n abortSignal: AbortSignal,\n ) => {\n const res = await retry(async () => {\n const messages: Message[] = [\n new TextMessage({\n role: Role.System,\n content: editingApiConfig.makeSystemPrompt(\n textareaPurpose,\n getContextString(documents, contextCategories),\n ),\n }),\n ...editingApiConfig.fewShotMessages,\n new TextMessage({\n role: Role.User,\n content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextToEdit>${editorState.selectedText}</TextToEdit>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<EditingPrompt>${editingPrompt}</EditingPrompt>`,\n }),\n ];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n });\n\n return runtimeClientResponseToStringStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [],\n },\n messages: convertMessagesToGqlInput(messages),\n metadata: {\n requestType: CopilotRequestType.TextareaCompletion,\n },\n },\n properties: copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n });\n\n return res;\n },\n [editingApiConfig, getContextString, contextCategories, textareaPurpose],\n );\n\n const insertionOrEditingFunction = useCallback(\n async (\n editorState: EditingEditorState,\n insertionPrompt: string,\n documents: DocumentPointer[],\n abortSignal: AbortSignal,\n ) => {\n if (editorState.selectedText === \"\") {\n return await insertionFunction(editorState, insertionPrompt, documents, abortSignal);\n } else {\n return await editingFunction(editorState, insertionPrompt, documents, abortSignal);\n }\n },\n [insertionFunction, editingFunction],\n );\n\n return insertionOrEditingFunction;\n}\n","export function retry<T>(\n fn: () => Promise<T>,\n retriesLeft: number = 2,\n interval: number = 200,\n backoff: number = 1.5,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n fn()\n .then(resolve)\n .catch((error) => {\n if (retriesLeft === 1) {\n reject(error);\n return;\n }\n\n setTimeout(() => {\n retry(fn, retriesLeft - 1, interval * backoff, backoff)\n .then(resolve)\n .catch(reject);\n }, interval);\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAoD;AACpD,wBAA+B;AAC/B,mBAAwC;AACxC,gCAQO;;;ACXA,SAAS,MACd,IACA,cAAsB,GACtB,WAAmB,KACnB,UAAkB,KACN;AACZ,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,OAAG,EACA,KAAK,OAAO,EACZ,MAAM,CAAC,UAAU;AAChB,UAAI,gBAAgB,GAAG;AACrB,eAAO,KAAK;AACZ;AAAA,MACF;AAEA,iBAAW,MAAM;AACf,cAAM,IAAI,cAAc,GAAG,WAAW,SAAS,OAAO,EACnD,KAAK,OAAO,EACZ,MAAM,MAAM;AAAA,MACjB,GAAG,QAAQ;AAAA,IACb,CAAC;AAAA,EACL,CAAC;AACH;;;ADaO,SAAS,0CACd,iBACA,mBACA,oBACA,kBACwC;AACxC,QAAM,EAAE,kBAAkB,iBAAiB,QAAI,yBAAW,gCAAc;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,+BAAK;AAAA,YACX,SAAS,kBAAkB;AAAA,UAC7B,CAAC;AAAA,QACH;AAEA,cAAMA,iBAAgB,IAAI,+CAAqB;AAAA,UAC7C,KAAK,iBAAiB;AAAA,UACtB,cAAc,iBAAiB;AAAA,UAC/B;AAAA,QACF,CAAC;AAED,eAAO;AAAA,UACLA,eAAc,wBAAwB;AAAA,YACpC,MAAM;AAAA,cACJ,UAAU;AAAA,gBACR,SAAS,CAAC;AAAA,cACZ;AAAA,cACA,cAAU,qDAA0B,QAAQ;AAAA,cAC5C,UAAU;AAAA,gBACR,aAAa,6CAAmB;AAAA,cAClC;AAAA,YACF;AAAA,YACA,YAAY,iBAAiB;AAAA,YAC7B,QAAQ;AAAA,UACV,CAAC;AAAA,QACH;AAAA,MACF,EAAC;AAED,aAAO;AAAA,IACT;AAAA,IACA,CAAC,kBAAkB,kBAAkB,mBAAmB,eAAe;AAAA,EACzE;AAEA,QAAM,iCAA6B;AAAA,IACjC,CACE,aACA,iBACA,WACA,gBACG;AACH,UAAI,YAAY,iBAAiB,IAAI;AACnC,eAAO,MAAM,kBAAkB,aAAa,iBAAiB,WAAW,WAAW;AAAA,MACrF,OAAO;AACL,eAAO,MAAM,gBAAgB,aAAa,iBAAiB,WAAW,WAAW;AAAA,MACnF;AAAA,IACF;AAAA,IACA,CAAC,mBAAmB,eAAe;AAAA,EACrC;AAEA,SAAO;AACT;","names":["runtimeClient"]}
1
+ {"version":3,"sources":["../../../src/hooks/make-autosuggestions-function/use-make-standard-insertion-function.tsx","../../../src/lib/retry.tsx"],"sourcesContent":["import { COPILOT_CLOUD_PUBLIC_API_KEY_HEADER } from \"@copilotkit/shared\";\nimport { CopilotContext } from \"@copilotkit/react-core\";\nimport { useCallback, useContext } from \"react\";\nimport {\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n CopilotRequestType,\n} from \"@copilotkit/runtime-client-gql\";\nimport { retry } from \"../../lib/retry\";\nimport {\n EditingEditorState,\n Generator_InsertionOrEditingSuggestion,\n} from \"../../types/base/autosuggestions-bare-function\";\nimport { InsertionsApiConfig } from \"../../types/autosuggestions-config/insertions-api-config\";\nimport { EditingApiConfig } from \"../../types/autosuggestions-config/editing-api-config\";\nimport { DocumentPointer } from \"@copilotkit/react-core\";\nimport { randomId } from \"@copilotkit/shared\";\n\n/**\n * Returns a memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n * The function takes in the text before and after the cursor, and an abort signal.\n * It sends a POST request to the API endpoint with the messages array containing the system message, few shot messages, and user messages.\n * The function returns the suggestion from the API response.\n *\n * @param textareaPurpose - The purpose of the textarea. This is included in the system message.\n * @param apiEndpoint - The API endpoint to send the autosuggestion request to.\n * @param makeSystemMessage - A function that takes in a context string and returns a system message to include in the autosuggestion request.\n * @param fewShotMessages - An array of few shot messages to include in the autosuggestion request.\n * @param contextCategories - The categories of context strings we want to include. By default, we include the (default) \"global\" context category.\n * @returns A memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n */\nexport function useMakeStandardInsertionOrEditingFunction(\n textareaPurpose: string,\n contextCategories: string[],\n insertionApiConfig: InsertionsApiConfig,\n editingApiConfig: EditingApiConfig,\n): Generator_InsertionOrEditingSuggestion {\n const { getContextString, copilotApiConfig } = useContext(CopilotContext);\n const headers = {\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n });\n\n async function runtimeClientResponseToStringStream(\n responsePromise: ReturnType<typeof runtimeClient.generateCopilotResponse>,\n ) {\n const messagesStream = await CopilotRuntimeClient.asStream(responsePromise);\n\n return new ReadableStream({\n async start(controller) {\n const reader = messagesStream.getReader();\n let sentContent = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n const messages = convertGqlOutputToMessages(value.generateCopilotResponse.messages);\n\n let newContent = \"\";\n\n for (const message of messages) {\n if (message instanceof TextMessage) {\n newContent += message.content;\n }\n }\n if (newContent) {\n const contentToSend = newContent.slice(sentContent.length);\n controller.enqueue(contentToSend);\n sentContent += contentToSend;\n }\n }\n controller.close();\n },\n });\n }\n\n const insertionFunction = useCallback(\n async (\n editorState: EditingEditorState,\n insertionPrompt: string,\n documents: DocumentPointer[],\n abortSignal: AbortSignal,\n ) => {\n const res = await retry(async () => {\n const messages: Message[] = [\n new TextMessage({\n role: Role.System,\n content: insertionApiConfig.makeSystemPrompt(\n textareaPurpose,\n getContextString(documents, contextCategories),\n ),\n }),\n ...insertionApiConfig.fewShotMessages,\n new TextMessage({\n role: Role.User,\n content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<InsertionPrompt>${insertionPrompt}</InsertionPrompt>`,\n }),\n ];\n\n return runtimeClientResponseToStringStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [],\n },\n messages: convertMessagesToGqlInput(messages),\n metadata: {\n requestType: CopilotRequestType.TextareaCompletion,\n },\n },\n properties: copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n });\n\n return res;\n },\n [insertionApiConfig, getContextString, contextCategories, textareaPurpose],\n );\n\n const editingFunction = useCallback(\n async (\n editorState: EditingEditorState,\n editingPrompt: string,\n documents: DocumentPointer[],\n abortSignal: AbortSignal,\n ) => {\n const res = await retry(async () => {\n const messages: Message[] = [\n new TextMessage({\n role: Role.System,\n content: editingApiConfig.makeSystemPrompt(\n textareaPurpose,\n getContextString(documents, contextCategories),\n ),\n }),\n ...editingApiConfig.fewShotMessages,\n new TextMessage({\n role: Role.User,\n content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextToEdit>${editorState.selectedText}</TextToEdit>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<EditingPrompt>${editingPrompt}</EditingPrompt>`,\n }),\n ];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n });\n\n return runtimeClientResponseToStringStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [],\n },\n messages: convertMessagesToGqlInput(messages),\n metadata: {\n requestType: CopilotRequestType.TextareaCompletion,\n },\n },\n properties: copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n });\n\n return res;\n },\n [editingApiConfig, getContextString, contextCategories, textareaPurpose],\n );\n\n const insertionOrEditingFunction = useCallback(\n async (\n editorState: EditingEditorState,\n insertionPrompt: string,\n documents: DocumentPointer[],\n abortSignal: AbortSignal,\n ) => {\n if (editorState.selectedText === \"\") {\n return await insertionFunction(editorState, insertionPrompt, documents, abortSignal);\n } else {\n return await editingFunction(editorState, insertionPrompt, documents, abortSignal);\n }\n },\n [insertionFunction, editingFunction],\n );\n\n return insertionOrEditingFunction;\n}\n","export function retry<T>(\n fn: () => Promise<T>,\n retriesLeft: number = 2,\n interval: number = 200,\n backoff: number = 1.5,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n fn()\n .then(resolve)\n .catch((error) => {\n if (retriesLeft === 1) {\n reject(error);\n return;\n }\n\n setTimeout(() => {\n retry(fn, retriesLeft - 1, interval * backoff, backoff)\n .then(resolve)\n .catch(reject);\n }, interval);\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA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BACG;AACH,UAAI,YAAY,iBAAiB,IAAI;AACnC,eAAO,MAAM,kBAAkB,aAAa,iBAAiB,WAAW,WAAW;AAAA,MACrF,OAAO;AACL,eAAO,MAAM,gBAAgB,aAAa,iBAAiB,WAAW,WAAW;AAAA,MACnF;AAAA,IACF;AAAA,IACA,CAAC,mBAAmB,eAAe;AAAA,EACrC;AAEA,SAAO;AACT;","names":["runtimeClient"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useMakeStandardInsertionOrEditingFunction
3
- } from "../../chunk-WDV7S66U.mjs";
3
+ } from "../../chunk-MUAPKB7X.mjs";
4
4
  import "../../chunk-KNQIEOFP.mjs";
5
5
  import "../../chunk-MRXNTQOX.mjs";
6
6
  export {
package/dist/index.js CHANGED
@@ -205,7 +205,7 @@ function useAutosuggestions(debounceTime, shouldAcceptAutosuggestionOnKeyPress,
205
205
  const keyDownOrTouchHandler = (0, import_react.useCallback)(
206
206
  (event) => {
207
207
  if (currentAutocompleteSuggestion) {
208
- const shouldAcceptSuggestion = event instanceof KeyboardEvent ? shouldAcceptAutosuggestionOnKeyPress(event) : shouldAcceptAutosuggestionOnTouch(event);
208
+ const shouldAcceptSuggestion = event.type === "touchstart" ? shouldAcceptAutosuggestionOnTouch(event) : shouldAcceptAutosuggestionOnKeyPress(event);
209
209
  if (shouldAcceptSuggestion) {
210
210
  event.preventDefault();
211
211
  insertAutocompleteSuggestion(currentAutocompleteSuggestion);
@@ -651,7 +651,7 @@ var defaultShouldAcceptAutosuggestionOnKeyPress = (event) => {
651
651
  }
652
652
  return false;
653
653
  };
654
- var defaultShouldAcceptAutosuggestionOnTouch = () => true;
654
+ var defaultShouldAcceptAutosuggestionOnTouch = () => false;
655
655
  var defaultBaseAutosuggestionsConfig = {
656
656
  debounceTime: 250,
657
657
  contextCategories: import_react_core.defaultCopilotContextCategories,
@@ -1849,7 +1849,8 @@ function useMakeStandardAutosuggestionFunction(textareaPurpose, contextCategorie
1849
1849
  const runtimeClient = new import_runtime_client_gql.CopilotRuntimeClient({
1850
1850
  url: copilotApiConfig.chatApiEndpoint,
1851
1851
  publicApiKey: copilotApiConfig.publicApiKey,
1852
- headers: copilotApiConfig.headers
1852
+ headers: copilotApiConfig.headers,
1853
+ credentials: copilotApiConfig.credentials
1853
1854
  });
1854
1855
  const response = yield runtimeClient.generateCopilotResponse({
1855
1856
  data: {
@@ -2109,7 +2110,8 @@ function useMakeStandardInsertionOrEditingFunction(textareaPurpose, contextCateg
2109
2110
  const runtimeClient = new import_runtime_client_gql5.CopilotRuntimeClient({
2110
2111
  url: copilotApiConfig.chatApiEndpoint,
2111
2112
  publicApiKey: copilotApiConfig.publicApiKey,
2112
- headers
2113
+ headers,
2114
+ credentials: copilotApiConfig.credentials
2113
2115
  });
2114
2116
  function runtimeClientResponseToStringStream(responsePromise) {
2115
2117
  return __async(this, null, function* () {
@@ -2220,7 +2222,8 @@ function useMakeStandardInsertionOrEditingFunction(textareaPurpose, contextCateg
2220
2222
  const runtimeClient2 = new import_runtime_client_gql5.CopilotRuntimeClient({
2221
2223
  url: copilotApiConfig.chatApiEndpoint,
2222
2224
  publicApiKey: copilotApiConfig.publicApiKey,
2223
- headers
2225
+ headers,
2226
+ credentials: copilotApiConfig.credentials
2224
2227
  });
2225
2228
  return runtimeClientResponseToStringStream(
2226
2229
  runtimeClient2.generateCopilotResponse({