@copilotkit/react-core 0.15.0-alpha.3 → 0.15.0-alpha.5

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 (97) hide show
  1. package/.turbo/turbo-build.log +76 -76
  2. package/CHANGELOG.md +22 -0
  3. package/dist/chunk-3MAIWZNZ.mjs +58 -0
  4. package/dist/chunk-3MAIWZNZ.mjs.map +1 -0
  5. package/dist/chunk-45PUEKTG.mjs +19 -0
  6. package/dist/chunk-45PUEKTG.mjs.map +1 -0
  7. package/dist/chunk-6LKBKYRJ.mjs +165 -0
  8. package/dist/chunk-6LKBKYRJ.mjs.map +1 -0
  9. package/dist/chunk-6LNDDH6K.mjs +19 -0
  10. package/dist/chunk-6LNDDH6K.mjs.map +1 -0
  11. package/dist/chunk-6N6X7K7T.mjs +13 -0
  12. package/dist/chunk-6N6X7K7T.mjs.map +1 -0
  13. package/dist/chunk-7GFKOIO7.mjs +3 -0
  14. package/dist/chunk-7GFKOIO7.mjs.map +1 -0
  15. package/dist/chunk-BABVSMJR.mjs +3 -0
  16. package/dist/chunk-BABVSMJR.mjs.map +1 -0
  17. package/dist/chunk-E3P5YZO2.mjs +27 -0
  18. package/dist/chunk-E3P5YZO2.mjs.map +1 -0
  19. package/dist/chunk-EFZPSZWO.mjs +3 -0
  20. package/dist/chunk-EFZPSZWO.mjs.map +1 -0
  21. package/dist/chunk-FRAKUJWH.mjs +3 -0
  22. package/dist/chunk-FRAKUJWH.mjs.map +1 -0
  23. package/dist/chunk-JD7BAH7U.mjs +3 -0
  24. package/dist/chunk-JD7BAH7U.mjs.map +1 -0
  25. package/dist/chunk-JHJ7LUTD.mjs +125 -0
  26. package/dist/chunk-JHJ7LUTD.mjs.map +1 -0
  27. package/dist/chunk-MRXNTQOX.mjs +55 -0
  28. package/dist/chunk-MRXNTQOX.mjs.map +1 -0
  29. package/dist/chunk-MZ5UN3BY.mjs +28 -0
  30. package/dist/chunk-MZ5UN3BY.mjs.map +1 -0
  31. package/dist/chunk-OFRZZ5OF.mjs +79 -0
  32. package/dist/chunk-OFRZZ5OF.mjs.map +1 -0
  33. package/dist/chunk-QACD2U6P.mjs +3 -0
  34. package/dist/chunk-QACD2U6P.mjs.map +1 -0
  35. package/dist/chunk-SPCZTZCY.mjs +3 -0
  36. package/dist/chunk-SPCZTZCY.mjs.map +1 -0
  37. package/dist/chunk-VUY2K2DI.mjs +135 -0
  38. package/dist/chunk-VUY2K2DI.mjs.map +1 -0
  39. package/dist/chunk-YPSGKPDA.mjs +3 -0
  40. package/dist/chunk-YPSGKPDA.mjs.map +1 -0
  41. package/dist/chunk-YULKJPY3.mjs +70 -0
  42. package/dist/chunk-YULKJPY3.mjs.map +1 -0
  43. package/dist/components/copilot-provider/copilot-provider-props.mjs +2 -1
  44. package/dist/components/copilot-provider/copilot-provider-props.mjs.map +1 -1
  45. package/dist/components/copilot-provider/copilot-provider.mjs +7 -468
  46. package/dist/components/copilot-provider/copilot-provider.mjs.map +1 -1
  47. package/dist/components/copilot-provider/index.mjs +8 -467
  48. package/dist/components/copilot-provider/index.mjs.map +1 -1
  49. package/dist/components/copilot-provider/standard-cpilot-api-config.mjs +3 -12
  50. package/dist/components/copilot-provider/standard-cpilot-api-config.mjs.map +1 -1
  51. package/dist/components/index.mjs +9 -467
  52. package/dist/components/index.mjs.map +1 -1
  53. package/dist/context/copilot-context.mjs +3 -81
  54. package/dist/context/copilot-context.mjs.map +1 -1
  55. package/dist/context/index.mjs +4 -80
  56. package/dist/context/index.mjs.map +1 -1
  57. package/dist/hooks/index.mjs +14 -249
  58. package/dist/hooks/index.mjs.map +1 -1
  59. package/dist/hooks/use-copilot-chat.mjs +10 -194
  60. package/dist/hooks/use-copilot-chat.mjs.map +1 -1
  61. package/dist/hooks/use-flat-category-store.mjs +3 -68
  62. package/dist/hooks/use-flat-category-store.mjs.map +1 -1
  63. package/dist/hooks/use-make-copilot-actionable.mjs +4 -95
  64. package/dist/hooks/use-make-copilot-actionable.mjs.map +1 -1
  65. package/dist/hooks/use-make-copilot-document-readable.mjs +4 -87
  66. package/dist/hooks/use-make-copilot-document-readable.mjs.map +1 -1
  67. package/dist/hooks/use-make-copilot-readable.mjs +4 -87
  68. package/dist/hooks/use-make-copilot-readable.mjs.map +1 -1
  69. package/dist/hooks/use-tree.mjs +3 -153
  70. package/dist/hooks/use-tree.mjs.map +1 -1
  71. package/dist/index.mjs +21 -755
  72. package/dist/index.mjs.map +1 -1
  73. package/dist/openai-assistants/hooks/index.mjs +14 -245
  74. package/dist/openai-assistants/hooks/index.mjs.map +1 -1
  75. package/dist/openai-assistants/hooks/use-assistants.mjs +8 -52
  76. package/dist/openai-assistants/hooks/use-assistants.mjs.map +1 -1
  77. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +13 -246
  78. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +1 -1
  79. package/dist/openai-assistants/index.mjs +15 -246
  80. package/dist/openai-assistants/index.mjs.map +1 -1
  81. package/dist/openai-assistants/utils/index.mjs +4 -46
  82. package/dist/openai-assistants/utils/index.mjs.map +1 -1
  83. package/dist/openai-assistants/utils/process-message-stream.mjs +3 -46
  84. package/dist/openai-assistants/utils/process-message-stream.mjs.map +1 -1
  85. package/dist/types/annotated-function.mjs +2 -0
  86. package/dist/types/annotated-function.mjs.map +1 -1
  87. package/dist/types/document-pointer.mjs +2 -0
  88. package/dist/types/document-pointer.mjs.map +1 -1
  89. package/dist/types/index.mjs +2 -0
  90. package/dist/types/index.mjs.map +1 -1
  91. package/dist/utils/utils.mjs +2 -0
  92. package/dist/utils/utils.mjs.map +1 -1
  93. package/dist/utils/utils.test.mjs +1 -0
  94. package/dist/utils/utils.test.mjs.map +1 -1
  95. package/package.json +3 -3
  96. package/src/hooks/use-copilot-chat.ts +1 -4
  97. package/src/openai-assistants/hooks/use-copilot-chat-v2.ts +4 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-make-copilot-actionable.ts"],"names":[],"mappings":";;;;;AAEA,SAAS,QAAQ,YAAY,WAAW,eAAe;AAGvD,SAAS,cAAc;AAEhB,SAAS,yBACd,mBACA,cACA;AACA,QAAM,QAAQ,OAAO,OAAO,CAAC;AAC7B,QAAM,EAAE,eAAe,iBAAiB,IAAI,WAAW,cAAc;AAErE,QAAM,4BAA4D;AAAA,IAChE,OAAO;AAAA,MACL,MAAM,kBAAkB;AAAA,MACxB,aAAa,kBAAkB;AAAA,MAC/B,qBAAqB,kBAAkB;AAAA,MACvC,gBAAgB,kBAAkB;AAAA,IACpC;AAAA,IACA;AAAA,EACF;AAEA,YAAU,MAAM;AACd,kBAAc,MAAM,SAAS,yBAAqD;AAElF,WAAO,MAAM;AACX,uBAAiB,MAAM,OAAO;AAAA,IAChC;AAAA,EACF,GAAG,CAAC,2BAA2B,eAAe,gBAAgB,CAAC;AACjE","sourcesContent":["\"use client\";\n\nimport { useRef, useContext, useEffect, useMemo } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { AnnotatedFunction } from \"../types/annotated-function\";\nimport { nanoid } from \"nanoid\";\n\nexport function useMakeCopilotActionable<ActionInput extends any[]>(\n annotatedFunction: AnnotatedFunction<ActionInput>,\n dependencies: any[],\n) {\n const idRef = useRef(nanoid()); // generate a unique id\n const { setEntryPoint, removeEntryPoint } = useContext(CopilotContext);\n\n const memoizedAnnotatedFunction: AnnotatedFunction<ActionInput> = useMemo(\n () => ({\n name: annotatedFunction.name,\n description: annotatedFunction.description,\n argumentAnnotations: annotatedFunction.argumentAnnotations,\n implementation: annotatedFunction.implementation,\n }),\n dependencies,\n );\n\n useEffect(() => {\n setEntryPoint(idRef.current, memoizedAnnotatedFunction as AnnotatedFunction<any[]>);\n\n return () => {\n removeEntryPoint(idRef.current);\n };\n }, [memoizedAnnotatedFunction, setEntryPoint, removeEntryPoint]);\n}\n"]}
@@ -0,0 +1,3 @@
1
+
2
+ //# sourceMappingURL=out.js.map
3
+ //# sourceMappingURL=chunk-EFZPSZWO.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -0,0 +1,3 @@
1
+
2
+ //# sourceMappingURL=out.js.map
3
+ //# sourceMappingURL=chunk-FRAKUJWH.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -0,0 +1,3 @@
1
+
2
+ //# sourceMappingURL=out.js.map
3
+ //# sourceMappingURL=chunk-JD7BAH7U.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -0,0 +1,125 @@
1
+ import { processMessageStream } from './chunk-MZ5UN3BY.mjs';
2
+ import { defaultCopilotContextCategories } from './chunk-6LKBKYRJ.mjs';
3
+ import { CopilotContext, copilotApiConfigExtrapolator } from './chunk-3MAIWZNZ.mjs';
4
+ import { __async, __spreadValues } from './chunk-MRXNTQOX.mjs';
5
+ import { useContext, useState, useMemo } from 'react';
6
+ import { parseStreamPart } from '@copilotkit/shared';
7
+
8
+ function useCopilotChatV2(options) {
9
+ const {
10
+ getContextString,
11
+ getChatCompletionFunctionDescriptions,
12
+ getFunctionCallHandler,
13
+ copilotApiConfig
14
+ } = useContext(CopilotContext);
15
+ const [messages, setMessages] = useState([]);
16
+ const [input, setInput] = useState("");
17
+ const [threadId, setThreadId] = useState(void 0);
18
+ const [status, setStatus] = useState("awaiting_message");
19
+ const [error, setError] = useState(void 0);
20
+ useMemo(() => {
21
+ const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage;
22
+ const contextString = getContextString([], defaultCopilotContextCategories);
23
+ return {
24
+ id: "system",
25
+ content: systemMessageMaker(contextString),
26
+ role: "system"
27
+ };
28
+ }, [getContextString, options.makeSystemMessage]);
29
+ const handleInputChange = (e) => {
30
+ setInput(e.target.value);
31
+ };
32
+ const submitMessage = (e) => __async(this, null, function* () {
33
+ var _a, _b;
34
+ e.preventDefault();
35
+ if (input === "") {
36
+ return;
37
+ }
38
+ setStatus("in_progress");
39
+ setMessages((messages2) => [...messages2, { id: "", role: "user", content: input }]);
40
+ setInput("");
41
+ const apiUrl = copilotApiConfigExtrapolator(copilotApiConfig).chatApiEndpointV2;
42
+ const functions = getChatCompletionFunctionDescriptions();
43
+ const result = yield fetch(apiUrl, {
44
+ method: "POST",
45
+ headers: __spreadValues(__spreadValues({
46
+ "Content-Type": "application/json"
47
+ }, copilotApiConfig.headers), options.headers),
48
+ body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues({
49
+ // always use user-provided threadId when available:
50
+ threadId: (_b = (_a = options.threadId) != null ? _a : threadId) != null ? _b : null,
51
+ message: input
52
+ }, functions.length > 0 && { functions }), copilotApiConfig.body), options.body))
53
+ });
54
+ if (result.body == null) {
55
+ throw new Error("The response body is empty.");
56
+ }
57
+ yield processMessageStream(result.body.getReader(), (message) => {
58
+ try {
59
+ const { type, value } = parseStreamPart(message);
60
+ switch (type) {
61
+ case "assistant_message": {
62
+ setMessages((messages2) => [
63
+ ...messages2,
64
+ {
65
+ id: value.id,
66
+ role: value.role,
67
+ content: value.content[0].text.value
68
+ }
69
+ ]);
70
+ break;
71
+ }
72
+ case "assistant_control_data": {
73
+ setThreadId(value.threadId);
74
+ setMessages((messages2) => {
75
+ const lastMessage = messages2[messages2.length - 1];
76
+ lastMessage.id = value.messageId;
77
+ return [...messages2.slice(0, messages2.length - 1), lastMessage];
78
+ });
79
+ break;
80
+ }
81
+ case "error": {
82
+ setError(value);
83
+ break;
84
+ }
85
+ }
86
+ } catch (error2) {
87
+ setError(error2);
88
+ }
89
+ });
90
+ setStatus("awaiting_message");
91
+ });
92
+ return {
93
+ messages,
94
+ input,
95
+ handleInputChange,
96
+ submitMessage,
97
+ status,
98
+ error
99
+ };
100
+ }
101
+ function defaultSystemMessage(contextString) {
102
+ return `
103
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
104
+
105
+ Help the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.
106
+ Always be polite and respectful, and prefer brevity over verbosity.
107
+
108
+ The user has provided you with the following context:
109
+ \`\`\`
110
+ ${contextString}
111
+ \`\`\`
112
+
113
+ They have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.
114
+
115
+ Please assist them as best you can.
116
+
117
+ You can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.
118
+
119
+ If you would like to call a function, call it without saying anything else.
120
+ `;
121
+ }
122
+
123
+ export { defaultSystemMessage, useCopilotChatV2 };
124
+ //# sourceMappingURL=out.js.map
125
+ //# sourceMappingURL=chunk-JHJ7LUTD.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/openai-assistants/hooks/use-copilot-chat-v2.ts"],"names":["messages","error"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,SAAS,gBAAgB;AAE9C,SAAkB,uBAAuB;AA6ClC,SAAS,iBAAiB,SAA0D;AACzF,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,WAAW,cAAc;AAE7B,QAAM,CAAC,UAAU,WAAW,IAAI,SAAoB,CAAC,CAAC;AACtD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAS,EAAE;AACrC,QAAM,CAAC,UAAU,WAAW,IAAI,SAA6B,MAAS;AACtE,QAAM,CAAC,QAAQ,SAAS,IAAI,SAA0B,kBAAkB;AACxE,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA8B,MAAS;AAEjE,QAAM,gBAAyB,QAAQ,MAAM;AAC3C,UAAM,qBAAqB,QAAQ,qBAAqB;AACxD,UAAM,gBAAgB,iBAAiB,CAAC,GAAG,+BAA+B;AAE1E,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,SAAS,mBAAmB,aAAa;AAAA,MACzC,MAAM;AAAA,IACR;AAAA,EACF,GAAG,CAAC,kBAAkB,QAAQ,iBAAiB,CAAC;AAEhD,QAAM,oBAAoB,CAAC,MAAW;AACpC,aAAS,EAAE,O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0BAAY,KAAK,MAAM;AACvB,qBAAO,CAAC,GAAGA,UAAS,MAAM,GAAGA,UAAS,SAAS,CAAC,GAAG,WAAW;AAAA,YAChE,CAAC;AAED;AAAA,UACF;AAAA,UAEA,KAAK,SAAS;AACZ,qBAAS,KAAK;AACd;AAAA,UACF;AAAA,QACF;AAAA,MACF,SAASC,QAAP;AACA,iBAASA,MAAK;AAAA,MAChB;AAAA,IACF,CAAC;AAED,cAAU,kBAAkB;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,qBAAqB,eAA+B;AAClE,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWF","sourcesContent":["import { useContext, useMemo, useState } from \"react\";\nimport { processMessageStream } from \"../utils\";\nimport { Message, parseStreamPart } from \"@copilotkit/shared\";\nimport { CopilotContext, copilotApiConfigExtrapolator } from \"../../context\";\nimport { defaultCopilotContextCategories } from \"../../components\";\n\nexport type AssistantStatus = \"in_progress\" | \"awaiting_message\";\n\nexport interface RequestForwardingOptions {\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 * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n}\nexport interface UseCopilotChatOptionsV2 extends RequestForwardingOptions {\n makeSystemMessage?: (contextString: string) => string;\n threadId?: string | undefined;\n}\n\nexport interface UseCopilotChatV2Result {\n messages: Message[];\n input: string;\n handleInputChange: (e: any) => void;\n submitMessage: (e: any) => Promise<void>;\n status: AssistantStatus;\n error: unknown;\n}\n\nexport function useCopilotChatV2(options: UseCopilotChatOptionsV2): UseCopilotChatV2Result {\n const {\n getContextString,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n copilotApiConfig,\n } = useContext(CopilotContext);\n\n const [messages, setMessages] = useState<Message[]>([]);\n const [input, setInput] = useState(\"\");\n const [threadId, setThreadId] = useState<string | undefined>(undefined);\n const [status, setStatus] = useState<AssistantStatus>(\"awaiting_message\");\n const [error, setError] = useState<unknown | undefined>(undefined);\n\n const systemMessage: Message = useMemo(() => {\n const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage;\n const contextString = getContextString([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return {\n id: \"system\",\n content: systemMessageMaker(contextString),\n role: \"system\",\n };\n }, [getContextString, options.makeSystemMessage]);\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const submitMessage = async (e: any) => {\n e.preventDefault();\n\n if (input === \"\") {\n return;\n }\n\n setStatus(\"in_progress\");\n\n setMessages((messages) => [...messages, { id: \"\", role: \"user\", content: input }]);\n\n setInput(\"\");\n\n const apiUrl = copilotApiConfigExtrapolator(copilotApiConfig).chatApiEndpointV2;\n\n const functions = getChatCompletionFunctionDescriptions();\n\n const result = await fetch(apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...copilotApiConfig.headers,\n ...options.headers,\n },\n body: JSON.stringify({\n // always use user-provided threadId when available:\n threadId: options.threadId ?? threadId ?? null,\n message: input,\n ...(functions.length > 0 && { functions: functions }),\n ...copilotApiConfig.body,\n ...options.body,\n }),\n });\n\n if (result.body == null) {\n throw new Error(\"The response body is empty.\");\n }\n\n await processMessageStream(result.body.getReader(), (message: string) => {\n try {\n const { type, value } = parseStreamPart(message);\n\n switch (type) {\n case \"assistant_message\": {\n // append message:\n setMessages((messages) => [\n ...messages,\n {\n id: value.id,\n role: value.role,\n content: value.content[0].text.value,\n },\n ]);\n break;\n }\n\n case \"assistant_control_data\": {\n setThreadId(value.threadId);\n\n // set id of last message:\n setMessages((messages) => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.id = value.messageId;\n return [...messages.slice(0, messages.length - 1), lastMessage];\n });\n\n break;\n }\n\n case \"error\": {\n setError(value);\n break;\n }\n }\n } catch (error) {\n setError(error);\n }\n });\n\n setStatus(\"awaiting_message\");\n };\n\n return {\n messages,\n input,\n handleInputChange,\n submitMessage,\n status,\n error,\n };\n}\n\nexport function defaultSystemMessage(contextString: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\n`;\n}\n"]}
@@ -0,0 +1,55 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __objRest = (source, exclude) => {
21
+ var target = {};
22
+ for (var prop in source)
23
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
+ target[prop] = source[prop];
25
+ if (source != null && __getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(source)) {
27
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
+ target[prop] = source[prop];
29
+ }
30
+ return target;
31
+ };
32
+ var __async = (__this, __arguments, generator) => {
33
+ return new Promise((resolve, reject) => {
34
+ var fulfilled = (value) => {
35
+ try {
36
+ step(generator.next(value));
37
+ } catch (e) {
38
+ reject(e);
39
+ }
40
+ };
41
+ var rejected = (value) => {
42
+ try {
43
+ step(generator.throw(value));
44
+ } catch (e) {
45
+ reject(e);
46
+ }
47
+ };
48
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
49
+ step((generator = generator.apply(__this, __arguments)).next());
50
+ });
51
+ };
52
+
53
+ export { __async, __objRest, __spreadProps, __spreadValues };
54
+ //# sourceMappingURL=out.js.map
55
+ //# sourceMappingURL=chunk-MRXNTQOX.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","sourcesContent":[]}
@@ -0,0 +1,28 @@
1
+ import { __async } from './chunk-MRXNTQOX.mjs';
2
+
3
+ // src/openai-assistants/utils/process-message-stream.ts
4
+ function processMessageStream(reader, processMessage) {
5
+ return __async(this, null, function* () {
6
+ const decoder = new TextDecoder();
7
+ let buffer = "";
8
+ while (true) {
9
+ const { done, value } = yield reader.read();
10
+ if (done) {
11
+ if (buffer.length > 0) {
12
+ processMessage(buffer);
13
+ }
14
+ break;
15
+ }
16
+ buffer += decoder.decode(value, { stream: true });
17
+ let endIndex;
18
+ while ((endIndex = buffer.indexOf("\n")) !== -1) {
19
+ processMessage(buffer.substring(0, endIndex).trim());
20
+ buffer = buffer.substring(endIndex + 1);
21
+ }
22
+ }
23
+ });
24
+ }
25
+
26
+ export { processMessageStream };
27
+ //# sourceMappingURL=out.js.map
28
+ //# sourceMappingURL=chunk-MZ5UN3BY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/openai-assistants/utils/process-message-stream.ts"],"names":[],"mappings":";;;;;AAAA,SAAsB,qBACpB,QACA,gBACA;AAAA;AACA,UAAM,UAAU,IAAI,YAAY;AAChC,QAAI,SAAS;AACb,WAAO,MAAM;AACX,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,UAAI,MAAM;AACR,YAAI,OAAO,SAAS,GAAG;AACrB,yBAAe,MAAM;AAAA,QACvB;AACA;AAAA,MACF;AAEA,gBAAU,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC;AAEhD,UAAI;AACJ,cAAQ,WAAW,OAAO,QAAQ,IAAI,OAAO,IAAI;AAC/C,uBAAe,OAAO,UAAU,GAAG,QAAQ,EAAE,KAAK,CAAC;AACnD,iBAAS,OAAO,UAAU,WAAW,CAAC;AAAA,MACxC;AAAA,IACF;AAAA,EACF;AAAA","sourcesContent":["export async function processMessageStream(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n processMessage: (message: string) => void | Promise<void>,\n) {\n const decoder = new TextDecoder();\n let buffer = \"\";\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n if (buffer.length > 0) {\n processMessage(buffer);\n }\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n\n let endIndex: number;\n while ((endIndex = buffer.indexOf(\"\\n\")) !== -1) {\n processMessage(buffer.substring(0, endIndex).trim());\n buffer = buffer.substring(endIndex + 1); // Remove the processed instruction + delimiter\n }\n }\n}\n"]}
@@ -0,0 +1,79 @@
1
+ import { defaultCopilotContextCategories } from './chunk-6LKBKYRJ.mjs';
2
+ import { CopilotContext, copilotApiConfigExtrapolator } from './chunk-3MAIWZNZ.mjs';
3
+ import { __objRest, __spreadProps, __spreadValues } from './chunk-MRXNTQOX.mjs';
4
+ import { useContext, useMemo } from 'react';
5
+ import { useChat } from 'ai/react';
6
+
7
+ function useCopilotChat(_a) {
8
+ var _b = _a, {
9
+ makeSystemMessage
10
+ } = _b, options = __objRest(_b, [
11
+ "makeSystemMessage"
12
+ ]);
13
+ const {
14
+ getContextString,
15
+ getChatCompletionFunctionDescriptions,
16
+ getFunctionCallHandler,
17
+ copilotApiConfig
18
+ } = useContext(CopilotContext);
19
+ const systemMessage = useMemo(() => {
20
+ const systemMessageMaker = makeSystemMessage || defaultSystemMessage;
21
+ const contextString = getContextString([], defaultCopilotContextCategories);
22
+ return {
23
+ id: "system",
24
+ content: systemMessageMaker(contextString),
25
+ role: "system"
26
+ };
27
+ }, [getContextString, makeSystemMessage]);
28
+ const initialMessagesWithContext = [systemMessage].concat(options.initialMessages || []);
29
+ const functionDescriptions = useMemo(() => {
30
+ return getChatCompletionFunctionDescriptions();
31
+ }, [getChatCompletionFunctionDescriptions]);
32
+ const { messages, append, reload, stop, isLoading, input, setInput } = useChat(__spreadProps(__spreadValues({}, options), {
33
+ api: copilotApiConfigExtrapolator(copilotApiConfig).chatApiEndpoint,
34
+ id: options.id,
35
+ initialMessages: initialMessagesWithContext,
36
+ experimental_onFunctionCall: getFunctionCallHandler(),
37
+ headers: __spreadValues(__spreadValues({}, copilotApiConfig.headers), options.headers),
38
+ body: __spreadValues(__spreadValues(__spreadValues({
39
+ id: options.id
40
+ }, functionDescriptions.length > 0 && { functions: functionDescriptions }), copilotApiConfig.body), options.body)
41
+ }));
42
+ const visibleMessages = messages.filter(
43
+ (message) => message.role === "user" || message.role === "assistant"
44
+ );
45
+ return {
46
+ visibleMessages,
47
+ append,
48
+ reload,
49
+ stop,
50
+ isLoading,
51
+ input,
52
+ setInput
53
+ };
54
+ }
55
+ function defaultSystemMessage(contextString) {
56
+ return `
57
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
58
+
59
+ Help the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.
60
+ Always be polite and respectful, and prefer brevity over verbosity.
61
+
62
+ The user has provided you with the following context:
63
+ \`\`\`
64
+ ${contextString}
65
+ \`\`\`
66
+
67
+ They have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.
68
+
69
+ Please assist them as best you can.
70
+
71
+ You can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.
72
+
73
+ If you would like to call a function, call it without saying anything else.
74
+ `;
75
+ }
76
+
77
+ export { defaultSystemMessage, useCopilotChat };
78
+ //# sourceMappingURL=out.js.map
79
+ //# sourceMappingURL=chunk-OFRZZ5OF.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-chat.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,SAAS,kBAAkB;AAMpC,SAAS,eAAe;AAuBjB,SAAS,eAAe,IAGiB;AAHjB,eAC7B;AAAA;AAAA,EA9BF,IA6B+B,IAE1B,oBAF0B,IAE1B;AAAA,IADH;AAAA;AAGA,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,WAAW,cAAc;AAE7B,QAAM,gBAAyB,QAAQ,MAAM;AAC3C,UAAM,qBAAqB,qBAAqB;AAChD,UAAM,gBAAgB,iBAAiB,CAAC,GAAG,+BAA+B;AAE1E,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,SAAS,mBAAmB,aAAa;AAAA,MACzC,MAAM;AAAA,IACR;AAAA,EACF,GAAG,CAAC,kBAAkB,iBAAiB,CAAC;AAExC,QAAM,6BAA6B,CAAC,aAAa,EAAE,OAAO,QAAQ,mBAAmB,CAAC,CAAC;AAEvF,QAAM,uBAA8D,QAAQ,MAAM;AAChF,WAAO,sCAAsC;AAAA,EAC/C,GAAG,CAAC,qCAAqC,CAAC;AAE1C,QAAM,EAAE,UAAU,QAAQ,QAAQ,MAAM,WAAW,OAAO,SAAS,IAAI,QAAQ,iCAC1E,UAD0E;AAAA,IAE7E,KAAK,6BAA6B,gBAAgB,EAAE;AAAA,IACpD,IAAI,QAAQ;AAAA,IACZ,iBAAiB;AAAA,IACjB,6BAA6B,uBAAuB;AAAA,IACpD,SAAS,kCAAK,iBAAiB,UAAY,QAAQ;AAAA,IACnD,MAAM;AAAA,MACJ,IAAI,QAAQ;AAAA,OACR,qBAAqB,SAAS,KAAK,EAAE,WAAW,qBAAqB,IACtE,iBAAiB,OACjB,QAAQ;AAAA,EAEf,EAAC;AAED,QAAM,kBAAkB,SAAS;AAAA,IAC/B,CAAC,YAAY,QAAQ,SAAS,UAAU,QAAQ,SAAS;AAAA,EAC3D;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,qBAAqB,eAA+B;AAClE,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWF","sourcesContent":["import { useMemo, useContext } from \"react\";\nimport {\n CopilotContext,\n CopilotContextParams,\n copilotApiConfigExtrapolator,\n} from \"../context/copilot-context\";\nimport { useChat } from \"ai/react\";\nimport { ChatRequestOptions, CreateMessage, Message } from \"ai\";\nimport { UseChatOptions } from \"ai\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { ChatCompletionCreateParams } from \"openai/resources/chat\";\n\nexport interface UseCopilotChatOptions extends UseChatOptions {\n makeSystemMessage?: (contextString: string) => string;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n append: (\n message: Message | CreateMessage,\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n reload: (chatRequestOptions?: ChatRequestOptions) => Promise<string | null | undefined>;\n stop: () => void;\n isLoading: boolean;\n input: string;\n setInput: React.Dispatch<React.SetStateAction<string>>;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions): UseCopilotChatReturn {\n const {\n getContextString,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n copilotApiConfig,\n } = useContext(CopilotContext);\n\n const systemMessage: Message = useMemo(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n const contextString = getContextString([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return {\n id: \"system\",\n content: systemMessageMaker(contextString),\n role: \"system\",\n };\n }, [getContextString, makeSystemMessage]);\n\n const initialMessagesWithContext = [systemMessage].concat(options.initialMessages || []);\n\n const functionDescriptions: ChatCompletionCreateParams.Function[] = useMemo(() => {\n return getChatCompletionFunctionDescriptions();\n }, [getChatCompletionFunctionDescriptions]);\n\n const { messages, append, reload, stop, isLoading, input, setInput } = useChat({\n ...options,\n api: copilotApiConfigExtrapolator(copilotApiConfig).chatApiEndpoint,\n id: options.id,\n initialMessages: initialMessagesWithContext,\n experimental_onFunctionCall: getFunctionCallHandler(),\n headers: { ...copilotApiConfig.headers, ...options.headers },\n body: {\n id: options.id,\n ...(functionDescriptions.length > 0 && { functions: functionDescriptions }),\n ...copilotApiConfig.body,\n ...options.body,\n },\n });\n\n const visibleMessages = messages.filter(\n (message) => message.role === \"user\" || message.role === \"assistant\",\n );\n\n return {\n visibleMessages,\n append,\n reload,\n stop,\n isLoading,\n input,\n setInput,\n };\n}\n\nexport function defaultSystemMessage(contextString: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\n`;\n}\n"]}
@@ -0,0 +1,3 @@
1
+
2
+ //# sourceMappingURL=out.js.map
3
+ //# sourceMappingURL=chunk-QACD2U6P.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -0,0 +1,3 @@
1
+
2
+ //# sourceMappingURL=out.js.map
3
+ //# sourceMappingURL=chunk-SPCZTZCY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -0,0 +1,135 @@
1
+ import { __spreadProps, __spreadValues } from './chunk-MRXNTQOX.mjs';
2
+ import { nanoid } from 'nanoid';
3
+ import { useReducer, useCallback } from 'react';
4
+
5
+ var removeNode = (nodes, id) => {
6
+ return nodes.reduce((result, node) => {
7
+ if (node.id !== id) {
8
+ const newNode = __spreadProps(__spreadValues({}, node), { children: removeNode(node.children, id) });
9
+ result.push(newNode);
10
+ }
11
+ return result;
12
+ }, []);
13
+ };
14
+ var addNode = (nodes, newNode, parentId) => {
15
+ if (!parentId) {
16
+ return [...nodes, newNode];
17
+ }
18
+ return nodes.map((node) => {
19
+ if (node.id === parentId) {
20
+ return __spreadProps(__spreadValues({}, node), { children: [...node.children, newNode] });
21
+ } else if (node.children.length) {
22
+ return __spreadProps(__spreadValues({}, node), { children: addNode(node.children, newNode, parentId) });
23
+ }
24
+ return node;
25
+ });
26
+ };
27
+ var treeIndentationRepresentation = (index, indentLevel) => {
28
+ if (indentLevel === 0) {
29
+ return (index + 1).toString();
30
+ } else if (indentLevel === 1) {
31
+ return String.fromCharCode(65 + index);
32
+ } else if (indentLevel === 2) {
33
+ return String.fromCharCode(97 + index);
34
+ } else {
35
+ return "-";
36
+ }
37
+ };
38
+ var printNode = (node, prefix = "", indentLevel = 0) => {
39
+ const indent = " ".repeat(3).repeat(indentLevel);
40
+ const prefixPlusIndentLength = prefix.length + indent.length;
41
+ const subsequentLinesPrefix = " ".repeat(prefixPlusIndentLength);
42
+ const valueLines = node.value.split("\n");
43
+ const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;
44
+ const outputSubsequentLines = valueLines.slice(1).map((line) => `${subsequentLinesPrefix}${line}`).join("\n");
45
+ let output = `${outputFirstLine}
46
+ `;
47
+ if (outputSubsequentLines) {
48
+ output += `${outputSubsequentLines}
49
+ `;
50
+ }
51
+ const childPrePrefix = " ".repeat(prefix.length);
52
+ node.children.forEach(
53
+ (child, index) => output += printNode(
54
+ child,
55
+ `${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `,
56
+ indentLevel + 1
57
+ )
58
+ );
59
+ return output;
60
+ };
61
+ function treeReducer(state, action) {
62
+ switch (action.type) {
63
+ case "ADD_NODE": {
64
+ const { value, parentId, id: newNodeId } = action;
65
+ const newNode = {
66
+ id: newNodeId,
67
+ value,
68
+ children: [],
69
+ categories: new Set(action.categories)
70
+ };
71
+ try {
72
+ return addNode(state, newNode, parentId);
73
+ } catch (error) {
74
+ console.error(`Error while adding node with id ${newNodeId}: ${error}`);
75
+ return state;
76
+ }
77
+ }
78
+ case "REMOVE_NODE":
79
+ return removeNode(state, action.id);
80
+ default:
81
+ return state;
82
+ }
83
+ }
84
+ var useTree = () => {
85
+ const [tree, dispatch] = useReducer(treeReducer, []);
86
+ const addElement = useCallback(
87
+ (value, categories, parentId) => {
88
+ const newNodeId = nanoid();
89
+ dispatch({
90
+ type: "ADD_NODE",
91
+ value,
92
+ parentId,
93
+ id: newNodeId,
94
+ categories
95
+ });
96
+ return newNodeId;
97
+ },
98
+ []
99
+ );
100
+ const removeElement = useCallback((id) => {
101
+ dispatch({ type: "REMOVE_NODE", id });
102
+ }, []);
103
+ const printTree = useCallback(
104
+ (categories) => {
105
+ const categoriesSet = new Set(categories);
106
+ let output = "";
107
+ tree.forEach((node, index) => {
108
+ if (!setsHaveIntersection(categoriesSet, node.categories)) {
109
+ return;
110
+ }
111
+ if (index !== 0) {
112
+ output += "\n";
113
+ }
114
+ output += printNode(node, `${treeIndentationRepresentation(index, 0)}. `);
115
+ });
116
+ return output;
117
+ },
118
+ [tree]
119
+ );
120
+ return { tree, addElement, printTree, removeElement };
121
+ };
122
+ var use_tree_default = useTree;
123
+ function setsHaveIntersection(setA, setB) {
124
+ const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
125
+ for (let item of smallerSet) {
126
+ if (largerSet.has(item)) {
127
+ return true;
128
+ }
129
+ }
130
+ return false;
131
+ }
132
+
133
+ export { use_tree_default };
134
+ //# sourceMappingURL=out.js.map
135
+ //# sourceMappingURL=chunk-VUY2K2DI.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-tree.ts"],"names":[],"mappings":";;;;;;AAAA,SAAS,cAAc;AACvB,SAAS,aAAa,kBAAkB;AAkCxC,IAAM,aAAa,CAAC,OAAa,OAAyB;AACxD,SAAO,MAAM,OAAO,CAAC,QAAc,SAAS;AAC1C,QAAI,KAAK,OAAO,IAAI;AAClB,YAAM,UAAU,iCAAK,OAAL,EAAW,UAAU,WAAW,KAAK,UAAU,EAAE,EAAE;AACnE,aAAO,KAAK,OAAO;AAAA,IACrB;AACA,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AACP;AAEA,IAAM,UAAU,CAAC,OAAa,SAAmB,aAAgC;AAC/E,MAAI,CAAC,UAAU;AACb,WAAO,CAAC,GAAG,OAAO,OAAO;AAAA,EAC3B;AACA,SAAO,MAAM,IAAI,CAAC,SAAS;AACzB,QAAI,KAAK,OAAO,UAAU;AACxB,aAAO,iCAAK,OAAL,EAAW,UAAU,CAAC,GAAG,KAAK,UAAU,OAAO,EAAE;AAAA,IAC1D,WAAW,KAAK,SAAS,QAAQ;AAC/B,aAAO,iCAAK,OAAL,EAAW,UAAU,QAAQ,KAAK,UAAU,SAAS,QAAQ,EAAE;AAAA,IACxE;AACA,WAAO;AAAA,EACT,CAAC;AACH;AAEA,IAAM,gCAAgC,CA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AAEnF,WAAS,QAAQ,YAAY;AAC3B,QAAI,UAAU,IAAI,IAAI,GAAG;AACvB,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT","sourcesContent":["import { nanoid } from \"nanoid\";\nimport { useCallback, useReducer } from \"react\";\n\nexport type TreeNodeId = string;\n\nexport interface TreeNode {\n id: TreeNodeId;\n value: string;\n children: TreeNode[];\n parentId?: TreeNodeId;\n categories: Set<string>;\n}\n\nexport type Tree = TreeNode[];\n\nexport interface UseTreeReturn {\n tree: Tree;\n addElement: (value: string, categories: string[], parentId?: TreeNodeId) => TreeNodeId;\n printTree: (categories: string[]) => string;\n removeElement: (id: TreeNodeId) => void;\n}\n\nconst findNode = (nodes: Tree, id: TreeNodeId): TreeNode | undefined => {\n for (const node of nodes) {\n if (node.id === id) {\n return node;\n }\n const result = findNode(node.children, id);\n if (result) {\n return result;\n }\n }\n return undefined;\n};\n\nconst removeNode = (nodes: Tree, id: TreeNodeId): Tree => {\n return nodes.reduce((result: Tree, node) => {\n if (node.id !== id) {\n const newNode = { ...node, children: removeNode(node.children, id) };\n result.push(newNode);\n }\n return result;\n }, []);\n};\n\nconst addNode = (nodes: Tree, newNode: TreeNode, parentId?: TreeNodeId): Tree => {\n if (!parentId) {\n return [...nodes, newNode];\n }\n return nodes.map((node) => {\n if (node.id === parentId) {\n return { ...node, children: [...node.children, newNode] };\n } else if (node.children.length) {\n return { ...node, children: addNode(node.children, newNode, parentId) };\n }\n return node;\n });\n};\n\nconst treeIndentationRepresentation = (index: number, indentLevel: number): string => {\n if (indentLevel === 0) {\n return (index + 1).toString();\n } else if (indentLevel === 1) {\n return String.fromCharCode(65 + index); // 65 is the ASCII value for 'A'\n } else if (indentLevel === 2) {\n return String.fromCharCode(97 + index); // 97 is the ASCII value for 'a'\n } else {\n return \"-\";\n }\n};\n\nconst printNode = (node: TreeNode, prefix = \"\", indentLevel = 0): string => {\n const indent = \" \".repeat(3).repeat(indentLevel);\n\n const prefixPlusIndentLength = prefix.length + indent.length;\n const subsequentLinesPrefix = \" \".repeat(prefixPlusIndentLength);\n\n const valueLines = node.value.split(\"\\n\");\n\n const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;\n const outputSubsequentLines = valueLines\n .slice(1)\n .map((line) => `${subsequentLinesPrefix}${line}`)\n .join(\"\\n\");\n\n let output = `${outputFirstLine}\\n`;\n if (outputSubsequentLines) {\n output += `${outputSubsequentLines}\\n`;\n }\n\n const childPrePrefix = \" \".repeat(prefix.length);\n\n node.children.forEach(\n (child, index) =>\n (output += printNode(\n child,\n `${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `,\n indentLevel + 1,\n )),\n );\n return output;\n};\n\n// Action types\ntype Action =\n | {\n type: \"ADD_NODE\";\n value: string;\n parentId?: string;\n id: string;\n categories: string[];\n }\n | { type: \"REMOVE_NODE\"; id: string };\n\n// Reducer function\nfunction treeReducer(state: Tree, action: Action): Tree {\n switch (action.type) {\n case \"ADD_NODE\": {\n const { value, parentId, id: newNodeId } = action;\n const newNode: TreeNode = {\n id: newNodeId,\n value,\n children: [],\n categories: new Set(action.categories),\n };\n\n try {\n return addNode(state, newNode, parentId);\n } catch (error) {\n console.error(`Error while adding node with id ${newNodeId}: ${error}`);\n return state;\n }\n }\n case \"REMOVE_NODE\":\n return removeNode(state, action.id);\n default:\n return state;\n }\n}\n\n// useTree hook\nconst useTree = (): UseTreeReturn => {\n const [tree, dispatch] = useReducer(treeReducer, []);\n\n const addElement = useCallback(\n (value: string, categories: string[], parentId?: string): TreeNodeId => {\n const newNodeId = nanoid(); // Generate new ID outside of dispatch\n dispatch({\n type: \"ADD_NODE\",\n value,\n parentId,\n id: newNodeId,\n categories: categories,\n });\n return newNodeId; // Return the new ID\n },\n [],\n );\n\n const removeElement = useCallback((id: TreeNodeId): void => {\n dispatch({ type: \"REMOVE_NODE\", id });\n }, []);\n\n const printTree = useCallback(\n (categories: string[]): string => {\n const categoriesSet = new Set(categories);\n\n let output = \"\";\n tree.forEach((node, index) => {\n // if the node does not have any of the desired categories, continue to the next node\n if (!setsHaveIntersection(categoriesSet, node.categories)) {\n return;\n }\n\n // add a new line before each node except the first one\n if (index !== 0) {\n output += \"\\n\";\n }\n\n output += printNode(node, `${treeIndentationRepresentation(index, 0)}. `);\n });\n return output;\n },\n [tree],\n );\n\n return { tree, addElement, printTree, removeElement };\n};\n\nexport default useTree;\n\nfunction setsHaveIntersection<T>(setA: Set<T>, setB: Set<T>): boolean {\n const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];\n\n for (let item of smallerSet) {\n if (largerSet.has(item)) {\n return true;\n }\n }\n\n return false;\n}\n"]}
@@ -0,0 +1,3 @@
1
+
2
+ //# sourceMappingURL=out.js.map
3
+ //# sourceMappingURL=chunk-YPSGKPDA.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -0,0 +1,70 @@
1
+ import { nanoid } from 'nanoid';
2
+ import { useReducer, useCallback } from 'react';
3
+
4
+ // src/hooks/use-flat-category-store.ts
5
+ var useFlatCategoryStore = () => {
6
+ const [elements, dispatch] = useReducer(flatCategoryStoreReducer, /* @__PURE__ */ new Map());
7
+ const addElement = useCallback((value, categories) => {
8
+ const newId = nanoid();
9
+ dispatch({
10
+ type: "ADD_ELEMENT",
11
+ value,
12
+ id: newId,
13
+ categories
14
+ });
15
+ return newId;
16
+ }, []);
17
+ const removeElement = useCallback((id) => {
18
+ dispatch({ type: "REMOVE_ELEMENT", id });
19
+ }, []);
20
+ const allElements = useCallback(
21
+ (categories) => {
22
+ const categoriesSet = new Set(categories);
23
+ const result = [];
24
+ elements.forEach((element) => {
25
+ if (setsHaveIntersection(categoriesSet, element.categories)) {
26
+ result.push(element.value);
27
+ }
28
+ });
29
+ return result;
30
+ },
31
+ [elements]
32
+ );
33
+ return { addElement, removeElement, allElements };
34
+ };
35
+ var use_flat_category_store_default = useFlatCategoryStore;
36
+ function flatCategoryStoreReducer(state, action) {
37
+ switch (action.type) {
38
+ case "ADD_ELEMENT": {
39
+ const { value, id, categories } = action;
40
+ const newElement = {
41
+ id,
42
+ value,
43
+ categories: new Set(categories)
44
+ };
45
+ const newState = new Map(state);
46
+ newState.set(id, newElement);
47
+ return newState;
48
+ }
49
+ case "REMOVE_ELEMENT": {
50
+ const newState = new Map(state);
51
+ newState.delete(action.id);
52
+ return newState;
53
+ }
54
+ default:
55
+ return state;
56
+ }
57
+ }
58
+ function setsHaveIntersection(setA, setB) {
59
+ const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
60
+ for (let item of smallerSet) {
61
+ if (largerSet.has(item)) {
62
+ return true;
63
+ }
64
+ }
65
+ return false;
66
+ }
67
+
68
+ export { use_flat_category_store_default };
69
+ //# sourceMappingURL=out.js.map
70
+ //# sourceMappingURL=chunk-YULKJPY3.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-flat-category-store.ts"],"names":[],"mappings":";AAAA,SAAS,cAAc;AACvB,SAAS,aAAa,kBAAkB;AAgBxC,IAAM,uBAAuB,MAAwC;AACnE,QAAM,CAAC,UAAU,QAAQ,IAAI,WAE3B,0BAA0B,oBAAI,IAAsD,CAAC;AAEvF,QAAM,aAAa,YAAY,CAAC,OAAU,eAA8C;AACtF,UAAM,QAAQ,OAAO;AACrB,aAAS;AAAA,MACP,MAAM;AAAA,MACN;AAAA,MACA,IAAI;AAAA,MACJ;AAAA,IACF,CAAC;AACD,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AAEL,QAAM,gBAAgB,YAAY,CAAC,OAAkC;AACnE,aAAS,EAAE,MAAM,kBAAkB,GAAG,CAAC;AAAA,EACzC,GAAG,CAAC,CAAC;AAEL,QAAM,cAAc;AAAA,IAClB,CAAC,eAA8B;AAC7B,YAAM,gBAAgB,IAAI,IAAI,UAAU;AACxC,YAAM,SAAc,CAAC;AACrB,eAAS,QAAQ,CAAC,YAAY;AAC5B,YAAI,qBAAqB,eAAe,QAAQ,UAAU,GAAG;AAC3D,iBAAO,KAAK,QAAQ,KAAK;AAAA,QAC3B;AAAA,MACF,CAAC;AACD,aAAO;AAAA,IACT;AAAA,IACA,CAAC,QAAQ;AAAA,EACX;AAEA,SAAO,EAAE,YAAY,eAAe,YAAY;AAClD;AAEA,IAAO,kCAAQ;AAaf,SAAS,yBACP,OACA,QACuD;AACvD,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK,eAAe;AAClB,YAAM,EAAE,OAAO,IAAI,WAAW,IAAI;AAClC,YAAM,aAA0C;AAAA,QAC9C;AAAA,QACA;AAAA,QACA,YAAY,IAAI,IAAI,UAAU;AAAA,MAChC;AACA,YAAM,WAAW,IAAI,IAAI,KAAK;AAC9B,eAAS,IAAI,IAAI,UAAU;AAC3B,aAAO;AAAA,IACT;AAAA,IACA,KAAK,kBAAkB;AACrB,YAAM,WAAW,IAAI,IAAI,KAAK;AAC9B,eAAS,OAAO,OAAO,EAAE;AACzB,aAAO;AAAA,IACT;AAAA,IACA;AACE,aAAO;AAAA,EACX;AACF;AAEA,SAAS,qBAAwB,MAAc,MAAuB;AACpE,QAAM,CAAC,YAAY,SAAS,IAAI,KAAK,QAAQ,KAAK,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,IAAI;AAEnF,WAAS,QAAQ,YAAY;AAC3B,QAAI,UAAU,IAAI,IAAI,GAAG;AACvB,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT","sourcesContent":["import { nanoid } from \"nanoid\";\nimport { useCallback, useReducer } from \"react\";\n\nexport type FlatCategoryStoreId = string;\n\nexport interface UseFlatCategoryStoreReturn<T> {\n addElement: (value: T, categories: string[]) => FlatCategoryStoreId;\n removeElement: (id: FlatCategoryStoreId) => void;\n allElements: (categories: string[]) => T[];\n}\n\ninterface FlatCategoryStoreElement<T> {\n id: FlatCategoryStoreId;\n value: T;\n categories: Set<string>;\n}\n\nconst useFlatCategoryStore = <T>(): UseFlatCategoryStoreReturn<T> => {\n const [elements, dispatch] = useReducer<\n React.Reducer<Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>>, Action<T>>\n >(flatCategoryStoreReducer, new Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>>());\n\n const addElement = useCallback((value: T, categories: string[]): FlatCategoryStoreId => {\n const newId = nanoid();\n dispatch({\n type: \"ADD_ELEMENT\",\n value,\n id: newId,\n categories,\n });\n return newId;\n }, []);\n\n const removeElement = useCallback((id: FlatCategoryStoreId): void => {\n dispatch({ type: \"REMOVE_ELEMENT\", id });\n }, []);\n\n const allElements = useCallback(\n (categories: string[]): T[] => {\n const categoriesSet = new Set(categories);\n const result: T[] = [];\n elements.forEach((element) => {\n if (setsHaveIntersection(categoriesSet, element.categories)) {\n result.push(element.value);\n }\n });\n return result;\n },\n [elements],\n );\n\n return { addElement, removeElement, allElements };\n};\n\nexport default useFlatCategoryStore;\n\n// Action types\ntype Action<T> =\n | {\n type: \"ADD_ELEMENT\";\n value: T;\n id: FlatCategoryStoreId;\n categories: string[];\n }\n | { type: \"REMOVE_ELEMENT\"; id: FlatCategoryStoreId };\n\n// Reducer\nfunction flatCategoryStoreReducer<T>(\n state: Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>>,\n action: Action<T>,\n): Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>> {\n switch (action.type) {\n case \"ADD_ELEMENT\": {\n const { value, id, categories } = action;\n const newElement: FlatCategoryStoreElement<T> = {\n id,\n value,\n categories: new Set(categories),\n };\n const newState = new Map(state);\n newState.set(id, newElement);\n return newState;\n }\n case \"REMOVE_ELEMENT\": {\n const newState = new Map(state);\n newState.delete(action.id);\n return newState;\n }\n default:\n return state;\n }\n}\n\nfunction setsHaveIntersection<T>(setA: Set<T>, setB: Set<T>): boolean {\n const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];\n\n for (let item of smallerSet) {\n if (largerSet.has(item)) {\n return true;\n }\n }\n\n return false;\n}\n"]}
@@ -1,2 +1,3 @@
1
- "use client";
1
+
2
+ //# sourceMappingURL=out.js.map
2
3
  //# sourceMappingURL=copilot-provider-props.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
1
+ {"version":3,"sources":[],"names":[],"mappings":""}