@langchain/classic 1.0.27 → 1.0.28

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 (298) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/agents/agent.cjs.map +1 -1
  3. package/dist/agents/agent.js.map +1 -1
  4. package/dist/agents/executor.cjs.map +1 -1
  5. package/dist/agents/executor.js.map +1 -1
  6. package/dist/agents/openai_functions/index.cjs.map +1 -1
  7. package/dist/agents/openai_functions/index.d.cts.map +1 -1
  8. package/dist/agents/openai_functions/index.d.ts.map +1 -1
  9. package/dist/agents/openai_functions/index.js.map +1 -1
  10. package/dist/agents/openai_tools/index.cjs.map +1 -1
  11. package/dist/agents/openai_tools/index.d.cts +2 -2
  12. package/dist/agents/openai_tools/index.d.cts.map +1 -1
  13. package/dist/agents/openai_tools/index.d.ts +2 -2
  14. package/dist/agents/openai_tools/index.d.ts.map +1 -1
  15. package/dist/agents/openai_tools/index.js.map +1 -1
  16. package/dist/agents/react/index.d.cts +2 -2
  17. package/dist/agents/react/index.d.cts.map +1 -1
  18. package/dist/agents/react/index.d.ts +2 -2
  19. package/dist/agents/react/index.d.ts.map +1 -1
  20. package/dist/agents/structured_chat/index.d.cts +2 -2
  21. package/dist/agents/structured_chat/index.d.cts.map +1 -1
  22. package/dist/agents/structured_chat/index.d.ts +2 -2
  23. package/dist/agents/structured_chat/index.d.ts.map +1 -1
  24. package/dist/agents/tool_calling/index.d.cts +2 -2
  25. package/dist/agents/tool_calling/index.d.cts.map +1 -1
  26. package/dist/agents/tool_calling/index.d.ts +2 -2
  27. package/dist/agents/tool_calling/index.d.ts.map +1 -1
  28. package/dist/agents/tool_calling/output_parser.cjs.map +1 -1
  29. package/dist/agents/tool_calling/output_parser.d.cts.map +1 -1
  30. package/dist/agents/tool_calling/output_parser.js.map +1 -1
  31. package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.d.cts +2 -2
  32. package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.d.cts.map +1 -1
  33. package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.d.ts +2 -2
  34. package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.d.ts.map +1 -1
  35. package/dist/agents/xml/index.d.cts.map +1 -1
  36. package/dist/agents/xml/index.d.ts.map +1 -1
  37. package/dist/cache/file_system.cjs.map +1 -1
  38. package/dist/cache/file_system.js.map +1 -1
  39. package/dist/chains/analyze_documents_chain.cjs.map +1 -1
  40. package/dist/chains/analyze_documents_chain.js.map +1 -1
  41. package/dist/chains/base.cjs.map +1 -1
  42. package/dist/chains/base.d.cts +2 -2
  43. package/dist/chains/base.d.cts.map +1 -1
  44. package/dist/chains/base.d.ts +2 -2
  45. package/dist/chains/base.d.ts.map +1 -1
  46. package/dist/chains/base.js.map +1 -1
  47. package/dist/chains/chat_vector_db_chain.cjs.map +1 -1
  48. package/dist/chains/chat_vector_db_chain.js.map +1 -1
  49. package/dist/chains/combine_docs_chain.d.cts +2 -2
  50. package/dist/chains/combine_docs_chain.d.cts.map +1 -1
  51. package/dist/chains/combine_docs_chain.d.ts +2 -2
  52. package/dist/chains/combine_docs_chain.d.ts.map +1 -1
  53. package/dist/chains/combine_documents/reduce.cjs.map +1 -1
  54. package/dist/chains/combine_documents/reduce.js.map +1 -1
  55. package/dist/chains/conversational_retrieval_chain.cjs.map +1 -1
  56. package/dist/chains/conversational_retrieval_chain.js.map +1 -1
  57. package/dist/chains/graph_qa/cypher.cjs.map +1 -1
  58. package/dist/chains/graph_qa/cypher.js.map +1 -1
  59. package/dist/chains/llm_chain.cjs.map +1 -1
  60. package/dist/chains/llm_chain.js.map +1 -1
  61. package/dist/chains/load.d.cts +1 -2
  62. package/dist/chains/load.d.cts.map +1 -1
  63. package/dist/chains/load.d.ts +1 -2
  64. package/dist/chains/load.d.ts.map +1 -1
  65. package/dist/chains/openai_functions/base.cjs.map +1 -1
  66. package/dist/chains/openai_functions/base.js.map +1 -1
  67. package/dist/chains/openai_functions/openapi.cjs.map +1 -1
  68. package/dist/chains/openai_functions/openapi.js.map +1 -1
  69. package/dist/chains/openai_moderation.cjs.map +1 -1
  70. package/dist/chains/openai_moderation.js.map +1 -1
  71. package/dist/chains/query_constructor/index.cjs.map +1 -1
  72. package/dist/chains/query_constructor/index.js.map +1 -1
  73. package/dist/chains/question_answering/load.d.cts +1 -2
  74. package/dist/chains/question_answering/load.d.cts.map +1 -1
  75. package/dist/chains/question_answering/load.d.ts +1 -2
  76. package/dist/chains/question_answering/load.d.ts.map +1 -1
  77. package/dist/chains/retrieval.cjs.map +1 -1
  78. package/dist/chains/retrieval.js.map +1 -1
  79. package/dist/chains/retrieval_qa.cjs.map +1 -1
  80. package/dist/chains/retrieval_qa.js.map +1 -1
  81. package/dist/chains/router/utils.cjs.map +1 -1
  82. package/dist/chains/router/utils.js.map +1 -1
  83. package/dist/chains/summarization/load.d.cts +1 -2
  84. package/dist/chains/summarization/load.d.cts.map +1 -1
  85. package/dist/chains/summarization/load.d.ts +1 -2
  86. package/dist/chains/summarization/load.d.ts.map +1 -1
  87. package/dist/chains/vector_db_qa.cjs.map +1 -1
  88. package/dist/chains/vector_db_qa.js.map +1 -1
  89. package/dist/chat_models/universal.cjs +8 -10
  90. package/dist/chat_models/universal.cjs.map +1 -1
  91. package/dist/chat_models/universal.d.cts +3 -5
  92. package/dist/chat_models/universal.d.cts.map +1 -1
  93. package/dist/chat_models/universal.d.ts +3 -5
  94. package/dist/chat_models/universal.d.ts.map +1 -1
  95. package/dist/chat_models/universal.js +8 -10
  96. package/dist/chat_models/universal.js.map +1 -1
  97. package/dist/document_loaders/fs/directory.d.cts.map +1 -1
  98. package/dist/document_loaders/fs/directory.d.ts.map +1 -1
  99. package/dist/document_loaders/fs/json.cjs.map +1 -1
  100. package/dist/document_loaders/fs/json.js.map +1 -1
  101. package/dist/document_transformers/openai_functions.d.cts.map +1 -1
  102. package/dist/evaluation/agents/index.d.cts +1 -0
  103. package/dist/evaluation/agents/trajectory.d.cts +2 -2
  104. package/dist/evaluation/agents/trajectory.d.cts.map +1 -1
  105. package/dist/evaluation/agents/trajectory.d.ts +2 -2
  106. package/dist/evaluation/agents/trajectory.d.ts.map +1 -1
  107. package/dist/evaluation/base.cjs.map +1 -1
  108. package/dist/evaluation/base.d.cts.map +1 -1
  109. package/dist/evaluation/base.js.map +1 -1
  110. package/dist/evaluation/comparison/index.d.cts +1 -0
  111. package/dist/evaluation/comparison/pairwise.cjs.map +1 -1
  112. package/dist/evaluation/comparison/pairwise.d.cts +3 -3
  113. package/dist/evaluation/comparison/pairwise.d.cts.map +1 -1
  114. package/dist/evaluation/comparison/pairwise.d.ts +3 -3
  115. package/dist/evaluation/comparison/pairwise.d.ts.map +1 -1
  116. package/dist/evaluation/comparison/pairwise.js.map +1 -1
  117. package/dist/evaluation/criteria/criteria.cjs.map +1 -1
  118. package/dist/evaluation/criteria/criteria.d.cts +3 -3
  119. package/dist/evaluation/criteria/criteria.d.cts.map +1 -1
  120. package/dist/evaluation/criteria/criteria.d.ts +3 -3
  121. package/dist/evaluation/criteria/criteria.d.ts.map +1 -1
  122. package/dist/evaluation/criteria/criteria.js.map +1 -1
  123. package/dist/evaluation/criteria/index.d.cts +1 -0
  124. package/dist/evaluation/embedding_distance/index.d.cts +1 -0
  125. package/dist/evaluation/loader.cjs.map +1 -1
  126. package/dist/evaluation/loader.d.cts.map +1 -1
  127. package/dist/evaluation/loader.js.map +1 -1
  128. package/dist/evaluation/qa/index.d.cts +1 -0
  129. package/dist/experimental/autogpt/prompt.d.cts +2 -2
  130. package/dist/experimental/autogpt/prompt.d.cts.map +1 -1
  131. package/dist/experimental/autogpt/prompt.d.ts +2 -2
  132. package/dist/experimental/autogpt/prompt.d.ts.map +1 -1
  133. package/dist/experimental/autogpt/prompt_generator.cjs.map +1 -1
  134. package/dist/experimental/autogpt/prompt_generator.js.map +1 -1
  135. package/dist/experimental/autogpt/schema.cjs.map +1 -1
  136. package/dist/experimental/autogpt/schema.js.map +1 -1
  137. package/dist/experimental/generative_agents/generative_agent_memory.cjs.map +1 -1
  138. package/dist/experimental/generative_agents/generative_agent_memory.js.map +1 -1
  139. package/dist/experimental/masking/parser.cjs.map +1 -1
  140. package/dist/experimental/masking/parser.js.map +1 -1
  141. package/dist/experimental/masking/regex_masking_transformer.cjs.map +1 -1
  142. package/dist/experimental/masking/regex_masking_transformer.js.map +1 -1
  143. package/dist/experimental/openai_assistant/index.cjs.map +1 -1
  144. package/dist/experimental/openai_assistant/index.d.cts +3 -3
  145. package/dist/experimental/openai_assistant/index.d.ts +3 -3
  146. package/dist/experimental/openai_assistant/index.js.map +1 -1
  147. package/dist/experimental/openai_files/index.d.cts +4 -4
  148. package/dist/experimental/openai_files/index.d.ts +4 -4
  149. package/dist/experimental/plan_and_execute/agent_executor.cjs.map +1 -1
  150. package/dist/experimental/plan_and_execute/agent_executor.js.map +1 -1
  151. package/dist/experimental/prompts/custom_format.cjs.map +1 -1
  152. package/dist/experimental/prompts/custom_format.js.map +1 -1
  153. package/dist/experimental/prompts/handlebars.cjs.map +1 -1
  154. package/dist/experimental/prompts/handlebars.d.cts +2 -2
  155. package/dist/experimental/prompts/handlebars.d.cts.map +1 -1
  156. package/dist/experimental/prompts/handlebars.d.ts +2 -2
  157. package/dist/experimental/prompts/handlebars.d.ts.map +1 -1
  158. package/dist/experimental/prompts/handlebars.js.map +1 -1
  159. package/dist/hub/base.cjs.map +1 -1
  160. package/dist/hub/base.d.cts +0 -1
  161. package/dist/hub/base.d.cts.map +1 -1
  162. package/dist/hub/base.d.ts +0 -1
  163. package/dist/hub/base.d.ts.map +1 -1
  164. package/dist/hub/base.js.map +1 -1
  165. package/dist/hub/index.cjs.map +1 -1
  166. package/dist/hub/index.js.map +1 -1
  167. package/dist/load/index.cjs.map +1 -1
  168. package/dist/load/index.js.map +1 -1
  169. package/dist/output_parsers/combining.cjs.map +1 -1
  170. package/dist/output_parsers/combining.js.map +1 -1
  171. package/dist/output_parsers/expression_type_handlers/base.cjs.map +1 -1
  172. package/dist/output_parsers/expression_type_handlers/base.d.cts.map +1 -1
  173. package/dist/output_parsers/expression_type_handlers/base.d.ts.map +1 -1
  174. package/dist/output_parsers/expression_type_handlers/base.js.map +1 -1
  175. package/dist/output_parsers/fix.cjs.map +1 -1
  176. package/dist/output_parsers/fix.js.map +1 -1
  177. package/dist/output_parsers/openai_functions.d.cts.map +1 -1
  178. package/dist/output_parsers/openai_functions.d.ts.map +1 -1
  179. package/dist/output_parsers/openai_tools.cjs.map +1 -1
  180. package/dist/output_parsers/openai_tools.js.map +1 -1
  181. package/dist/output_parsers/regex.cjs.map +1 -1
  182. package/dist/output_parsers/regex.js.map +1 -1
  183. package/dist/output_parsers/structured.d.cts +2 -2
  184. package/dist/output_parsers/structured.d.cts.map +1 -1
  185. package/dist/output_parsers/structured.d.ts +2 -2
  186. package/dist/output_parsers/structured.d.ts.map +1 -1
  187. package/dist/retrievers/document_compressors/index.cjs.map +1 -1
  188. package/dist/retrievers/document_compressors/index.js.map +1 -1
  189. package/dist/retrievers/matryoshka_retriever.cjs.map +1 -1
  190. package/dist/retrievers/matryoshka_retriever.d.cts +1 -1
  191. package/dist/retrievers/matryoshka_retriever.d.cts.map +1 -1
  192. package/dist/retrievers/matryoshka_retriever.d.ts +1 -1
  193. package/dist/retrievers/matryoshka_retriever.d.ts.map +1 -1
  194. package/dist/retrievers/matryoshka_retriever.js.map +1 -1
  195. package/dist/retrievers/multi_query.cjs.map +1 -1
  196. package/dist/retrievers/multi_query.js.map +1 -1
  197. package/dist/retrievers/parent_document.cjs.map +1 -1
  198. package/dist/retrievers/parent_document.js.map +1 -1
  199. package/dist/schema/prompt_template.d.cts +1 -2
  200. package/dist/schema/prompt_template.d.cts.map +1 -1
  201. package/dist/schema/prompt_template.d.ts +1 -2
  202. package/dist/schema/prompt_template.d.ts.map +1 -1
  203. package/dist/smith/config.cjs.map +1 -1
  204. package/dist/smith/config.d.cts +1 -1
  205. package/dist/smith/config.d.ts +1 -1
  206. package/dist/smith/config.d.ts.map +1 -1
  207. package/dist/smith/config.js.map +1 -1
  208. package/dist/smith/runner_utils.cjs.map +1 -1
  209. package/dist/smith/runner_utils.d.cts +1 -1
  210. package/dist/smith/runner_utils.d.cts.map +1 -1
  211. package/dist/smith/runner_utils.d.ts +1 -1
  212. package/dist/smith/runner_utils.d.ts.map +1 -1
  213. package/dist/smith/runner_utils.js.map +1 -1
  214. package/dist/sql_db.d.cts +2 -2
  215. package/dist/sql_db.d.cts.map +1 -1
  216. package/dist/sql_db.d.ts +2 -2
  217. package/dist/sql_db.d.ts.map +1 -1
  218. package/dist/storage/encoder_backed.cjs.map +1 -1
  219. package/dist/storage/encoder_backed.js.map +1 -1
  220. package/dist/storage/file_system.cjs.map +1 -1
  221. package/dist/storage/file_system.js.map +1 -1
  222. package/dist/stores/doc/in_memory.cjs.map +1 -1
  223. package/dist/stores/doc/in_memory.js.map +1 -1
  224. package/dist/tools/json.cjs.map +1 -1
  225. package/dist/tools/json.js.map +1 -1
  226. package/dist/tools/webbrowser.cjs.map +1 -1
  227. package/dist/tools/webbrowser.d.cts.map +1 -1
  228. package/dist/tools/webbrowser.d.ts.map +1 -1
  229. package/dist/tools/webbrowser.js.map +1 -1
  230. package/dist/util/document.d.cts +1 -1
  231. package/dist/util/document.d.cts.map +1 -1
  232. package/dist/util/document.d.ts +1 -1
  233. package/dist/util/document.d.ts.map +1 -1
  234. package/dist/util/is-network-error/index.cjs.map +1 -1
  235. package/dist/util/is-network-error/index.js.map +1 -1
  236. package/dist/util/load.cjs.map +1 -1
  237. package/dist/util/load.js.map +1 -1
  238. package/dist/util/openapi.cjs.map +1 -1
  239. package/dist/util/openapi.d.cts +32 -32
  240. package/dist/util/openapi.d.cts.map +1 -1
  241. package/dist/util/openapi.d.ts +32 -32
  242. package/dist/util/openapi.d.ts.map +1 -1
  243. package/dist/util/openapi.js.map +1 -1
  244. package/dist/util/p-retry/index.cjs.map +1 -1
  245. package/dist/util/p-retry/index.js.map +1 -1
  246. package/dist/vectorstores/memory.cjs.map +1 -1
  247. package/dist/vectorstores/memory.js.map +1 -1
  248. package/package.json +25 -48
  249. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/client.d.cts +0 -1494
  250. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/client.d.cts.map +0 -1
  251. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/client.d.ts +0 -1494
  252. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/client.d.ts.map +0 -1
  253. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/evaluation/_runner.d.cts +0 -1
  254. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/evaluation/_runner.d.ts +0 -1
  255. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/evaluation/evaluate_comparative.d.cts +0 -1
  256. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/evaluation/evaluate_comparative.d.ts +0 -1
  257. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/evaluation/evaluator.d.cts +0 -66
  258. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/evaluation/evaluator.d.cts.map +0 -1
  259. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/evaluation/evaluator.d.ts +0 -66
  260. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/evaluation/evaluator.d.ts.map +0 -1
  261. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/evaluation/index.d.cts +0 -1
  262. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/evaluation/index.d.ts +0 -1
  263. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/evaluation/string_evaluator.d.cts +0 -1
  264. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/evaluation/string_evaluator.d.ts +0 -1
  265. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/index.d.cts +0 -4
  266. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/index.d.ts +0 -4
  267. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/run_trees.d.cts +0 -145
  268. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/run_trees.d.cts.map +0 -1
  269. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/run_trees.d.ts +0 -145
  270. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/run_trees.d.ts.map +0 -1
  271. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/schemas.d.cts +0 -437
  272. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/schemas.d.cts.map +0 -1
  273. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/schemas.d.ts +0 -437
  274. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/schemas.d.ts.map +0 -1
  275. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/singletons/traceable.d.cts +0 -7
  276. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/singletons/traceable.d.cts.map +0 -1
  277. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/singletons/traceable.d.ts +0 -7
  278. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/singletons/traceable.d.ts.map +0 -1
  279. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/singletons/types.d.cts +0 -38
  280. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/singletons/types.d.cts.map +0 -1
  281. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/singletons/types.d.ts +0 -38
  282. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/singletons/types.d.ts.map +0 -1
  283. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/utils/async_caller.d.cts +0 -25
  284. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/utils/async_caller.d.cts.map +0 -1
  285. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/utils/async_caller.d.ts +0 -25
  286. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/utils/async_caller.d.ts.map +0 -1
  287. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/utils/p-queue.d.cts +0 -1
  288. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/utils/p-queue.d.ts +0 -1
  289. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/utils/prompt_cache/index.d.cts +0 -129
  290. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/utils/prompt_cache/index.d.cts.map +0 -1
  291. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/utils/prompt_cache/index.d.ts +0 -129
  292. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/dist/utils/prompt_cache/index.d.ts.map +0 -1
  293. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/evaluation.d.cts +0 -1
  294. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/evaluation.d.ts +0 -1
  295. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/singletons/traceable.d.cts +0 -2
  296. package/dist/node_modules/.pnpm/langsmith@0.5.9_@opentelemetry_api@1.9.0_openai@6.22.0_ws@8.20.0_bufferutil@4.1.0__zod@4.3.6_/node_modules/langsmith/singletons/traceable.d.ts +0 -2
  297. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.d.cts +0 -1
  298. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.d.ts +0 -1
@@ -10,8 +10,8 @@ declare class OpenAPISpec {
10
10
  getSchemasStrict(): Record<string, OpenAPIV3_1.SchemaObject>;
11
11
  getRequestBodiesStrict(): Record<string, OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.RequestBodyObject>;
12
12
  getPathStrict(path: string): Omit<OpenAPIV3.PathItemObject<{}>, "parameters" | "servers"> & {
13
- servers?: OpenAPIV3_1.ServerObject[] | undefined;
14
- parameters?: (OpenAPIV3.ParameterObject | OpenAPIV3_1.ReferenceObject)[] | undefined;
13
+ servers?: OpenAPIV3_1.ServerObject[];
14
+ parameters?: (OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.ParameterObject)[];
15
15
  } & {
16
16
  delete?: OpenAPIV3_1.OperationObject<{}> | undefined;
17
17
  get?: OpenAPIV3_1.OperationObject<{}> | undefined;
@@ -26,47 +26,47 @@ declare class OpenAPISpec {
26
26
  getRootReferencedParameter(ref: OpenAPIV3_1.ReferenceObject): OpenAPIV3_1.ParameterObject;
27
27
  getReferencedSchema(ref: OpenAPIV3_1.ReferenceObject): OpenAPIV3_1.SchemaObject;
28
28
  getSchema(schema: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.SchemaObject): OpenAPIV3_1.SchemaObject;
29
- getRootReferencedSchema(ref: OpenAPIV3_1.ReferenceObject): OpenAPIV3.ParameterObject;
29
+ getRootReferencedSchema(ref: OpenAPIV3_1.ReferenceObject): OpenAPIV3_1.ParameterObject;
30
30
  getReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject): OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.RequestBodyObject;
31
31
  getRootReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject): OpenAPIV3_1.RequestBodyObject;
32
32
  getMethodsForPath(path: string): OpenAPIV3.HttpMethods[];
33
33
  getParametersForPath(path: string): OpenAPIV3.ParameterObject[];
34
34
  getOperation(path: string, method: OpenAPIV3.HttpMethods): {
35
- tags?: string[] | undefined;
36
- summary?: string | undefined;
37
- description?: string | undefined;
38
- externalDocs?: OpenAPIV3.ExternalDocumentationObject | undefined;
39
- operationId?: string | undefined;
40
- parameters?: (OpenAPIV3.ParameterObject | OpenAPIV3.ReferenceObject)[] | undefined;
41
- requestBody?: OpenAPIV3.ReferenceObject | OpenAPIV3.RequestBodyObject | undefined;
35
+ tags?: string[];
36
+ summary?: string;
37
+ description?: string;
38
+ externalDocs?: OpenAPIV3.ExternalDocumentationObject;
39
+ operationId?: string;
40
+ parameters?: (OpenAPIV3.ReferenceObject | OpenAPIV3.ParameterObject)[];
41
+ requestBody?: OpenAPIV3.ReferenceObject | OpenAPIV3.RequestBodyObject;
42
42
  responses: OpenAPIV3.ResponsesObject;
43
43
  callbacks?: {
44
- [callback: string]: OpenAPIV3.CallbackObject | OpenAPIV3.ReferenceObject;
45
- } | undefined;
46
- deprecated?: boolean | undefined;
47
- security?: OpenAPIV3.SecurityRequirementObject[] | undefined;
48
- servers?: OpenAPIV3.ServerObject[] | undefined;
44
+ [callback: string]: OpenAPIV3.ReferenceObject | OpenAPIV3.CallbackObject;
45
+ };
46
+ deprecated?: boolean;
47
+ security?: OpenAPIV3.SecurityRequirementObject[];
48
+ servers?: OpenAPIV3.ServerObject[];
49
49
  } & Omit<{
50
- tags?: string[] | undefined;
51
- summary?: string | undefined;
52
- description?: string | undefined;
53
- externalDocs?: OpenAPIV3.ExternalDocumentationObject | undefined;
54
- operationId?: string | undefined;
55
- parameters?: (OpenAPIV3.ParameterObject | OpenAPIV3.ReferenceObject)[] | undefined;
56
- requestBody?: OpenAPIV3.ReferenceObject | OpenAPIV3.RequestBodyObject | undefined;
50
+ tags?: string[];
51
+ summary?: string;
52
+ description?: string;
53
+ externalDocs?: OpenAPIV3.ExternalDocumentationObject;
54
+ operationId?: string;
55
+ parameters?: (OpenAPIV3.ReferenceObject | OpenAPIV3.ParameterObject)[];
56
+ requestBody?: OpenAPIV3.ReferenceObject | OpenAPIV3.RequestBodyObject;
57
57
  responses: OpenAPIV3.ResponsesObject;
58
58
  callbacks?: {
59
- [callback: string]: OpenAPIV3.CallbackObject | OpenAPIV3.ReferenceObject;
60
- } | undefined;
61
- deprecated?: boolean | undefined;
62
- security?: OpenAPIV3.SecurityRequirementObject[] | undefined;
63
- servers?: OpenAPIV3.ServerObject[] | undefined;
59
+ [callback: string]: OpenAPIV3.ReferenceObject | OpenAPIV3.CallbackObject;
60
+ };
61
+ deprecated?: boolean;
62
+ security?: OpenAPIV3.SecurityRequirementObject[];
63
+ servers?: OpenAPIV3.ServerObject[];
64
64
  }, "callbacks" | "parameters" | "requestBody" | "responses" | "servers"> & {
65
- parameters?: (OpenAPIV3.ParameterObject | OpenAPIV3_1.ReferenceObject)[] | undefined;
66
- requestBody?: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.RequestBodyObject | undefined;
67
- responses?: OpenAPIV3_1.ResponsesObject | undefined;
68
- callbacks?: Record<string, OpenAPIV3_1.CallbackObject | OpenAPIV3_1.ReferenceObject> | undefined;
69
- servers?: OpenAPIV3_1.ServerObject[] | undefined;
65
+ parameters?: (OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.ParameterObject)[];
66
+ requestBody?: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.RequestBodyObject;
67
+ responses?: OpenAPIV3_1.ResponsesObject;
68
+ callbacks?: Record<string, OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.CallbackObject>;
69
+ servers?: OpenAPIV3_1.ServerObject[];
70
70
  };
71
71
  getParametersForOperation(operation: OpenAPIV3_1.OperationObject): OpenAPIV3.ParameterObject[];
72
72
  getRequestBodyForOperation(operation: OpenAPIV3_1.OperationObject): OpenAPIV3_1.RequestBodyObject;
@@ -1 +1 @@
1
- {"version":3,"file":"openapi.d.cts","names":[],"sources":["../../src/util/openapi.ts"],"mappings":";;;cAGa,WAAA;EACQ,QAAA,EAAU,WAAA,CAAY,QAAA;EAAzC,WAAA,CAAmB,QAAA,EAAU,WAAA,CAAY,QAAA;EAAA,IAErC,OAAA,CAAA;EAIJ,cAAA,CAAA,GAAc,WAAA,CAAA,WAAA;EAOd,mBAAA,CAAA,GAAmB,MAAA,SAAA,SAAA,CAAA,eAAA,GAAA,WAAA,CAAA,eAAA;EAOnB,gBAAA,CAAA,GAAgB,MAAA,SAAA,WAAA,CAAA,YAAA;EAOhB,sBAAA,CAAA,GAAsB,MAAA,SAAA,WAAA,CAAA,eAAA,GAAA,WAAA,CAAA,iBAAA;EAOtB,aAAA,CAAc,IAAA,WAAY,IAAA,CAAA,SAAA,CAAA,cAAA;;;;;;;;;;;;;EAQ1B,sBAAA,CAAuB,GAAA,EAAK,WAAA,CAAY,eAAA,GAAe,SAAA,CAAA,eAAA,GAAA,WAAA,CAAA,eAAA;EASvD,0BAA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;;;;;;;;;;;;;;;;;;;;;;;;;;EAQ7C,yBAAA,CAA0B,SAAA,EAAW,WAAA,CAAY,eAAA,GAAe,SAAA,CAAA,eAAA;EAchE,0BAAA,CACE,SAAA,EAAW,WAAA,CAAY,eAAA,GACtB,WAAA,CAAY,iBAAA;EAAA,OAUR,qBAAA,CACL,SAAA,EAAW,WAAA,CAAY,eAAA,EACvB,IAAA,UACA,MAAA,EAAQ,WAAA,CAAY,WAAA;EAAA,OAgBf,oBAAA,CAAqB,QAAA,EAAU,MAAA;EAAA,OAyB/B,UAAA,CAAW,QAAA,EAAU,MAAA,gBAAmB,WAAA;EAAA,OAKxC,UAAA,CAAW,SAAA,WAAiB,WAAA;EAAA,OAUtB,OAAA,CAAQ,GAAA,WAAW,OAAA,CAAA,WAAA;AAAA"}
@@ -10,8 +10,8 @@ declare class OpenAPISpec {
10
10
  getSchemasStrict(): Record<string, OpenAPIV3_1.SchemaObject>;
11
11
  getRequestBodiesStrict(): Record<string, OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.RequestBodyObject>;
12
12
  getPathStrict(path: string): Omit<OpenAPIV3.PathItemObject<{}>, "parameters" | "servers"> & {
13
- servers?: OpenAPIV3_1.ServerObject[] | undefined;
14
- parameters?: (OpenAPIV3.ParameterObject | OpenAPIV3_1.ReferenceObject)[] | undefined;
13
+ servers?: OpenAPIV3_1.ServerObject[];
14
+ parameters?: (OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.ParameterObject)[];
15
15
  } & {
16
16
  delete?: OpenAPIV3_1.OperationObject<{}> | undefined;
17
17
  get?: OpenAPIV3_1.OperationObject<{}> | undefined;
@@ -26,47 +26,47 @@ declare class OpenAPISpec {
26
26
  getRootReferencedParameter(ref: OpenAPIV3_1.ReferenceObject): OpenAPIV3_1.ParameterObject;
27
27
  getReferencedSchema(ref: OpenAPIV3_1.ReferenceObject): OpenAPIV3_1.SchemaObject;
28
28
  getSchema(schema: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.SchemaObject): OpenAPIV3_1.SchemaObject;
29
- getRootReferencedSchema(ref: OpenAPIV3_1.ReferenceObject): OpenAPIV3.ParameterObject;
29
+ getRootReferencedSchema(ref: OpenAPIV3_1.ReferenceObject): OpenAPIV3_1.ParameterObject;
30
30
  getReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject): OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.RequestBodyObject;
31
31
  getRootReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject): OpenAPIV3_1.RequestBodyObject;
32
32
  getMethodsForPath(path: string): OpenAPIV3.HttpMethods[];
33
33
  getParametersForPath(path: string): OpenAPIV3.ParameterObject[];
34
34
  getOperation(path: string, method: OpenAPIV3.HttpMethods): {
35
- tags?: string[] | undefined;
36
- summary?: string | undefined;
37
- description?: string | undefined;
38
- externalDocs?: OpenAPIV3.ExternalDocumentationObject | undefined;
39
- operationId?: string | undefined;
40
- parameters?: (OpenAPIV3.ParameterObject | OpenAPIV3.ReferenceObject)[] | undefined;
41
- requestBody?: OpenAPIV3.ReferenceObject | OpenAPIV3.RequestBodyObject | undefined;
35
+ tags?: string[];
36
+ summary?: string;
37
+ description?: string;
38
+ externalDocs?: OpenAPIV3.ExternalDocumentationObject;
39
+ operationId?: string;
40
+ parameters?: (OpenAPIV3.ReferenceObject | OpenAPIV3.ParameterObject)[];
41
+ requestBody?: OpenAPIV3.ReferenceObject | OpenAPIV3.RequestBodyObject;
42
42
  responses: OpenAPIV3.ResponsesObject;
43
43
  callbacks?: {
44
- [callback: string]: OpenAPIV3.CallbackObject | OpenAPIV3.ReferenceObject;
45
- } | undefined;
46
- deprecated?: boolean | undefined;
47
- security?: OpenAPIV3.SecurityRequirementObject[] | undefined;
48
- servers?: OpenAPIV3.ServerObject[] | undefined;
44
+ [callback: string]: OpenAPIV3.ReferenceObject | OpenAPIV3.CallbackObject;
45
+ };
46
+ deprecated?: boolean;
47
+ security?: OpenAPIV3.SecurityRequirementObject[];
48
+ servers?: OpenAPIV3.ServerObject[];
49
49
  } & Omit<{
50
- tags?: string[] | undefined;
51
- summary?: string | undefined;
52
- description?: string | undefined;
53
- externalDocs?: OpenAPIV3.ExternalDocumentationObject | undefined;
54
- operationId?: string | undefined;
55
- parameters?: (OpenAPIV3.ParameterObject | OpenAPIV3.ReferenceObject)[] | undefined;
56
- requestBody?: OpenAPIV3.ReferenceObject | OpenAPIV3.RequestBodyObject | undefined;
50
+ tags?: string[];
51
+ summary?: string;
52
+ description?: string;
53
+ externalDocs?: OpenAPIV3.ExternalDocumentationObject;
54
+ operationId?: string;
55
+ parameters?: (OpenAPIV3.ReferenceObject | OpenAPIV3.ParameterObject)[];
56
+ requestBody?: OpenAPIV3.ReferenceObject | OpenAPIV3.RequestBodyObject;
57
57
  responses: OpenAPIV3.ResponsesObject;
58
58
  callbacks?: {
59
- [callback: string]: OpenAPIV3.CallbackObject | OpenAPIV3.ReferenceObject;
60
- } | undefined;
61
- deprecated?: boolean | undefined;
62
- security?: OpenAPIV3.SecurityRequirementObject[] | undefined;
63
- servers?: OpenAPIV3.ServerObject[] | undefined;
59
+ [callback: string]: OpenAPIV3.ReferenceObject | OpenAPIV3.CallbackObject;
60
+ };
61
+ deprecated?: boolean;
62
+ security?: OpenAPIV3.SecurityRequirementObject[];
63
+ servers?: OpenAPIV3.ServerObject[];
64
64
  }, "callbacks" | "parameters" | "requestBody" | "responses" | "servers"> & {
65
- parameters?: (OpenAPIV3.ParameterObject | OpenAPIV3_1.ReferenceObject)[] | undefined;
66
- requestBody?: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.RequestBodyObject | undefined;
67
- responses?: OpenAPIV3_1.ResponsesObject | undefined;
68
- callbacks?: Record<string, OpenAPIV3_1.CallbackObject | OpenAPIV3_1.ReferenceObject> | undefined;
69
- servers?: OpenAPIV3_1.ServerObject[] | undefined;
65
+ parameters?: (OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.ParameterObject)[];
66
+ requestBody?: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.RequestBodyObject;
67
+ responses?: OpenAPIV3_1.ResponsesObject;
68
+ callbacks?: Record<string, OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.CallbackObject>;
69
+ servers?: OpenAPIV3_1.ServerObject[];
70
70
  };
71
71
  getParametersForOperation(operation: OpenAPIV3_1.OperationObject): OpenAPIV3.ParameterObject[];
72
72
  getRequestBodyForOperation(operation: OpenAPIV3_1.OperationObject): OpenAPIV3_1.RequestBodyObject;
@@ -1 +1 @@
1
- {"version":3,"file":"openapi.d.ts","names":[],"sources":["../../src/util/openapi.ts"],"mappings":";;;cAGa,WAAA;EACQ,QAAA,EAAU,WAAA,CAAY,QAAA;EAAzC,WAAA,CAAmB,QAAA,EAAU,WAAA,CAAY,QAAA;EAAA,IAErC,OAAA,CAAA;EAIJ,cAAA,CAAA,GAAc,WAAA,CAAA,WAAA;EAOd,mBAAA,CAAA,GAAmB,MAAA,SAAA,SAAA,CAAA,eAAA,GAAA,WAAA,CAAA,eAAA;EAOnB,gBAAA,CAAA,GAAgB,MAAA,SAAA,WAAA,CAAA,YAAA;EAOhB,sBAAA,CAAA,GAAsB,MAAA,SAAA,WAAA,CAAA,eAAA,GAAA,WAAA,CAAA,iBAAA;EAOtB,aAAA,CAAc,IAAA,WAAY,IAAA,CAAA,SAAA,CAAA,cAAA;;;;;;;;;;;;;EAQ1B,sBAAA,CAAuB,GAAA,EAAK,WAAA,CAAY,eAAA,GAAe,SAAA,CAAA,eAAA,GAAA,WAAA,CAAA,eAAA;EASvD,0BAAA,CACE,GAAA,EAAK,WAAA,CAAY,eAAA,GAChB,WAAA,CAAY,eAAA;EAUf,mBAAA,CACE,GAAA,EAAK,WAAA,CAAY,eAAA,GAChB,WAAA,CAAY,YAAA;EAUf,SAAA,CACE,MAAA,EAAQ,WAAA,CAAY,eAAA,GAAkB,WAAA,CAAY,YAAA,GACjD,WAAA,CAAY,YAAA;EAOf,uBAAA,CAAwB,GAAA,EAAK,WAAA,CAAY,eAAA,GA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EAAA,OAgBf,oBAAA,CAAqB,QAAA,EAAU,MAAA;EAAA,OAyB/B,UAAA,CAAW,QAAA,EAAU,MAAA,gBAAmB,WAAA;EAAA,OAKxC,UAAA,CAAW,SAAA,WAAiB,WAAA;EAAA,OAUtB,OAAA,CAAQ,GAAA,WAAW,OAAA,CAAA,WAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"openapi.js","names":[],"sources":["../../src/util/openapi.ts"],"sourcesContent":["import * as yaml from \"js-yaml\";\nimport { OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\n\nexport class OpenAPISpec {\n constructor(public document: OpenAPIV3_1.Document) {}\n\n get baseUrl() {\n return this.document.servers ? this.document.servers[0].url : undefined;\n }\n\n getPathsStrict() {\n if (!this.document.paths) {\n throw new Error(\"No paths found in spec\");\n }\n return this.document.paths;\n }\n\n getParametersStrict() {\n if (!this.document.components?.parameters) {\n throw new Error(\"No parameters found in spec\");\n }\n return this.document.components.parameters;\n }\n\n getSchemasStrict() {\n if (!this.document.components?.schemas) {\n throw new Error(\"No schemas found in spec.\");\n }\n return this.document.components.schemas;\n }\n\n getRequestBodiesStrict() {\n if (!this.document.components?.requestBodies) {\n throw new Error(\"No request body found in spec.\");\n }\n return this.document.components.requestBodies;\n }\n\n getPathStrict(path: string) {\n const pathItem = this.getPathsStrict()[path];\n if (pathItem === undefined) {\n throw new Error(`No path found for \"${path}\".`);\n }\n return pathItem;\n }\n\n getReferencedParameter(ref: OpenAPIV3_1.ReferenceObject) {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n if (this.getParametersStrict()[refName] === undefined) {\n throw new Error(`No parameter found for \"${refName}\".`);\n }\n return this.getParametersStrict()[refName];\n }\n\n getRootReferencedParameter(\n ref: OpenAPIV3_1.ReferenceObject\n ): OpenAPIV3_1.ParameterObject {\n let parameter = this.getReferencedParameter(ref);\n while ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n parameter = this.getReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n }\n\n getReferencedSchema(\n ref: OpenAPIV3_1.ReferenceObject\n ): OpenAPIV3_1.SchemaObject {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n const schema = this.getSchemasStrict()[refName];\n if (schema === undefined) {\n throw new Error(`No schema found for \"${refName}\".`);\n }\n return schema;\n }\n\n getSchema(\n schema: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.SchemaObject\n ): OpenAPIV3_1.SchemaObject {\n if ((schema as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getReferencedSchema(schema as OpenAPIV3_1.ReferenceObject);\n }\n return schema;\n }\n\n getRootReferencedSchema(ref: OpenAPIV3_1.ReferenceObject) {\n let schema = this.getReferencedSchema(ref);\n while ((schema as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n schema = this.getReferencedSchema(schema as OpenAPIV3_1.ReferenceObject);\n }\n return schema as OpenAPIV3_1.ParameterObject;\n }\n\n getReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject) {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n const requestBodies = this.getRequestBodiesStrict();\n if (requestBodies[refName] === undefined) {\n throw new Error(`No request body found for \"${refName}\"`);\n }\n return requestBodies[refName];\n }\n\n getRootReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject) {\n let requestBody = this.getReferencedRequestBody(ref);\n while ((requestBody as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n requestBody = this.getReferencedRequestBody(\n requestBody as OpenAPIV3_1.ReferenceObject\n );\n }\n return requestBody as OpenAPIV3_1.RequestBodyObject;\n }\n\n getMethodsForPath(path: string): OpenAPIV3.HttpMethods[] {\n const pathItem = this.getPathStrict(path);\n // This is an enum in the underlying package.\n // Werestate here to allow \"import type\" above and not cause warnings in certain envs.\n const possibleMethods = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"options\",\n \"head\",\n \"patch\",\n \"trace\",\n ];\n return possibleMethods.filter(\n (possibleMethod) =>\n pathItem[possibleMethod as OpenAPIV3.HttpMethods] !== undefined\n ) as OpenAPIV3.HttpMethods[];\n }\n\n getParametersForPath(path: string) {\n const pathItem = this.getPathStrict(path);\n if (pathItem.parameters === undefined) {\n return [];\n }\n return pathItem.parameters.map((parameter) => {\n if ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getRootReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n });\n }\n\n getOperation(path: string, method: OpenAPIV3.HttpMethods) {\n const pathItem = this.getPathStrict(path);\n if (pathItem[method] === undefined) {\n throw new Error(`No ${method} method found for \"path\".`);\n }\n return pathItem[method];\n }\n\n getParametersForOperation(operation: OpenAPIV3_1.OperationObject) {\n if (operation.parameters === undefined) {\n return [];\n }\n return operation.parameters.map((parameter) => {\n if ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getRootReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n });\n }\n\n getRequestBodyForOperation(\n operation: OpenAPIV3_1.OperationObject\n ): OpenAPIV3_1.RequestBodyObject {\n const { requestBody } = operation;\n if ((requestBody as OpenAPIV3_1.ReferenceObject)?.$ref !== undefined) {\n return this.getRootReferencedRequestBody(\n requestBody as OpenAPIV3_1.ReferenceObject\n );\n }\n return requestBody as OpenAPIV3_1.RequestBodyObject;\n }\n\n static getCleanedOperationId(\n operation: OpenAPIV3_1.OperationObject,\n path: string,\n method: OpenAPIV3_1.HttpMethods\n ) {\n let { operationId } = operation;\n if (operationId === undefined) {\n const updatedPath = path.replaceAll(/[^a-zA-Z0-9]/g, \"_\");\n operationId = `${\n updatedPath.startsWith(\"/\") ? updatedPath.slice(1) : updatedPath\n }_${method}`;\n }\n return operationId\n .replaceAll(/-/g, \"_\")\n .replaceAll(/\\./g, \"_\")\n .replaceAll(/\\//g, \"_\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static alertUnsupportedSpec(document: Record<string, any>) {\n const warningMessage =\n \"This may result in degraded performance. Convert your OpenAPI spec to 3.1.0 for better support.\";\n const swaggerVersion = document.swagger;\n const openAPIVersion = document.openapi;\n if (openAPIVersion !== undefined && openAPIVersion !== \"3.1.0\") {\n console.warn(\n `Attempting to load an OpenAPI ${openAPIVersion} spec. ${warningMessage}`\n );\n } else if (swaggerVersion !== undefined) {\n console.warn(\n `Attempting to load a Swagger ${swaggerVersion} spec. ${warningMessage}`\n );\n } else {\n throw new Error(\n `Attempting to load an unsupported spec:\\n\\n${JSON.stringify(\n document,\n null,\n 2\n )}.`\n );\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static fromObject(document: Record<string, any>) {\n OpenAPISpec.alertUnsupportedSpec(document);\n return new OpenAPISpec(document as OpenAPIV3_1.Document);\n }\n\n static fromString(rawString: string) {\n let document;\n try {\n document = JSON.parse(rawString);\n } catch {\n document = yaml.load(rawString);\n }\n return OpenAPISpec.fromObject(document);\n }\n\n static async fromURL(url: string) {\n const response = await fetch(url);\n const rawDocument = await response.text();\n return OpenAPISpec.fromString(rawDocument);\n }\n}\n"],"mappings":";;AAGA,IAAa,cAAb,MAAa,YAAY;CACvB,YAAY,UAAuC;AAAhC,OAAA,WAAA;;CAEnB,IAAI,UAAU;AACZ,SAAO,KAAK,SAAS,UAAU,KAAK,SAAS,QAAQ,GAAG,MAAM,KAAA;;CAGhE,iBAAiB;AACf,MAAI,CAAC,KAAK,SAAS,MACjB,OAAM,IAAI,MAAM,yBAAyB;AAE3C,SAAO,KAAK,SAAS;;CAGvB,sBAAsB;AACpB,MAAI,CAAC,KAAK,SAAS,YAAY,WAC7B,OAAM,IAAI,MAAM,8BAA8B;AAEhD,SAAO,KAAK,SAAS,WAAW;;CAGlC,mBAAmB;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gB;AACtB,MAAI,gBAAgB,KAAA,GAAW;GAC7B,MAAM,cAAc,KAAK,WAAW,iBAAiB,IAAI;AACzD,iBAAc,GACZ,YAAY,WAAW,IAAI,GAAG,YAAY,MAAM,EAAE,GAAG,YACtD,GAAG;;AAEN,SAAO,YACJ,WAAW,MAAM,IAAI,CACrB,WAAW,OAAO,IAAI,CACtB,WAAW,OAAO,IAAI;;CAI3B,OAAO,qBAAqB,UAA+B;EACzD,MAAM,iBACJ;EACF,MAAM,iBAAiB,SAAS;EAChC,MAAM,iBAAiB,SAAS;AAChC,MAAI,mBAAmB,KAAA,KAAa,mBAAmB,QACrD,SAAQ,KACN,iCAAiC,eAAe,SAAS,iBAC1D;WACQ,mBAAmB,KAAA,EAC5B,SAAQ,KACN,gCAAgC,eAAe,SAAS,iBACzD;MAED,OAAM,IAAI,MACR,8CAA8C,KAAK,UACjD,UACA,MACA,EACD,CAAC,GACH;;CAKL,OAAO,WAAW,UAA+B;AAC/C,cAAY,qBAAqB,SAAS;AAC1C,SAAO,IAAI,YAAY,SAAiC;;CAG1D,OAAO,WAAW,WAAmB;EACnC,IAAI;AACJ,MAAI;AACF,cAAW,KAAK,MAAM,UAAU;UAC1B;AACN,cAAW,KAAK,KAAK,UAAU;;AAEjC,SAAO,YAAY,WAAW,SAAS;;CAGzC,aAAa,QAAQ,KAAa;EAEhC,MAAM,cAAc,OADH,MAAM,MAAM,IAAI,EACE,MAAM;AACzC,SAAO,YAAY,WAAW,YAAY"}
1
+ {"version":3,"file":"openapi.js","names":[],"sources":["../../src/util/openapi.ts"],"sourcesContent":["import * as yaml from \"js-yaml\";\nimport { OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\n\nexport class OpenAPISpec {\n constructor(public document: OpenAPIV3_1.Document) {}\n\n get baseUrl() {\n return this.document.servers ? this.document.servers[0].url : undefined;\n }\n\n getPathsStrict() {\n if (!this.document.paths) {\n throw new Error(\"No paths found in spec\");\n }\n return this.document.paths;\n }\n\n getParametersStrict() {\n if (!this.document.components?.parameters) {\n throw new Error(\"No parameters found in spec\");\n }\n return this.document.components.parameters;\n }\n\n getSchemasStrict() {\n if (!this.document.components?.schemas) {\n throw new Error(\"No schemas found in spec.\");\n }\n return this.document.components.schemas;\n }\n\n getRequestBodiesStrict() {\n if (!this.document.components?.requestBodies) {\n throw new Error(\"No request body found in spec.\");\n }\n return this.document.components.requestBodies;\n }\n\n getPathStrict(path: string) {\n const pathItem = this.getPathsStrict()[path];\n if (pathItem === undefined) {\n throw new Error(`No path found for \"${path}\".`);\n }\n return pathItem;\n }\n\n getReferencedParameter(ref: OpenAPIV3_1.ReferenceObject) {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n if (this.getParametersStrict()[refName] === undefined) {\n throw new Error(`No parameter found for \"${refName}\".`);\n }\n return this.getParametersStrict()[refName];\n }\n\n getRootReferencedParameter(\n ref: OpenAPIV3_1.ReferenceObject\n ): OpenAPIV3_1.ParameterObject {\n let parameter = this.getReferencedParameter(ref);\n while ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n parameter = this.getReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n }\n\n getReferencedSchema(\n ref: OpenAPIV3_1.ReferenceObject\n ): OpenAPIV3_1.SchemaObject {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n const schema = this.getSchemasStrict()[refName];\n if (schema === undefined) {\n throw new Error(`No schema found for \"${refName}\".`);\n }\n return schema;\n }\n\n getSchema(\n schema: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.SchemaObject\n ): OpenAPIV3_1.SchemaObject {\n if ((schema as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getReferencedSchema(schema as OpenAPIV3_1.ReferenceObject);\n }\n return schema;\n }\n\n getRootReferencedSchema(ref: OpenAPIV3_1.ReferenceObject) {\n let schema = this.getReferencedSchema(ref);\n while ((schema as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n schema = this.getReferencedSchema(schema as OpenAPIV3_1.ReferenceObject);\n }\n return schema as OpenAPIV3_1.ParameterObject;\n }\n\n getReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject) {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n const requestBodies = this.getRequestBodiesStrict();\n if (requestBodies[refName] === undefined) {\n throw new Error(`No request body found for \"${refName}\"`);\n }\n return requestBodies[refName];\n }\n\n getRootReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject) {\n let requestBody = this.getReferencedRequestBody(ref);\n while ((requestBody as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n requestBody = this.getReferencedRequestBody(\n requestBody as OpenAPIV3_1.ReferenceObject\n );\n }\n return requestBody as OpenAPIV3_1.RequestBodyObject;\n }\n\n getMethodsForPath(path: string): OpenAPIV3.HttpMethods[] {\n const pathItem = this.getPathStrict(path);\n // This is an enum in the underlying package.\n // Werestate here to allow \"import type\" above and not cause warnings in certain envs.\n const possibleMethods = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"options\",\n \"head\",\n \"patch\",\n \"trace\",\n ];\n return possibleMethods.filter(\n (possibleMethod) =>\n pathItem[possibleMethod as OpenAPIV3.HttpMethods] !== undefined\n ) as OpenAPIV3.HttpMethods[];\n }\n\n getParametersForPath(path: string) {\n const pathItem = this.getPathStrict(path);\n if (pathItem.parameters === undefined) {\n return [];\n }\n return pathItem.parameters.map((parameter) => {\n if ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getRootReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n });\n }\n\n getOperation(path: string, method: OpenAPIV3.HttpMethods) {\n const pathItem = this.getPathStrict(path);\n if (pathItem[method] === undefined) {\n throw new Error(`No ${method} method found for \"path\".`);\n }\n return pathItem[method];\n }\n\n getParametersForOperation(operation: OpenAPIV3_1.OperationObject) {\n if (operation.parameters === undefined) {\n return [];\n }\n return operation.parameters.map((parameter) => {\n if ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getRootReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n });\n }\n\n getRequestBodyForOperation(\n operation: OpenAPIV3_1.OperationObject\n ): OpenAPIV3_1.RequestBodyObject {\n const { requestBody } = operation;\n if ((requestBody as OpenAPIV3_1.ReferenceObject)?.$ref !== undefined) {\n return this.getRootReferencedRequestBody(\n requestBody as OpenAPIV3_1.ReferenceObject\n );\n }\n return requestBody as OpenAPIV3_1.RequestBodyObject;\n }\n\n static getCleanedOperationId(\n operation: OpenAPIV3_1.OperationObject,\n path: string,\n method: OpenAPIV3_1.HttpMethods\n ) {\n let { operationId } = operation;\n if (operationId === undefined) {\n const updatedPath = path.replaceAll(/[^a-zA-Z0-9]/g, \"_\");\n operationId = `${\n updatedPath.startsWith(\"/\") ? updatedPath.slice(1) : updatedPath\n }_${method}`;\n }\n return operationId\n .replaceAll(/-/g, \"_\")\n .replaceAll(/\\./g, \"_\")\n .replaceAll(/\\//g, \"_\");\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n static alertUnsupportedSpec(document: Record<string, any>) {\n const warningMessage =\n \"This may result in degraded performance. Convert your OpenAPI spec to 3.1.0 for better support.\";\n const swaggerVersion = document.swagger;\n const openAPIVersion = document.openapi;\n if (openAPIVersion !== undefined && openAPIVersion !== \"3.1.0\") {\n console.warn(\n `Attempting to load an OpenAPI ${openAPIVersion} spec. ${warningMessage}`\n );\n } else if (swaggerVersion !== undefined) {\n console.warn(\n `Attempting to load a Swagger ${swaggerVersion} spec. ${warningMessage}`\n );\n } else {\n throw new Error(\n `Attempting to load an unsupported spec:\\n\\n${JSON.stringify(\n document,\n null,\n 2\n )}.`\n );\n }\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n static fromObject(document: Record<string, any>) {\n OpenAPISpec.alertUnsupportedSpec(document);\n return new OpenAPISpec(document as OpenAPIV3_1.Document);\n }\n\n static fromString(rawString: string) {\n let document;\n try {\n document = JSON.parse(rawString);\n } catch {\n document = yaml.load(rawString);\n }\n return OpenAPISpec.fromObject(document);\n }\n\n static async fromURL(url: string) {\n const response = await fetch(url);\n const rawDocument = await response.text();\n return OpenAPISpec.fromString(rawDocument);\n }\n}\n"],"mappings":";;AAGA,IAAa,cAAb,MAAa,YAAY;CACvB,YAAY,UAAuC;AAAhC,OAAA,WAAA;;CAEnB,IAAI,UAAU;AACZ,SAAO,KAAK,SAAS,UAAU,KAAK,SAAS,QAAQ,GAAG,MAAM,KAAA;;CAGhE,iBAAiB;AACf,MAAI,CAAC,KAAK,SAAS,MACjB,OAAM,IAAI,MAAM,yBAAyB;AAE3C,SAAO,KAAK,SAAS;;CAGvB,sBAAsB;AACpB,MAAI,CAAC,KAAK,SAAS,YAAY,WAC7B,OAAM,IAAI,MAAM,8BAA8B;AAEhD,SAAO,KAAK,SAAS,WAAW;;CAGlC,mBAAmB;AACjB,MAAI,CAAC,KAAK,SAAS,YAAY,QAC7B,OAAM,IAAI,MAAM,4BAA4B;AAE9C,SAAO,KAAK,SAAS,WAAW;;CAGlC,yBAAyB;AACvB,MAAI,CAAC,KAAK,SAAS,YAAY,cAC7B,OAAM,IAAI,MAAM,iCAAiC;AAEnD,SAAO,KAAK,SAAS,WAAW;;CAGlC,cAAc,MAAc;EAC1B,MAAM,WAAW,KAAK,gBAAgB,CAAC;AACvC,MAAI,aAAa,KAAA,EACf,OAAM,IAAI,MAAM,sBAAsB,KAAK,IAAI;AAEjD,SAAO;;CAGT,uBAAuB,KAAkC;EACvD,MAAM,gBAAgB,IAAI,KAAK,MAAM,IAAI;EACzC,MAAM,UAAU,cAAc,cAAc,SAAS;AACrD,MAAI,KAAK,qBAAqB,CAAC,aAAa,KAAA,EAC1C,OAAM,IAAI,MAAM,2BAA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,UACjD,UACA,MACA,EACD,CAAC,GACH;;CAKL,OAAO,WAAW,UAA+B;AAC/C,cAAY,qBAAqB,SAAS;AAC1C,SAAO,IAAI,YAAY,SAAiC;;CAG1D,OAAO,WAAW,WAAmB;EACnC,IAAI;AACJ,MAAI;AACF,cAAW,KAAK,MAAM,UAAU;UAC1B;AACN,cAAW,KAAK,KAAK,UAAU;;AAEjC,SAAO,YAAY,WAAW,SAAS;;CAGzC,aAAa,QAAQ,KAAa;EAEhC,MAAM,cAAc,OADH,MAAM,MAAM,IAAI,EACE,MAAM;AACzC,SAAO,YAAY,WAAW,YAAY"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["isNetworkError"],"sources":["../../../src/util/p-retry/index.js"],"sourcesContent":["/* eslint-disable */\nimport isNetworkError from \"../is-network-error/index.js\";\n\nfunction validateRetries(retries) {\n if (typeof retries === \"number\") {\n if (retries < 0) {\n throw new TypeError(\"Expected `retries` to be a non-negative number.\");\n }\n\n if (Number.isNaN(retries)) {\n throw new TypeError(\n \"Expected `retries` to be a valid number or Infinity, got NaN.\"\n );\n }\n } else if (retries !== undefined) {\n throw new TypeError(\"Expected `retries` to be a number or Infinity.\");\n }\n}\n\nfunction validateNumberOption(\n name,\n value,\n { min = 0, allowInfinity = false } = {}\n) {\n if (value === undefined) {\n return;\n }\n\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n throw new TypeError(\n `Expected \\`${name}\\` to be a number${\n allowInfinity ? \" or Infinity\" : \"\"\n }.`\n );\n }\n\n if (!allowInfinity && !Number.isFinite(value)) {\n throw new TypeError(`Expected \\`${name}\\` to be a finite number.`);\n }\n\n if (value < min) {\n throw new TypeError(`Expected \\`${name}\\` to be \\u2265 ${min}.`);\n }\n}\n\nexport class AbortError extends Error {\n constructor(message) {\n super();\n\n if (message instanceof Error) {\n this.originalError = message;\n ({ message } = message);\n } else {\n this.originalError = new Error(message);\n this.originalError.stack = this.stack;\n }\n\n this.name = \"AbortError\";\n this.message = message;\n }\n}\n\nfunction calculateDelay(retriesConsumed, options) {\n const attempt = Math.max(1, retriesConsumed + 1);\n const random = options.randomize ? Math.random() + 1 : 1;\n\n let timeout = Math.round(\n random * options.minTimeout * options.factor ** (attempt - 1)\n );\n timeout = Math.min(timeout, options.maxTimeout);\n\n return timeout;\n}\n\nfunction calculateRemainingTime(start, max) {\n if (!Number.isFinite(max)) {\n return max;\n }\n\n return max - (performance.now() - start);\n}\n\nasync function onAttemptFailure({\n error,\n attemptNumber,\n retriesConsumed,\n startTime,\n options,\n}) {\n const normalizedError =\n error instanceof Error\n ? error\n : new TypeError(\n `Non-error was thrown: \"${error}\". You should only throw errors.`\n );\n\n if (normalizedError instanceof AbortError) {\n throw normalizedError.originalError;\n }\n\n const retriesLeft = Number.isFinite(options.retries)\n ? Math.max(0, options.retries - retriesConsumed)\n : options.retries;\n\n const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;\n\n const context = Object.freeze({\n error: normalizedError,\n attemptNumber,\n retriesLeft,\n retriesConsumed,\n });\n\n await options.onFailedAttempt(context);\n\n if (calculateRemainingTime(startTime, maxRetryTime) <= 0) {\n throw normalizedError;\n }\n\n const consumeRetry = await options.shouldConsumeRetry(context);\n\n const remainingTime = calculateRemainingTime(startTime, maxRetryTime);\n\n if (remainingTime <= 0 || retriesLeft <= 0) {\n throw normalizedError;\n }\n\n if (\n normalizedError instanceof TypeError &&\n !isNetworkError(normalizedError)\n ) {\n if (consumeRetry) {\n throw normalizedError;\n }\n\n options.signal?.throwIfAborted();\n return false;\n }\n\n if (!(await options.shouldRetry(context))) {\n throw normalizedError;\n }\n\n if (!consumeRetry) {\n options.signal?.throwIfAborted();\n return false;\n }\n\n const delayTime = calculateDelay(retriesConsumed, options);\n const finalDelay = Math.min(delayTime, remainingTime);\n\n if (finalDelay > 0) {\n await new Promise((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timeoutToken);\n options.signal?.removeEventListener(\"abort\", onAbort);\n reject(options.signal.reason);\n };\n\n const timeoutToken = setTimeout(() => {\n options.signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, finalDelay);\n\n if (options.unref) {\n timeoutToken.unref?.();\n }\n\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n options.signal?.throwIfAborted();\n\n return true;\n}\n\nexport default async function pRetry(input, options = {}) {\n options = { ...options };\n\n validateRetries(options.retries);\n\n if (Object.hasOwn(options, \"forever\")) {\n throw new Error(\n \"The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.\"\n );\n }\n\n options.retries ??= 10;\n options.factor ??= 2;\n options.minTimeout ??= 1000;\n options.maxTimeout ??= Number.POSITIVE_INFINITY;\n options.maxRetryTime ??= Number.POSITIVE_INFINITY;\n options.randomize ??= false;\n options.onFailedAttempt ??= () => {};\n options.shouldRetry ??= () => true;\n options.shouldConsumeRetry ??= () => true;\n\n // Validate numeric options and normalize edge cases\n validateNumberOption(\"factor\", options.factor, {\n min: 0,\n allowInfinity: false,\n });\n validateNumberOption(\"minTimeout\", options.minTimeout, {\n min: 0,\n allowInfinity: false,\n });\n validateNumberOption(\"maxTimeout\", options.maxTimeout, {\n min: 0,\n allowInfinity: true,\n });\n validateNumberOption(\"maxRetryTime\", options.maxRetryTime, {\n min: 0,\n allowInfinity: true,\n });\n\n // Treat non-positive factor as 1 to avoid zero backoff or negative behavior\n if (!(options.factor > 0)) {\n options.factor = 1;\n }\n\n options.signal?.throwIfAborted();\n\n let attemptNumber = 0;\n let retriesConsumed = 0;\n const startTime = performance.now();\n\n while (\n Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true\n ) {\n attemptNumber++;\n\n try {\n options.signal?.throwIfAborted();\n\n const result = await input(attemptNumber);\n\n options.signal?.throwIfAborted();\n\n return result;\n } catch (error) {\n if (\n await onAttemptFailure({\n error,\n attemptNumber,\n retriesConsumed,\n startTime,\n options,\n })\n ) {\n retriesConsumed++;\n }\n }\n }\n\n // Should not reach here, but in case it does, throw an error\n throw new Error(\"Retry attempts exhausted without throwing an error.\");\n}\n\nexport function makeRetriable(function_, options) {\n return function (...arguments_) {\n return pRetry(() => function_.apply(this, arguments_), options);\n };\n}\n"],"mappings":";;AAGA,SAAS,gBAAgB,SAAS;AAChC,KAAI,OAAO,YAAY,UAAU;AAC/B,MAAI,UAAU,EACZ,OAAM,IAAI,UAAU,kDAAkD;AAGxE,MAAI,OAAO,MAAM,QAAQ,CACvB,OAAM,IAAI,UACR,gEACD;YAEM,YAAY,KAAA,EACrB,OAAM,IAAI,UAAU,iDAAiD;;AAIzE,SAAS,qBACP,MACA,OACA,EAAE,MAAM,GAAG,gBAAgB,UAAU,EAAE,EACvC;AACA,KAAI,UAAU,KAAA,EACZ;AAGF,KAAI,OAAO,UAAU,YAAY,OAAO,MAAM,MAAM,CAClD,OAAM,IAAI,UACR,cAAc,KAAK,mBACjB,gBAAgB,iBAAiB,GAClC,GACF;AAGH,KAAI,CAAC,iBAAiB,CAAC,OAAO,SAAS,MAAM,CAC3C,OAAM,IAAI,UAAU,cAAc,KAAK,2BAA2B;AAGpE,KAAI,QAAQ,IACV,OAAM,IAAI,UAAU,cAAc,KAAK,kBAAkB,IAAI,GAAG;;AAIpE,IAAa,aAAb,cAAgC,MAAM;CACpC,YAAY,SAAS;AACnB,SAAO;AAEP,MAAI,mBAAmB,OAAO;AAC5B,QAAK,gBAAgB;AACrB,IAAC,CAAE,WAAY;SACV;AACL,QAAK,gBAAgB,IAAI,MAAM,QAAQ;AACvC,QAAK,cAAc,QAAQ,KAAK;;AAGlC,OAAK,OAAO;AACZ,OAAK,UAAU;;;AAInB,SAAS,eAAe,iBAAiB,SAAS;CAChD,MAAM,UAAU,KAAK,IAAI,GAAG,kBAAkB,EAAE;CAChD,MAAM,SAAS,QAAQ,YAAY,KAAK,QAAQ,GAAG,IAAI;CAEvD,IAAI,UAAU,KAAK,MACjB,SAAS,QAAQ,aAAa,QAAQ,WAAW,UAAU,GAC5D;AACD,WAAU,KAAK,IAAI,SAAS,QAAQ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B;AAEhC,UAAO;WACA,OAAO;AACd,OACE,MAAM,iBAAiB;IACrB;IACA;IACA;IACA;IACA;IACD,CAAC,CAEF;;;AAMN,OAAM,IAAI,MAAM,sDAAsD"}
1
+ {"version":3,"file":"index.cjs","names":["isNetworkError"],"sources":["../../../src/util/p-retry/index.js"],"sourcesContent":["/* oxlint-disable */\nimport isNetworkError from \"../is-network-error/index.js\";\n\nfunction validateRetries(retries) {\n if (typeof retries === \"number\") {\n if (retries < 0) {\n throw new TypeError(\"Expected `retries` to be a non-negative number.\");\n }\n\n if (Number.isNaN(retries)) {\n throw new TypeError(\n \"Expected `retries` to be a valid number or Infinity, got NaN.\"\n );\n }\n } else if (retries !== undefined) {\n throw new TypeError(\"Expected `retries` to be a number or Infinity.\");\n }\n}\n\nfunction validateNumberOption(\n name,\n value,\n { min = 0, allowInfinity = false } = {}\n) {\n if (value === undefined) {\n return;\n }\n\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n throw new TypeError(\n `Expected \\`${name}\\` to be a number${\n allowInfinity ? \" or Infinity\" : \"\"\n }.`\n );\n }\n\n if (!allowInfinity && !Number.isFinite(value)) {\n throw new TypeError(`Expected \\`${name}\\` to be a finite number.`);\n }\n\n if (value < min) {\n throw new TypeError(`Expected \\`${name}\\` to be \\u2265 ${min}.`);\n }\n}\n\nexport class AbortError extends Error {\n constructor(message) {\n super();\n\n if (message instanceof Error) {\n this.originalError = message;\n ({ message } = message);\n } else {\n this.originalError = new Error(message);\n this.originalError.stack = this.stack;\n }\n\n this.name = \"AbortError\";\n this.message = message;\n }\n}\n\nfunction calculateDelay(retriesConsumed, options) {\n const attempt = Math.max(1, retriesConsumed + 1);\n const random = options.randomize ? Math.random() + 1 : 1;\n\n let timeout = Math.round(\n random * options.minTimeout * options.factor ** (attempt - 1)\n );\n timeout = Math.min(timeout, options.maxTimeout);\n\n return timeout;\n}\n\nfunction calculateRemainingTime(start, max) {\n if (!Number.isFinite(max)) {\n return max;\n }\n\n return max - (performance.now() - start);\n}\n\nasync function onAttemptFailure({\n error,\n attemptNumber,\n retriesConsumed,\n startTime,\n options,\n}) {\n const normalizedError =\n error instanceof Error\n ? error\n : new TypeError(\n `Non-error was thrown: \"${error}\". You should only throw errors.`\n );\n\n if (normalizedError instanceof AbortError) {\n throw normalizedError.originalError;\n }\n\n const retriesLeft = Number.isFinite(options.retries)\n ? Math.max(0, options.retries - retriesConsumed)\n : options.retries;\n\n const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;\n\n const context = Object.freeze({\n error: normalizedError,\n attemptNumber,\n retriesLeft,\n retriesConsumed,\n });\n\n await options.onFailedAttempt(context);\n\n if (calculateRemainingTime(startTime, maxRetryTime) <= 0) {\n throw normalizedError;\n }\n\n const consumeRetry = await options.shouldConsumeRetry(context);\n\n const remainingTime = calculateRemainingTime(startTime, maxRetryTime);\n\n if (remainingTime <= 0 || retriesLeft <= 0) {\n throw normalizedError;\n }\n\n if (\n normalizedError instanceof TypeError &&\n !isNetworkError(normalizedError)\n ) {\n if (consumeRetry) {\n throw normalizedError;\n }\n\n options.signal?.throwIfAborted();\n return false;\n }\n\n if (!(await options.shouldRetry(context))) {\n throw normalizedError;\n }\n\n if (!consumeRetry) {\n options.signal?.throwIfAborted();\n return false;\n }\n\n const delayTime = calculateDelay(retriesConsumed, options);\n const finalDelay = Math.min(delayTime, remainingTime);\n\n if (finalDelay > 0) {\n await new Promise((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timeoutToken);\n options.signal?.removeEventListener(\"abort\", onAbort);\n reject(options.signal.reason);\n };\n\n const timeoutToken = setTimeout(() => {\n options.signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, finalDelay);\n\n if (options.unref) {\n timeoutToken.unref?.();\n }\n\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n options.signal?.throwIfAborted();\n\n return true;\n}\n\nexport default async function pRetry(input, options = {}) {\n options = { ...options };\n\n validateRetries(options.retries);\n\n if (Object.hasOwn(options, \"forever\")) {\n throw new Error(\n \"The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.\"\n );\n }\n\n options.retries ??= 10;\n options.factor ??= 2;\n options.minTimeout ??= 1000;\n options.maxTimeout ??= Number.POSITIVE_INFINITY;\n options.maxRetryTime ??= Number.POSITIVE_INFINITY;\n options.randomize ??= false;\n options.onFailedAttempt ??= () => {};\n options.shouldRetry ??= () => true;\n options.shouldConsumeRetry ??= () => true;\n\n // Validate numeric options and normalize edge cases\n validateNumberOption(\"factor\", options.factor, {\n min: 0,\n allowInfinity: false,\n });\n validateNumberOption(\"minTimeout\", options.minTimeout, {\n min: 0,\n allowInfinity: false,\n });\n validateNumberOption(\"maxTimeout\", options.maxTimeout, {\n min: 0,\n allowInfinity: true,\n });\n validateNumberOption(\"maxRetryTime\", options.maxRetryTime, {\n min: 0,\n allowInfinity: true,\n });\n\n // Treat non-positive factor as 1 to avoid zero backoff or negative behavior\n if (!(options.factor > 0)) {\n options.factor = 1;\n }\n\n options.signal?.throwIfAborted();\n\n let attemptNumber = 0;\n let retriesConsumed = 0;\n const startTime = performance.now();\n\n while (\n Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true\n ) {\n attemptNumber++;\n\n try {\n options.signal?.throwIfAborted();\n\n const result = await input(attemptNumber);\n\n options.signal?.throwIfAborted();\n\n return result;\n } catch (error) {\n if (\n await onAttemptFailure({\n error,\n attemptNumber,\n retriesConsumed,\n startTime,\n options,\n })\n ) {\n retriesConsumed++;\n }\n }\n }\n\n // Should not reach here, but in case it does, throw an error\n throw new Error(\"Retry attempts exhausted without throwing an error.\");\n}\n\nexport function makeRetriable(function_, options) {\n return function (...arguments_) {\n return pRetry(() => function_.apply(this, arguments_), options);\n };\n}\n"],"mappings":";;AAGA,SAAS,gBAAgB,SAAS;AAChC,KAAI,OAAO,YAAY,UAAU;AAC/B,MAAI,UAAU,EACZ,OAAM,IAAI,UAAU,kDAAkD;AAGxE,MAAI,OAAO,MAAM,QAAQ,CACvB,O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A8B,OAAO,OAAO,UAAU,EAAE,EAAE;AACxD,WAAU,EAAE,GAAG,SAAS;AAExB,iBAAgB,QAAQ,QAAQ;AAEhC,KAAI,OAAO,OAAO,SAAS,UAAU,CACnC,OAAM,IAAI,MACR,4GACD;AAGH,SAAQ,YAAY;AACpB,SAAQ,WAAW;AACnB,SAAQ,eAAe;AACvB,SAAQ,eAAe,OAAO;AAC9B,SAAQ,iBAAiB,OAAO;AAChC,SAAQ,cAAc;AACtB,SAAQ,0BAA0B;AAClC,SAAQ,sBAAsB;AAC9B,SAAQ,6BAA6B;AAGrC,sBAAqB,UAAU,QAAQ,QAAQ;EAC7C,KAAK;EACL,eAAe;EAChB,CAAC;AACF,sBAAqB,cAAc,QAAQ,YAAY;EACrD,KAAK;EACL,eAAe;EAChB,CAAC;AACF,sBAAqB,cAAc,QAAQ,YAAY;EACrD,KAAK;EACL,eAAe;EAChB,CAAC;AACF,sBAAqB,gBAAgB,QAAQ,cAAc;EACzD,KAAK;EACL,eAAe;EAChB,CAAC;AAGF,KAAI,EAAE,QAAQ,SAAS,GACrB,SAAQ,SAAS;AAGnB,SAAQ,QAAQ,gBAAgB;CAEhC,IAAI,gBAAgB;CACpB,IAAI,kBAAkB;CACtB,MAAM,YAAY,YAAY,KAAK;AAEnC,QACE,OAAO,SAAS,QAAQ,QAAQ,GAAG,mBAAmB,QAAQ,UAAU,MACxE;AACA;AAEA,MAAI;AACF,WAAQ,QAAQ,gBAAgB;GAEhC,MAAM,SAAS,MAAM,MAAM,cAAc;AAEzC,WAAQ,QAAQ,gBAAgB;AAEhC,UAAO;WACA,OAAO;AACd,OACE,MAAM,iBAAiB;IACrB;IACA;IACA;IACA;IACA;IACD,CAAC,CAEF;;;AAMN,OAAM,IAAI,MAAM,sDAAsD"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/util/p-retry/index.js"],"sourcesContent":["/* eslint-disable */\nimport isNetworkError from \"../is-network-error/index.js\";\n\nfunction validateRetries(retries) {\n if (typeof retries === \"number\") {\n if (retries < 0) {\n throw new TypeError(\"Expected `retries` to be a non-negative number.\");\n }\n\n if (Number.isNaN(retries)) {\n throw new TypeError(\n \"Expected `retries` to be a valid number or Infinity, got NaN.\"\n );\n }\n } else if (retries !== undefined) {\n throw new TypeError(\"Expected `retries` to be a number or Infinity.\");\n }\n}\n\nfunction validateNumberOption(\n name,\n value,\n { min = 0, allowInfinity = false } = {}\n) {\n if (value === undefined) {\n return;\n }\n\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n throw new TypeError(\n `Expected \\`${name}\\` to be a number${\n allowInfinity ? \" or Infinity\" : \"\"\n }.`\n );\n }\n\n if (!allowInfinity && !Number.isFinite(value)) {\n throw new TypeError(`Expected \\`${name}\\` to be a finite number.`);\n }\n\n if (value < min) {\n throw new TypeError(`Expected \\`${name}\\` to be \\u2265 ${min}.`);\n }\n}\n\nexport class AbortError extends Error {\n constructor(message) {\n super();\n\n if (message instanceof Error) {\n this.originalError = message;\n ({ message } = message);\n } else {\n this.originalError = new Error(message);\n this.originalError.stack = this.stack;\n }\n\n this.name = \"AbortError\";\n this.message = message;\n }\n}\n\nfunction calculateDelay(retriesConsumed, options) {\n const attempt = Math.max(1, retriesConsumed + 1);\n const random = options.randomize ? Math.random() + 1 : 1;\n\n let timeout = Math.round(\n random * options.minTimeout * options.factor ** (attempt - 1)\n );\n timeout = Math.min(timeout, options.maxTimeout);\n\n return timeout;\n}\n\nfunction calculateRemainingTime(start, max) {\n if (!Number.isFinite(max)) {\n return max;\n }\n\n return max - (performance.now() - start);\n}\n\nasync function onAttemptFailure({\n error,\n attemptNumber,\n retriesConsumed,\n startTime,\n options,\n}) {\n const normalizedError =\n error instanceof Error\n ? error\n : new TypeError(\n `Non-error was thrown: \"${error}\". You should only throw errors.`\n );\n\n if (normalizedError instanceof AbortError) {\n throw normalizedError.originalError;\n }\n\n const retriesLeft = Number.isFinite(options.retries)\n ? Math.max(0, options.retries - retriesConsumed)\n : options.retries;\n\n const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;\n\n const context = Object.freeze({\n error: normalizedError,\n attemptNumber,\n retriesLeft,\n retriesConsumed,\n });\n\n await options.onFailedAttempt(context);\n\n if (calculateRemainingTime(startTime, maxRetryTime) <= 0) {\n throw normalizedError;\n }\n\n const consumeRetry = await options.shouldConsumeRetry(context);\n\n const remainingTime = calculateRemainingTime(startTime, maxRetryTime);\n\n if (remainingTime <= 0 || retriesLeft <= 0) {\n throw normalizedError;\n }\n\n if (\n normalizedError instanceof TypeError &&\n !isNetworkError(normalizedError)\n ) {\n if (consumeRetry) {\n throw normalizedError;\n }\n\n options.signal?.throwIfAborted();\n return false;\n }\n\n if (!(await options.shouldRetry(context))) {\n throw normalizedError;\n }\n\n if (!consumeRetry) {\n options.signal?.throwIfAborted();\n return false;\n }\n\n const delayTime = calculateDelay(retriesConsumed, options);\n const finalDelay = Math.min(delayTime, remainingTime);\n\n if (finalDelay > 0) {\n await new Promise((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timeoutToken);\n options.signal?.removeEventListener(\"abort\", onAbort);\n reject(options.signal.reason);\n };\n\n const timeoutToken = setTimeout(() => {\n options.signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, finalDelay);\n\n if (options.unref) {\n timeoutToken.unref?.();\n }\n\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n options.signal?.throwIfAborted();\n\n return true;\n}\n\nexport default async function pRetry(input, options = {}) {\n options = { ...options };\n\n validateRetries(options.retries);\n\n if (Object.hasOwn(options, \"forever\")) {\n throw new Error(\n \"The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.\"\n );\n }\n\n options.retries ??= 10;\n options.factor ??= 2;\n options.minTimeout ??= 1000;\n options.maxTimeout ??= Number.POSITIVE_INFINITY;\n options.maxRetryTime ??= Number.POSITIVE_INFINITY;\n options.randomize ??= false;\n options.onFailedAttempt ??= () => {};\n options.shouldRetry ??= () => true;\n options.shouldConsumeRetry ??= () => true;\n\n // Validate numeric options and normalize edge cases\n validateNumberOption(\"factor\", options.factor, {\n min: 0,\n allowInfinity: false,\n });\n validateNumberOption(\"minTimeout\", options.minTimeout, {\n min: 0,\n allowInfinity: false,\n });\n validateNumberOption(\"maxTimeout\", options.maxTimeout, {\n min: 0,\n allowInfinity: true,\n });\n validateNumberOption(\"maxRetryTime\", options.maxRetryTime, {\n min: 0,\n allowInfinity: true,\n });\n\n // Treat non-positive factor as 1 to avoid zero backoff or negative behavior\n if (!(options.factor > 0)) {\n options.factor = 1;\n }\n\n options.signal?.throwIfAborted();\n\n let attemptNumber = 0;\n let retriesConsumed = 0;\n const startTime = performance.now();\n\n while (\n Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true\n ) {\n attemptNumber++;\n\n try {\n options.signal?.throwIfAborted();\n\n const result = await input(attemptNumber);\n\n options.signal?.throwIfAborted();\n\n return result;\n } catch (error) {\n if (\n await onAttemptFailure({\n error,\n attemptNumber,\n retriesConsumed,\n startTime,\n options,\n })\n ) {\n retriesConsumed++;\n }\n }\n }\n\n // Should not reach here, but in case it does, throw an error\n throw new Error(\"Retry attempts exhausted without throwing an error.\");\n}\n\nexport function makeRetriable(function_, options) {\n return function (...arguments_) {\n return pRetry(() => function_.apply(this, arguments_), options);\n };\n}\n"],"mappings":";;AAGA,SAAS,gBAAgB,SAAS;AAChC,KAAI,OAAO,YAAY,UAAU;AAC/B,MAAI,UAAU,EACZ,OAAM,IAAI,UAAU,kDAAkD;AAGxE,MAAI,OAAO,MAAM,QAAQ,CACvB,OAAM,IAAI,UACR,gEACD;YAEM,YAAY,KAAA,EACrB,OAAM,IAAI,UAAU,iDAAiD;;AAIzE,SAAS,qBACP,MACA,OACA,EAAE,MAAM,GAAG,gBAAgB,UAAU,EAAE,EACvC;AACA,KAAI,UAAU,KAAA,EACZ;AAGF,KAAI,OAAO,UAAU,YAAY,OAAO,MAAM,MAAM,CAClD,OAAM,IAAI,UACR,cAAc,KAAK,mBAC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O;AAChC,SAAQ,cAAc;AACtB,SAAQ,0BAA0B;AAClC,SAAQ,sBAAsB;AAC9B,SAAQ,6BAA6B;AAGrC,sBAAqB,UAAU,QAAQ,QAAQ;EAC7C,KAAK;EACL,eAAe;EAChB,CAAC;AACF,sBAAqB,cAAc,QAAQ,YAAY;EACrD,KAAK;EACL,eAAe;EAChB,CAAC;AACF,sBAAqB,cAAc,QAAQ,YAAY;EACrD,KAAK;EACL,eAAe;EAChB,CAAC;AACF,sBAAqB,gBAAgB,QAAQ,cAAc;EACzD,KAAK;EACL,eAAe;EAChB,CAAC;AAGF,KAAI,EAAE,QAAQ,SAAS,GACrB,SAAQ,SAAS;AAGnB,SAAQ,QAAQ,gBAAgB;CAEhC,IAAI,gBAAgB;CACpB,IAAI,kBAAkB;CACtB,MAAM,YAAY,YAAY,KAAK;AAEnC,QACE,OAAO,SAAS,QAAQ,QAAQ,GAAG,mBAAmB,QAAQ,UAAU,MACxE;AACA;AAEA,MAAI;AACF,WAAQ,QAAQ,gBAAgB;GAEhC,MAAM,SAAS,MAAM,MAAM,cAAc;AAEzC,WAAQ,QAAQ,gBAAgB;AAEhC,UAAO;WACA,OAAO;AACd,OACE,MAAM,iBAAiB;IACrB;IACA;IACA;IACA;IACA;IACD,CAAC,CAEF;;;AAMN,OAAM,IAAI,MAAM,sDAAsD"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/util/p-retry/index.js"],"sourcesContent":["/* oxlint-disable */\nimport isNetworkError from \"../is-network-error/index.js\";\n\nfunction validateRetries(retries) {\n if (typeof retries === \"number\") {\n if (retries < 0) {\n throw new TypeError(\"Expected `retries` to be a non-negative number.\");\n }\n\n if (Number.isNaN(retries)) {\n throw new TypeError(\n \"Expected `retries` to be a valid number or Infinity, got NaN.\"\n );\n }\n } else if (retries !== undefined) {\n throw new TypeError(\"Expected `retries` to be a number or Infinity.\");\n }\n}\n\nfunction validateNumberOption(\n name,\n value,\n { min = 0, allowInfinity = false } = {}\n) {\n if (value === undefined) {\n return;\n }\n\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n throw new TypeError(\n `Expected \\`${name}\\` to be a number${\n allowInfinity ? \" or Infinity\" : \"\"\n }.`\n );\n }\n\n if (!allowInfinity && !Number.isFinite(value)) {\n throw new TypeError(`Expected \\`${name}\\` to be a finite number.`);\n }\n\n if (value < min) {\n throw new TypeError(`Expected \\`${name}\\` to be \\u2265 ${min}.`);\n }\n}\n\nexport class AbortError extends Error {\n constructor(message) {\n super();\n\n if (message instanceof Error) {\n this.originalError = message;\n ({ message } = message);\n } else {\n this.originalError = new Error(message);\n this.originalError.stack = this.stack;\n }\n\n this.name = \"AbortError\";\n this.message = message;\n }\n}\n\nfunction calculateDelay(retriesConsumed, options) {\n const attempt = Math.max(1, retriesConsumed + 1);\n const random = options.randomize ? Math.random() + 1 : 1;\n\n let timeout = Math.round(\n random * options.minTimeout * options.factor ** (attempt - 1)\n );\n timeout = Math.min(timeout, options.maxTimeout);\n\n return timeout;\n}\n\nfunction calculateRemainingTime(start, max) {\n if (!Number.isFinite(max)) {\n return max;\n }\n\n return max - (performance.now() - start);\n}\n\nasync function onAttemptFailure({\n error,\n attemptNumber,\n retriesConsumed,\n startTime,\n options,\n}) {\n const normalizedError =\n error instanceof Error\n ? error\n : new TypeError(\n `Non-error was thrown: \"${error}\". You should only throw errors.`\n );\n\n if (normalizedError instanceof AbortError) {\n throw normalizedError.originalError;\n }\n\n const retriesLeft = Number.isFinite(options.retries)\n ? Math.max(0, options.retries - retriesConsumed)\n : options.retries;\n\n const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;\n\n const context = Object.freeze({\n error: normalizedError,\n attemptNumber,\n retriesLeft,\n retriesConsumed,\n });\n\n await options.onFailedAttempt(context);\n\n if (calculateRemainingTime(startTime, maxRetryTime) <= 0) {\n throw normalizedError;\n }\n\n const consumeRetry = await options.shouldConsumeRetry(context);\n\n const remainingTime = calculateRemainingTime(startTime, maxRetryTime);\n\n if (remainingTime <= 0 || retriesLeft <= 0) {\n throw normalizedError;\n }\n\n if (\n normalizedError instanceof TypeError &&\n !isNetworkError(normalizedError)\n ) {\n if (consumeRetry) {\n throw normalizedError;\n }\n\n options.signal?.throwIfAborted();\n return false;\n }\n\n if (!(await options.shouldRetry(context))) {\n throw normalizedError;\n }\n\n if (!consumeRetry) {\n options.signal?.throwIfAborted();\n return false;\n }\n\n const delayTime = calculateDelay(retriesConsumed, options);\n const finalDelay = Math.min(delayTime, remainingTime);\n\n if (finalDelay > 0) {\n await new Promise((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timeoutToken);\n options.signal?.removeEventListener(\"abort\", onAbort);\n reject(options.signal.reason);\n };\n\n const timeoutToken = setTimeout(() => {\n options.signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, finalDelay);\n\n if (options.unref) {\n timeoutToken.unref?.();\n }\n\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n options.signal?.throwIfAborted();\n\n return true;\n}\n\nexport default async function pRetry(input, options = {}) {\n options = { ...options };\n\n validateRetries(options.retries);\n\n if (Object.hasOwn(options, \"forever\")) {\n throw new Error(\n \"The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.\"\n );\n }\n\n options.retries ??= 10;\n options.factor ??= 2;\n options.minTimeout ??= 1000;\n options.maxTimeout ??= Number.POSITIVE_INFINITY;\n options.maxRetryTime ??= Number.POSITIVE_INFINITY;\n options.randomize ??= false;\n options.onFailedAttempt ??= () => {};\n options.shouldRetry ??= () => true;\n options.shouldConsumeRetry ??= () => true;\n\n // Validate numeric options and normalize edge cases\n validateNumberOption(\"factor\", options.factor, {\n min: 0,\n allowInfinity: false,\n });\n validateNumberOption(\"minTimeout\", options.minTimeout, {\n min: 0,\n allowInfinity: false,\n });\n validateNumberOption(\"maxTimeout\", options.maxTimeout, {\n min: 0,\n allowInfinity: true,\n });\n validateNumberOption(\"maxRetryTime\", options.maxRetryTime, {\n min: 0,\n allowInfinity: true,\n });\n\n // Treat non-positive factor as 1 to avoid zero backoff or negative behavior\n if (!(options.factor > 0)) {\n options.factor = 1;\n }\n\n options.signal?.throwIfAborted();\n\n let attemptNumber = 0;\n let retriesConsumed = 0;\n const startTime = performance.now();\n\n while (\n Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true\n ) {\n attemptNumber++;\n\n try {\n options.signal?.throwIfAborted();\n\n const result = await input(attemptNumber);\n\n options.signal?.throwIfAborted();\n\n return result;\n } catch (error) {\n if (\n await onAttemptFailure({\n error,\n attemptNumber,\n retriesConsumed,\n startTime,\n options,\n })\n ) {\n retriesConsumed++;\n }\n }\n }\n\n // Should not reach here, but in case it does, throw an error\n throw new Error(\"Retry attempts exhausted without throwing an error.\");\n}\n\nexport function makeRetriable(function_, options) {\n return function (...arguments_) {\n return pRetry(() => function_.apply(this, arguments_), options);\n };\n}\n"],"mappings":";;AAGA,SAAS,gBAAgB,SAAS;AAChC,KAAI,OAAO,YAAY,UAAU;AAC/B,MAAI,UAAU,EACZ,OAAM,IAAI,UAAU,kDAAkD;AAGxE,MAAI,OAAO,MAAM,QAAQ,CACvB,OAAM,IAAI,UACR,gEACD;YAEM,YAAY,KAAA,EACrB,OAAM,IAAI,UAAU,iDAAiD;;AAIzE,SAAS,qBACP,MACA,OACA,EAAE,MAAM,GAAG,gBAAgB,UAAU,EAAE,EACvC;AACA,KAAI,UAAU,KAAA,EACZ;AAGF,KAAI,OAAO,UAAU,YAAY,OAAO,MAAM,MAAM,CAClD,OAAM,IAAI,UACR,cAAc,KAAK,mBACjB,gBAAgB,iBAAiB,GAClC,GACF;AAGH,KAAI,CAAC,iBAAiB,CAAC,OAAO,SAAS,MAAM,CAC3C,OAAM,IAAI,UAAU,cAAc,KAAK,2BAA2B;AAGpE,KAAI,QAAQ,IACV,OAAM,IAAI,UAAU,cAAc,KAAK,kBAAkB,IAAI,GAAG;;AAIpE,IAAa,aAAb,cAAgC,MAAM;CACpC,YAAY,SAAS;AACnB,SAAO;AAEP,MAAI,mB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;EAChB,CAAC;AACF,sBAAqB,gBAAgB,QAAQ,cAAc;EACzD,KAAK;EACL,eAAe;EAChB,CAAC;AAGF,KAAI,EAAE,QAAQ,SAAS,GACrB,SAAQ,SAAS;AAGnB,SAAQ,QAAQ,gBAAgB;CAEhC,IAAI,gBAAgB;CACpB,IAAI,kBAAkB;CACtB,MAAM,YAAY,YAAY,KAAK;AAEnC,QACE,OAAO,SAAS,QAAQ,QAAQ,GAAG,mBAAmB,QAAQ,UAAU,MACxE;AACA;AAEA,MAAI;AACF,WAAQ,QAAQ,gBAAgB;GAEhC,MAAM,SAAS,MAAM,MAAM,cAAc;AAEzC,WAAQ,QAAQ,gBAAgB;AAEhC,UAAO;WACA,OAAO;AACd,OACE,MAAM,iBAAiB;IACrB;IACA;IACA;IACA;IACA;IACD,CAAC,CAEF;;;AAMN,OAAM,IAAI,MAAM,sDAAsD"}
@@ -1 +1 @@
1
- {"version":3,"file":"memory.cjs","names":["VectorStore","cosine","Document"],"sources":["../../src/vectorstores/memory.ts"],"sourcesContent":["import {\n MaxMarginalRelevanceSearchOptions,\n VectorStore,\n} from \"@langchain/core/vectorstores\";\nimport type { EmbeddingsInterface } from \"@langchain/core/embeddings\";\nimport { Document, DocumentInterface } from \"@langchain/core/documents\";\nimport { maximalMarginalRelevance } from \"@langchain/core/utils/math\";\nimport { cosine } from \"../util/ml-distance/similarities.js\";\n\n/**\n * Interface representing a vector in memory. It includes the content\n * (text), the corresponding embedding (vector), and any associated\n * metadata.\n */\ninterface MemoryVector {\n content: string;\n embedding: number[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n id?: string;\n}\n\n/**\n * Interface for the arguments that can be passed to the\n * `MemoryVectorStore` constructor. It includes an optional `similarity`\n * function.\n */\nexport interface MemoryVectorStoreArgs {\n similarity?: typeof cosine;\n}\n\n/**\n * In-memory, ephemeral vector store.\n *\n * Setup:\n * Install `langchain`:\n *\n * ```bash\n * npm install langchain\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/langchain.vectorstores_memory.MemoryVectorStore.html#constructor)\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { MemoryVectorStore } from 'langchain/vectorstores/memory';\n * // Or other embeddings\n * import { OpenAIEmbeddings } from '@langchain/openai';\n *\n * const embeddings = new OpenAIEmbeddings({\n * model: \"text-embedding-3-small\",\n * });\n *\n * const vectorStore = new MemoryVectorStore(embeddings);\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Add documents</strong></summary>\n *\n * ```typescript\n * import type { Document } from '@langchain/core/documents';\n *\n * const document1 = { pageContent: \"foo\", metadata: { baz: \"bar\" } };\n * const document2 = { pageContent: \"thud\", metadata: { bar: \"baz\" } };\n * const document3 = { pageContent: \"i will be deleted :(\", metadata: {} };\n *\n * const documents: Document[] = [document1, document2, document3];\n *\n * await vectorStore.addDocuments(documents);\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Similarity search</strong></summary>\n *\n * ```typescript\n * const results = await vectorStore.similaritySearch(\"thud\", 1);\n * for (const doc of results) {\n * console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n * }\n * // Output: * thud [{\"baz\":\"bar\"}]\n * ```\n * </details>\n *\n * <br />\n *\n *\n * <details>\n * <summary><strong>Similarity search with filter</strong></summary>\n *\n * ```typescript\n * const resultsWithFilter = await vectorStore.similaritySearch(\"thud\", 1, { baz: \"bar\" });\n *\n * for (const doc of resultsWithFilter) {\n * console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n * }\n * // Output: * foo [{\"baz\":\"bar\"}]\n * ```\n * </details>\n *\n * <br />\n *\n *\n * <details>\n * <summary><strong>Similarity search with score</strong></summary>\n *\n * ```typescript\n * const resultsWithScore = await vectorStore.similaritySearchWithScore(\"qux\", 1);\n * for (const [doc, score] of resultsWithScore) {\n * console.log(`* [SIM=${score.toFixed(6)}] ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n * }\n * // Output: * [SIM=0.000000] qux [{\"bar\":\"baz\",\"baz\":\"bar\"}]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>As a retriever</strong></summary>\n *\n * ```typescript\n * const retriever = vectorStore.asRetriever({\n * searchType: \"mmr\", // Leave blank for standard similarity search\n * k: 1,\n * });\n * const resultAsRetriever = await retriever.invoke(\"thud\");\n * console.log(resultAsRetriever);\n *\n * // Output: [Document({ metadata: { \"baz\":\"bar\" }, pageContent: \"thud\" })]\n * ```\n * </details>\n *\n * <br />\n */\nexport class MemoryVectorStore extends VectorStore {\n declare FilterType: (doc: Document) => boolean;\n\n memoryVectors: MemoryVector[] = [];\n\n similarity: typeof cosine;\n\n _vectorstoreType(): string {\n return \"memory\";\n }\n\n constructor(\n embeddings: EmbeddingsInterface,\n { similarity, ...rest }: MemoryVectorStoreArgs = {}\n ) {\n super(embeddings, rest);\n\n this.similarity = similarity ?? cosine;\n }\n\n /**\n * Method to add documents to the memory vector store. It extracts the\n * text from each document, generates embeddings for them, and adds the\n * resulting vectors to the store.\n * @param documents Array of `Document` instances to be added to the store.\n * @returns Promise that resolves when all documents have been added.\n */\n async addDocuments(documents: Document[]): Promise<void> {\n const texts = documents.map(({ pageContent }) => pageContent);\n return this.addVectors(\n await this.embeddings.embedDocuments(texts),\n documents\n );\n }\n\n /**\n * Method to add vectors to the memory vector store. It creates\n * `MemoryVector` instances for each vector and document pair and adds\n * them to the store.\n * @param vectors Array of vectors to be added to the store.\n * @param documents Array of `Document` instances corresponding to the vectors.\n * @returns Promise that resolves when all vectors have been added.\n */\n async addVectors(vectors: number[][], documents: Document[]): Promise<void> {\n const memoryVectors = vectors.map((embedding, idx) => ({\n content: documents[idx].pageContent,\n embedding,\n metadata: documents[idx].metadata,\n id: documents[idx].id,\n }));\n\n this.memoryVectors = this.memoryVectors.concat(memoryVectors);\n }\n\n protected async _queryVectors(\n query: number[],\n k: number,\n filter?: this[\"FilterType\"]\n ) {\n const filterFunction = (memoryVector: MemoryVector) => {\n if (!filter) {\n return true;\n }\n\n const doc = new Document({\n metadata: memoryVector.metadata,\n pageContent: memoryVector.content,\n id: memoryVector.id,\n });\n return filter(doc);\n };\n const filteredMemoryVectors = this.memoryVectors.filter(filterFunction);\n return filteredMemoryVectors\n .map((vector, index) => ({\n similarity: this.similarity(query, vector.embedding),\n index,\n metadata: vector.metadata,\n content: vector.content,\n embedding: vector.embedding,\n id: vector.id,\n }))\n .sort((a, b) => (a.similarity > b.similarity ? -1 : 0))\n .slice(0, k);\n }\n\n /**\n * Method to perform a similarity search in the memory vector store. It\n * calculates the similarity between the query vector and each vector in\n * the store, sorts the results by similarity, and returns the top `k`\n * results along with their scores.\n * @param query Query vector to compare against the vectors in the store.\n * @param k Number of top results to return.\n * @param filter Optional filter function to apply to the vectors before performing the search.\n * @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score.\n */\n async similaritySearchVectorWithScore(\n query: number[],\n k: number,\n filter?: this[\"FilterType\"]\n ): Promise<[Document, number][]> {\n const searches = await this._queryVectors(query, k, filter);\n const result: [Document, number][] = searches.map((search) => [\n new Document({\n metadata: search.metadata,\n pageContent: search.content,\n id: search.id,\n }),\n search.similarity,\n ]);\n\n return result;\n }\n\n async maxMarginalRelevanceSearch(\n query: string,\n options: MaxMarginalRelevanceSearchOptions<this[\"FilterType\"]>\n ): Promise<DocumentInterface[]> {\n const queryEmbedding = await this.embeddings.embedQuery(query);\n\n const searches = await this._queryVectors(\n queryEmbedding,\n options.fetchK ?? 20,\n options.filter\n );\n\n const embeddingList = searches.map((searchResp) => searchResp.embedding);\n\n const mmrIndexes = maximalMarginalRelevance(\n queryEmbedding,\n embeddingList,\n options.lambda,\n options.k\n );\n\n return mmrIndexes.map(\n (idx) =>\n new Document({\n metadata: searches[idx].metadata,\n pageContent: searches[idx].content,\n id: searches[idx].id,\n })\n );\n }\n\n /**\n * Static method to create a `MemoryVectorStore` instance from an array of\n * texts. It creates a `Document` for each text and metadata pair, and\n * adds them to the store.\n * @param texts Array of texts to be added to the store.\n * @param metadatas Array or single object of metadata corresponding to the texts.\n * @param embeddings `Embeddings` instance used to generate embeddings for the texts.\n * @param dbConfig Optional `MemoryVectorStoreArgs` to configure the `MemoryVectorStore` instance.\n * @returns Promise that resolves with a new `MemoryVectorStore` instance.\n */\n static async fromTexts(\n texts: string[],\n metadatas: object[] | object,\n embeddings: EmbeddingsInterface,\n dbConfig?: MemoryVectorStoreArgs\n ): Promise<MemoryVectorStore> {\n const docs: Document[] = [];\n for (let i = 0; i < texts.length; i += 1) {\n const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;\n const newDoc = new Document({\n pageContent: texts[i],\n metadata,\n });\n docs.push(newDoc);\n }\n return MemoryVectorStore.fromDocuments(docs, embeddings, dbConfig);\n }\n\n /**\n * Static method to create a `MemoryVectorStore` instance from an array of\n * `Document` instances. It adds the documents to the store.\n * @param docs Array of `Document` instances to be added to the store.\n * @param embeddings `Embeddings` instance used to generate embeddings for the documents.\n * @param dbConfig Optional `MemoryVectorStoreArgs` to configure the `MemoryVectorStore` instance.\n * @returns Promise that resolves with a new `MemoryVectorStore` instance.\n */\n static async fromDocuments(\n docs: Document[],\n embeddings: EmbeddingsInterface,\n dbConfig?: MemoryVectorStoreArgs\n ): Promise<MemoryVectorStore> {\n const instance = new this(embeddings, dbConfig);\n await instance.addDocuments(docs);\n return instance;\n }\n\n /**\n * Static method to create a `MemoryVectorStore` instance from an existing\n * index. It creates a new `MemoryVectorStore` instance without adding any\n * documents or vectors.\n * @param embeddings `Embeddings` instance used to generate embeddings for the documents.\n * @param dbConfig Optional `MemoryVectorStoreArgs` to configure the `MemoryVectorStore` instance.\n * @returns Promise that resolves with a new `MemoryVectorStore` instance.\n */\n static async fromExistingIndex(\n embeddings: EmbeddingsInterface,\n dbConfig?: MemoryVectorStoreArgs\n ): Promise<MemoryVectorStore> {\n const instance = new this(embeddings, dbConfig);\n return instance;\n }\n}\n"],"mapp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ory.ts"],"sourcesContent":["import {\n MaxMarginalRelevanceSearchOptions,\n VectorStore,\n} from \"@langchain/core/vectorstores\";\nimport type { EmbeddingsInterface } from \"@langchain/core/embeddings\";\nimport { Document, DocumentInterface } from \"@langchain/core/documents\";\nimport { maximalMarginalRelevance } from \"@langchain/core/utils/math\";\nimport { cosine } from \"../util/ml-distance/similarities.js\";\n\n/**\n * Interface representing a vector in memory. It includes the content\n * (text), the corresponding embedding (vector), and any associated\n * metadata.\n */\ninterface MemoryVector {\n content: string;\n embedding: number[];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n id?: string;\n}\n\n/**\n * Interface for the arguments that can be passed to the\n * `MemoryVectorStore` constructor. It includes an optional `similarity`\n * function.\n */\nexport interface MemoryVectorStoreArgs {\n similarity?: typeof cosine;\n}\n\n/**\n * In-memory, ephemeral vector store.\n *\n * Setup:\n * Install `langchain`:\n *\n * ```bash\n * npm install langchain\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/langchain.vectorstores_memory.MemoryVectorStore.html#constructor)\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { MemoryVectorStore } from 'langchain/vectorstores/memory';\n * // Or other embeddings\n * import { OpenAIEmbeddings } from '@langchain/openai';\n *\n * const embeddings = new OpenAIEmbeddings({\n * model: \"text-embedding-3-small\",\n * });\n *\n * const vectorStore = new MemoryVectorStore(embeddings);\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Add documents</strong></summary>\n *\n * ```typescript\n * import type { Document } from '@langchain/core/documents';\n *\n * const document1 = { pageContent: \"foo\", metadata: { baz: \"bar\" } };\n * const document2 = { pageContent: \"thud\", metadata: { bar: \"baz\" } };\n * const document3 = { pageContent: \"i will be deleted :(\", metadata: {} };\n *\n * const documents: Document[] = [document1, document2, document3];\n *\n * await vectorStore.addDocuments(documents);\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Similarity search</strong></summary>\n *\n * ```typescript\n * const results = await vectorStore.similaritySearch(\"thud\", 1);\n * for (const doc of results) {\n * console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n * }\n * // Output: * thud [{\"baz\":\"bar\"}]\n * ```\n * </details>\n *\n * <br />\n *\n *\n * <details>\n * <summary><strong>Similarity search with filter</strong></summary>\n *\n * ```typescript\n * const resultsWithFilter = await vectorStore.similaritySearch(\"thud\", 1, { baz: \"bar\" });\n *\n * for (const doc of resultsWithFilter) {\n * console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n * }\n * // Output: * foo [{\"baz\":\"bar\"}]\n * ```\n * </details>\n *\n * <br />\n *\n *\n * <details>\n * <summary><strong>Similarity search with score</strong></summary>\n *\n * ```typescript\n * const resultsWithScore = await vectorStore.similaritySearchWithScore(\"qux\", 1);\n * for (const [doc, score] of resultsWithScore) {\n * console.log(`* [SIM=${score.toFixed(6)}] ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n * }\n * // Output: * [SIM=0.000000] qux [{\"bar\":\"baz\",\"baz\":\"bar\"}]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>As a retriever</strong></summary>\n *\n * ```typescript\n * const retriever = vectorStore.asRetriever({\n * searchType: \"mmr\", // Leave blank for standard similarity search\n * k: 1,\n * });\n * const resultAsRetriever = await retriever.invoke(\"thud\");\n * console.log(resultAsRetriever);\n *\n * // Output: [Document({ metadata: { \"baz\":\"bar\" }, pageContent: \"thud\" })]\n * ```\n * </details>\n *\n * <br />\n */\nexport class MemoryVectorStore extends VectorStore {\n declare FilterType: (doc: Document) => boolean;\n\n memoryVectors: MemoryVector[] = [];\n\n similarity: typeof cosine;\n\n _vectorstoreType(): string {\n return \"memory\";\n }\n\n constructor(\n embeddings: EmbeddingsInterface,\n { similarity, ...rest }: MemoryVectorStoreArgs = {}\n ) {\n super(embeddings, rest);\n\n this.similarity = similarity ?? cosine;\n }\n\n /**\n * Method to add documents to the memory vector store. It extracts the\n * text from each document, generates embeddings for them, and adds the\n * resulting vectors to the store.\n * @param documents Array of `Document` instances to be added to the store.\n * @returns Promise that resolves when all documents have been added.\n */\n async addDocuments(documents: Document[]): Promise<void> {\n const texts = documents.map(({ pageContent }) => pageContent);\n return this.addVectors(\n await this.embeddings.embedDocuments(texts),\n documents\n );\n }\n\n /**\n * Method to add vectors to the memory vector store. It creates\n * `MemoryVector` instances for each vector and document pair and adds\n * them to the store.\n * @param vectors Array of vectors to be added to the store.\n * @param documents Array of `Document` instances corresponding to the vectors.\n * @returns Promise that resolves when all vectors have been added.\n */\n async addVectors(vectors: number[][], documents: Document[]): Promise<void> {\n const memoryVectors = vectors.map((embedding, idx) => ({\n content: documents[idx].pageContent,\n embedding,\n metadata: documents[idx].metadata,\n id: documents[idx].id,\n }));\n\n this.memoryVectors = this.memoryVectors.concat(memoryVectors);\n }\n\n protected async _queryVectors(\n query: number[],\n k: number,\n filter?: this[\"FilterType\"]\n ) {\n const filterFunction = (memoryVector: MemoryVector) => {\n if (!filter) {\n return true;\n }\n\n const doc = new Document({\n metadata: memoryVector.metadata,\n pageContent: memoryVector.content,\n id: memoryVector.id,\n });\n return filter(doc);\n };\n const filteredMemoryVectors = this.memoryVectors.filter(filterFunction);\n return filteredMemoryVectors\n .map((vector, index) => ({\n similarity: this.similarity(query, vector.embedding),\n index,\n metadata: vector.metadata,\n content: vector.content,\n embedding: vector.embedding,\n id: vector.id,\n }))\n .sort((a, b) => (a.similarity > b.similarity ? -1 : 0))\n .slice(0, k);\n }\n\n /**\n * Method to perform a similarity search in the memory vector store. It\n * calculates the similarity between the query vector and each vector in\n * the store, sorts the results by similarity, and returns the top `k`\n * results along with their scores.\n * @param query Query vector to compare against the vectors in the store.\n * @param k Number of top results to return.\n * @param filter Optional filter function to apply to the vectors before performing the search.\n * @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score.\n */\n async similaritySearchVectorWithScore(\n query: number[],\n k: number,\n filter?: this[\"FilterType\"]\n ): Promise<[Document, number][]> {\n const searches = await this._queryVectors(query, k, filter);\n const result: [Document, number][] = searches.map((search) => [\n new Document({\n metadata: search.metadata,\n pageContent: search.content,\n id: search.id,\n }),\n search.similarity,\n ]);\n\n return result;\n }\n\n async maxMarginalRelevanceSearch(\n query: string,\n options: MaxMarginalRelevanceSearchOptions<this[\"FilterType\"]>\n ): Promise<DocumentInterface[]> {\n const queryEmbedding = await this.embeddings.embedQuery(query);\n\n const searches = await this._queryVectors(\n queryEmbedding,\n options.fetchK ?? 20,\n options.filter\n );\n\n const embeddingList = searches.map((searchResp) => searchResp.embedding);\n\n const mmrIndexes = maximalMarginalRelevance(\n queryEmbedding,\n embeddingList,\n options.lambda,\n options.k\n );\n\n return mmrIndexes.map(\n (idx) =>\n new Document({\n metadata: searches[idx].metadata,\n pageContent: searches[idx].content,\n id: searches[idx].id,\n })\n );\n }\n\n /**\n * Static method to create a `MemoryVectorStore` instance from an array of\n * texts. It creates a `Document` for each text and metadata pair, and\n * adds them to the store.\n * @param texts Array of texts to be added to the store.\n * @param metadatas Array or single object of metadata corresponding to the texts.\n * @param embeddings `Embeddings` instance used to generate embeddings for the texts.\n * @param dbConfig Optional `MemoryVectorStoreArgs` to configure the `MemoryVectorStore` instance.\n * @returns Promise that resolves with a new `MemoryVectorStore` instance.\n */\n static async fromTexts(\n texts: string[],\n metadatas: object[] | object,\n embeddings: EmbeddingsInterface,\n dbConfig?: MemoryVectorStoreArgs\n ): Promise<MemoryVectorStore> {\n const docs: Document[] = [];\n for (let i = 0; i < texts.length; i += 1) {\n const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;\n const newDoc = new Document({\n pageContent: texts[i],\n metadata,\n });\n docs.push(newDoc);\n }\n return MemoryVectorStore.fromDocuments(docs, embeddings, dbConfig);\n }\n\n /**\n * Static method to create a `MemoryVectorStore` instance from an array of\n * `Document` instances. It adds the documents to the store.\n * @param docs Array of `Document` instances to be added to the store.\n * @param embeddings `Embeddings` instance used to generate embeddings for the documents.\n * @param dbConfig Optional `MemoryVectorStoreArgs` to configure the `MemoryVectorStore` instance.\n * @returns Promise that resolves with a new `MemoryVectorStore` instance.\n */\n static async fromDocuments(\n docs: Document[],\n embeddings: EmbeddingsInterface,\n dbConfig?: MemoryVectorStoreArgs\n ): Promise<MemoryVectorStore> {\n const instance = new this(embeddings, dbConfig);\n await instance.addDocuments(docs);\n return instance;\n }\n\n /**\n * Static method to create a `MemoryVectorStore` instance from an existing\n * index. It creates a new `MemoryVectorStore` instance without adding any\n * documents or vectors.\n * @param embeddings `Embeddings` instance used to generate embeddings for the documents.\n * @param dbConfig Optional `MemoryVectorStoreArgs` to configure the `MemoryVectorStore` instance.\n * @returns Promise that resolves with a new `MemoryVectorStore` instance.\n */\n static async fromExistingIndex(\n embeddings: EmbeddingsInterface,\n dbConfig?: MemoryVectorStoreArgs\n ): Promise<MemoryVectorStore> {\n const instance = new this(embeddings, dbConfig);\n return instance;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6IA,IAAa,oBAAb,MAAa,0BAA0BA,6BAAAA,YAAY;CAGjD,gBAAgC,EAAE;CAElC;CAEA,mBAA2B;AACzB,SAAO;;CAGT,YACE,YACA,EAAE,YAAY,GAAG,SAAgC,EAAE,EACnD;AACA,QAAM,YAAY,KAAK;AAEvB,OAAK,aAAa,cAAcC,qBAAAA;;;;;;;;;CAUlC,MAAM,aAAa,WAAsC;EACvD,MAAM,QAAQ,UAAU,KAAK,EAAE,kBAAkB,YAAY;AAC7D,SAAO,KAAK,WACV,MAAM,KAAK,WAAW,eAAe,MAAM,EAC3C,UACD;;;;;;;;;;CAWH,MAAM,WAAW,SAAqB,WAAsC;EAC1E,MAAM,gBAAgB,QAAQ,KAAK,WAAW,SAAS;GACrD,SAAS,UAAU,K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CAaH,aAAa,UACX,OACA,WACA,YACA,UAC4B;EAC5B,MAAM,OAAmB,EAAE;AAC3B,OAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,GAAG;GACxC,MAAM,WAAW,MAAM,QAAQ,UAAU,GAAG,UAAU,KAAK;GAC3D,MAAM,SAAS,IAAIA,0BAAAA,SAAS;IAC1B,aAAa,MAAM;IACnB;IACD,CAAC;AACF,QAAK,KAAK,OAAO;;AAEnB,SAAO,kBAAkB,cAAc,MAAM,YAAY,SAAS;;;;;;;;;;CAWpE,aAAa,cACX,MACA,YACA,UAC4B;EAC5B,MAAM,WAAW,IAAI,KAAK,YAAY,SAAS;AAC/C,QAAM,SAAS,aAAa,KAAK;AACjC,SAAO;;;;;;;;;;CAWT,aAAa,kBACX,YACA,UAC4B;AAE5B,SADiB,IAAI,KAAK,YAAY,SAAS"}
@@ -1 +1 @@
1
- {"version":3,"file":"memory.js","names":[],"sources":["../../src/vectorstores/memory.ts"],"sourcesContent":["import {\n MaxMarginalRelevanceSearchOptions,\n VectorStore,\n} from \"@langchain/core/vectorstores\";\nimport type { EmbeddingsInterface } from \"@langchain/core/embeddings\";\nimport { Document, DocumentInterface } from \"@langchain/core/documents\";\nimport { maximalMarginalRelevance } from \"@langchain/core/utils/math\";\nimport { cosine } from \"../util/ml-distance/similarities.js\";\n\n/**\n * Interface representing a vector in memory. It includes the content\n * (text), the corresponding embedding (vector), and any associated\n * metadata.\n */\ninterface MemoryVector {\n content: string;\n embedding: number[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n id?: string;\n}\n\n/**\n * Interface for the arguments that can be passed to the\n * `MemoryVectorStore` constructor. It includes an optional `similarity`\n * function.\n */\nexport interface MemoryVectorStoreArgs {\n similarity?: typeof cosine;\n}\n\n/**\n * In-memory, ephemeral vector store.\n *\n * Setup:\n * Install `langchain`:\n *\n * ```bash\n * npm install langchain\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/langchain.vectorstores_memory.MemoryVectorStore.html#constructor)\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { MemoryVectorStore } from 'langchain/vectorstores/memory';\n * // Or other embeddings\n * import { OpenAIEmbeddings } from '@langchain/openai';\n *\n * const embeddings = new OpenAIEmbeddings({\n * model: \"text-embedding-3-small\",\n * });\n *\n * const vectorStore = new MemoryVectorStore(embeddings);\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Add documents</strong></summary>\n *\n * ```typescript\n * import type { Document } from '@langchain/core/documents';\n *\n * const document1 = { pageContent: \"foo\", metadata: { baz: \"bar\" } };\n * const document2 = { pageContent: \"thud\", metadata: { bar: \"baz\" } };\n * const document3 = { pageContent: \"i will be deleted :(\", metadata: {} };\n *\n * const documents: Document[] = [document1, document2, document3];\n *\n * await vectorStore.addDocuments(documents);\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Similarity search</strong></summary>\n *\n * ```typescript\n * const results = await vectorStore.similaritySearch(\"thud\", 1);\n * for (const doc of results) {\n * console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n * }\n * // Output: * thud [{\"baz\":\"bar\"}]\n * ```\n * </details>\n *\n * <br />\n *\n *\n * <details>\n * <summary><strong>Similarity search with filter</strong></summary>\n *\n * ```typescript\n * const resultsWithFilter = await vectorStore.similaritySearch(\"thud\", 1, { baz: \"bar\" });\n *\n * for (const doc of resultsWithFilter) {\n * console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n * }\n * // Output: * foo [{\"baz\":\"bar\"}]\n * ```\n * </details>\n *\n * <br />\n *\n *\n * <details>\n * <summary><strong>Similarity search with score</strong></summary>\n *\n * ```typescript\n * const resultsWithScore = await vectorStore.similaritySearchWithScore(\"qux\", 1);\n * for (const [doc, score] of resultsWithScore) {\n * console.log(`* [SIM=${score.toFixed(6)}] ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n * }\n * // Output: * [SIM=0.000000] qux [{\"bar\":\"baz\",\"baz\":\"bar\"}]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>As a retriever</strong></summary>\n *\n * ```typescript\n * const retriever = vectorStore.asRetriever({\n * searchType: \"mmr\", // Leave blank for standard similarity search\n * k: 1,\n * });\n * const resultAsRetriever = await retriever.invoke(\"thud\");\n * console.log(resultAsRetriever);\n *\n * // Output: [Document({ metadata: { \"baz\":\"bar\" }, pageContent: \"thud\" })]\n * ```\n * </details>\n *\n * <br />\n */\nexport class MemoryVectorStore extends VectorStore {\n declare FilterType: (doc: Document) => boolean;\n\n memoryVectors: MemoryVector[] = [];\n\n similarity: typeof cosine;\n\n _vectorstoreType(): string {\n return \"memory\";\n }\n\n constructor(\n embeddings: EmbeddingsInterface,\n { similarity, ...rest }: MemoryVectorStoreArgs = {}\n ) {\n super(embeddings, rest);\n\n this.similarity = similarity ?? cosine;\n }\n\n /**\n * Method to add documents to the memory vector store. It extracts the\n * text from each document, generates embeddings for them, and adds the\n * resulting vectors to the store.\n * @param documents Array of `Document` instances to be added to the store.\n * @returns Promise that resolves when all documents have been added.\n */\n async addDocuments(documents: Document[]): Promise<void> {\n const texts = documents.map(({ pageContent }) => pageContent);\n return this.addVectors(\n await this.embeddings.embedDocuments(texts),\n documents\n );\n }\n\n /**\n * Method to add vectors to the memory vector store. It creates\n * `MemoryVector` instances for each vector and document pair and adds\n * them to the store.\n * @param vectors Array of vectors to be added to the store.\n * @param documents Array of `Document` instances corresponding to the vectors.\n * @returns Promise that resolves when all vectors have been added.\n */\n async addVectors(vectors: number[][], documents: Document[]): Promise<void> {\n const memoryVectors = vectors.map((embedding, idx) => ({\n content: documents[idx].pageContent,\n embedding,\n metadata: documents[idx].metadata,\n id: documents[idx].id,\n }));\n\n this.memoryVectors = this.memoryVectors.concat(memoryVectors);\n }\n\n protected async _queryVectors(\n query: number[],\n k: number,\n filter?: this[\"FilterType\"]\n ) {\n const filterFunction = (memoryVector: MemoryVector) => {\n if (!filter) {\n return true;\n }\n\n const doc = new Document({\n metadata: memoryVector.metadata,\n pageContent: memoryVector.content,\n id: memoryVector.id,\n });\n return filter(doc);\n };\n const filteredMemoryVectors = this.memoryVectors.filter(filterFunction);\n return filteredMemoryVectors\n .map((vector, index) => ({\n similarity: this.similarity(query, vector.embedding),\n index,\n metadata: vector.metadata,\n content: vector.content,\n embedding: vector.embedding,\n id: vector.id,\n }))\n .sort((a, b) => (a.similarity > b.similarity ? -1 : 0))\n .slice(0, k);\n }\n\n /**\n * Method to perform a similarity search in the memory vector store. It\n * calculates the similarity between the query vector and each vector in\n * the store, sorts the results by similarity, and returns the top `k`\n * results along with their scores.\n * @param query Query vector to compare against the vectors in the store.\n * @param k Number of top results to return.\n * @param filter Optional filter function to apply to the vectors before performing the search.\n * @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score.\n */\n async similaritySearchVectorWithScore(\n query: number[],\n k: number,\n filter?: this[\"FilterType\"]\n ): Promise<[Document, number][]> {\n const searches = await this._queryVectors(query, k, filter);\n const result: [Document, number][] = searches.map((search) => [\n new Document({\n metadata: search.metadata,\n pageContent: search.content,\n id: search.id,\n }),\n search.similarity,\n ]);\n\n return result;\n }\n\n async maxMarginalRelevanceSearch(\n query: string,\n options: MaxMarginalRelevanceSearchOptions<this[\"FilterType\"]>\n ): Promise<DocumentInterface[]> {\n const queryEmbedding = await this.embeddings.embedQuery(query);\n\n const searches = await this._queryVectors(\n queryEmbedding,\n options.fetchK ?? 20,\n options.filter\n );\n\n const embeddingList = searches.map((searchResp) => searchResp.embedding);\n\n const mmrIndexes = maximalMarginalRelevance(\n queryEmbedding,\n embeddingList,\n options.lambda,\n options.k\n );\n\n return mmrIndexes.map(\n (idx) =>\n new Document({\n metadata: searches[idx].metadata,\n pageContent: searches[idx].content,\n id: searches[idx].id,\n })\n );\n }\n\n /**\n * Static method to create a `MemoryVectorStore` instance from an array of\n * texts. It creates a `Document` for each text and metadata pair, and\n * adds them to the store.\n * @param texts Array of texts to be added to the store.\n * @param metadatas Array or single object of metadata corresponding to the texts.\n * @param embeddings `Embeddings` instance used to generate embeddings for the texts.\n * @param dbConfig Optional `MemoryVectorStoreArgs` to configure the `MemoryVectorStore` instance.\n * @returns Promise that resolves with a new `MemoryVectorStore` instance.\n */\n static async fromTexts(\n texts: string[],\n metadatas: object[] | object,\n embeddings: EmbeddingsInterface,\n dbConfig?: MemoryVectorStoreArgs\n ): Promise<MemoryVectorStore> {\n const docs: Document[] = [];\n for (let i = 0; i < texts.length; i += 1) {\n const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;\n const newDoc = new Document({\n pageContent: texts[i],\n metadata,\n });\n docs.push(newDoc);\n }\n return MemoryVectorStore.fromDocuments(docs, embeddings, dbConfig);\n }\n\n /**\n * Static method to create a `MemoryVectorStore` instance from an array of\n * `Document` instances. It adds the documents to the store.\n * @param docs Array of `Document` instances to be added to the store.\n * @param embeddings `Embeddings` instance used to generate embeddings for the documents.\n * @param dbConfig Optional `MemoryVectorStoreArgs` to configure the `MemoryVectorStore` instance.\n * @returns Promise that resolves with a new `MemoryVectorStore` instance.\n */\n static async fromDocuments(\n docs: Document[],\n embeddings: EmbeddingsInterface,\n dbConfig?: MemoryVectorStoreArgs\n ): Promise<MemoryVectorStore> {\n const instance = new this(embeddings, dbConfig);\n await instance.addDocuments(docs);\n return instance;\n }\n\n /**\n * Static method to create a `MemoryVectorStore` instance from an existing\n * index. It creates a new `MemoryVectorStore` instance without adding any\n * documents or vectors.\n * @param embeddings `Embeddings` instance used to generate embeddings for the documents.\n * @param dbConfig Optional `MemoryVectorStoreArgs` to configure the `MemoryVectorStore` instance.\n * @returns Promise that resolves with a new `MemoryVectorStore` instance.\n */\n static async fromExistingIndex(\n embeddings: EmbeddingsInterface,\n dbConfig?: MemoryVectorStoreArgs\n ): Promise<MemoryVectorStore> {\n const instance = new this(embeddings, dbConfig);\n return instance;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;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MAAM,KAAK,cAAc,OAAO,GAAG,OAAO,EACb,KAAK,WAAW,CAC5D,IAAI,SAAS;GACX,UAAU,OAAO;GACjB,aAAa,OAAO;GACpB,IAAI,OAAO;GACZ,CAAC,EACF,OAAO,WACR,CAAC;;CAKJ,MAAM,2BACJ,OACA,SAC8B;EAC9B,MAAM,iBAAiB,MAAM,KAAK,WAAW,WAAW,MAAM;EAE9D,MAAM,WAAW,MAAM,KAAK,cAC1B,gBACA,QAAQ,UAAU,IAClB,QAAQ,OACT;AAWD,SAPmB,yBACjB,gBAHoB,SAAS,KAAK,eAAe,WAAW,UAAU,EAKtE,QAAQ,QACR,QAAQ,EACT,CAEiB,KACf,QACC,IAAI,SAAS;GACX,UAAU,SAAS,KAAK;GACxB,aAAa,SAAS,KAAK;GAC3B,IAAI,SAAS,KAAK;GACnB,CAAC,CACL;;;;;;;;;;;;CAaH,aAAa,UACX,OACA,WACA,YACA,UAC4B;EAC5B,MAAM,OAAmB,EAAE;AAC3B,OAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,GAAG;GACxC,MAAM,WAAW,MAAM,QAAQ,UAAU,GAAG,UAAU,KAAK;GAC3D,MAAM,SAAS,IAAI,SAAS;IAC1B,aAAa,MAAM;IACnB;IACD,CAAC;AACF,QAAK,KAAK,OAAO;;AAEnB,SAAO,kBAAkB,cAAc,MAAM,YAAY,SAAS;;;;;;;;;;CAWpE,aAAa,cACX,MACA,YACA,UAC4B;EAC5B,MAAM,WAAW,IAAI,KAAK,YAAY,SAAS;AAC/C,QAAM,SAAS,aAAa,KAAK;AACjC,SAAO;;;;;;;;;;CAWT,aAAa,kBACX,YACA,UAC4B;AAE5B,SADiB,IAAI,KAAK,YAAY,SAAS"}
1
+ {"version":3,"file":"memory.js","names":[],"sources":["../../src/vectorstores/memory.ts"],"sourcesContent":["import {\n MaxMarginalRelevanceSearchOptions,\n VectorStore,\n} from \"@langchain/core/vectorstores\";\nimport type { EmbeddingsInterface } from \"@langchain/core/embeddings\";\nimport { Document, DocumentInterface } from \"@langchain/core/documents\";\nimport { maximalMarginalRelevance } from \"@langchain/core/utils/math\";\nimport { cosine } from \"../util/ml-distance/similarities.js\";\n\n/**\n * Interface representing a vector in memory. It includes the content\n * (text), the corresponding embedding (vector), and any associated\n * metadata.\n */\ninterface MemoryVector {\n content: string;\n embedding: number[];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n id?: string;\n}\n\n/**\n * Interface for the arguments that can be passed to the\n * `MemoryVectorStore` constructor. It includes an optional `similarity`\n * function.\n */\nexport interface MemoryVectorStoreArgs {\n similarity?: typeof cosine;\n}\n\n/**\n * In-memory, ephemeral vector store.\n *\n * Setup:\n * Install `langchain`:\n *\n * ```bash\n * npm install langchain\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/langchain.vectorstores_memory.MemoryVectorStore.html#constructor)\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { MemoryVectorStore } from 'langchain/vectorstores/memory';\n * // Or other embeddings\n * import { OpenAIEmbeddings } from '@langchain/openai';\n *\n * const embeddings = new OpenAIEmbeddings({\n * model: \"text-embedding-3-small\",\n * });\n *\n * const vectorStore = new MemoryVectorStore(embeddings);\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Add documents</strong></summary>\n *\n * ```typescript\n * import type { Document } from '@langchain/core/documents';\n *\n * const document1 = { pageContent: \"foo\", metadata: { baz: \"bar\" } };\n * const document2 = { pageContent: \"thud\", metadata: { bar: \"baz\" } };\n * const document3 = { pageContent: \"i will be deleted :(\", metadata: {} };\n *\n * const documents: Document[] = [document1, document2, document3];\n *\n * await vectorStore.addDocuments(documents);\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Similarity search</strong></summary>\n *\n * ```typescript\n * const results = await vectorStore.similaritySearch(\"thud\", 1);\n * for (const doc of results) {\n * console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n * }\n * // Output: * thud [{\"baz\":\"bar\"}]\n * ```\n * </details>\n *\n * <br />\n *\n *\n * <details>\n * <summary><strong>Similarity search with filter</strong></summary>\n *\n * ```typescript\n * const resultsWithFilter = await vectorStore.similaritySearch(\"thud\", 1, { baz: \"bar\" });\n *\n * for (const doc of resultsWithFilter) {\n * console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n * }\n * // Output: * foo [{\"baz\":\"bar\"}]\n * ```\n * </details>\n *\n * <br />\n *\n *\n * <details>\n * <summary><strong>Similarity search with score</strong></summary>\n *\n * ```typescript\n * const resultsWithScore = await vectorStore.similaritySearchWithScore(\"qux\", 1);\n * for (const [doc, score] of resultsWithScore) {\n * console.log(`* [SIM=${score.toFixed(6)}] ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n * }\n * // Output: * [SIM=0.000000] qux [{\"bar\":\"baz\",\"baz\":\"bar\"}]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>As a retriever</strong></summary>\n *\n * ```typescript\n * const retriever = vectorStore.asRetriever({\n * searchType: \"mmr\", // Leave blank for standard similarity search\n * k: 1,\n * });\n * const resultAsRetriever = await retriever.invoke(\"thud\");\n * console.log(resultAsRetriever);\n *\n * // Output: [Document({ metadata: { \"baz\":\"bar\" }, pageContent: \"thud\" })]\n * ```\n * </details>\n *\n * <br />\n */\nexport class MemoryVectorStore extends VectorStore {\n declare FilterType: (doc: Document) => boolean;\n\n memoryVectors: MemoryVector[] = [];\n\n similarity: typeof cosine;\n\n _vectorstoreType(): string {\n return \"memory\";\n }\n\n constructor(\n embeddings: EmbeddingsInterface,\n { similarity, ...rest }: MemoryVectorStoreArgs = {}\n ) {\n super(embeddings, rest);\n\n this.similarity = similarity ?? cosine;\n }\n\n /**\n * Method to add documents to the memory vector store. It extracts the\n * text from each document, generates embeddings for them, and adds the\n * resulting vectors to the store.\n * @param documents Array of `Document` instances to be added to the store.\n * @returns Promise that resolves when all documents have been added.\n */\n async addDocuments(documents: Document[]): Promise<void> {\n const texts = documents.map(({ pageContent }) => pageContent);\n return this.addVectors(\n await this.embeddings.embedDocuments(texts),\n documents\n );\n }\n\n /**\n * Method to add vectors to the memory vector store. It creates\n * `MemoryVector` instances for each vector and document pair and adds\n * them to the store.\n * @param vectors Array of vectors to be added to the store.\n * @param documents Array of `Document` instances corresponding to the vectors.\n * @returns Promise that resolves when all vectors have been added.\n */\n async addVectors(vectors: number[][], documents: Document[]): Promise<void> {\n const memoryVectors = vectors.map((embedding, idx) => ({\n content: documents[idx].pageContent,\n embedding,\n metadata: documents[idx].metadata,\n id: documents[idx].id,\n }));\n\n this.memoryVectors = this.memoryVectors.concat(memoryVectors);\n }\n\n protected async _queryVectors(\n query: number[],\n k: number,\n filter?: this[\"FilterType\"]\n ) {\n const filterFunction = (memoryVector: MemoryVector) => {\n if (!filter) {\n return true;\n }\n\n const doc = new Document({\n metadata: memoryVector.metadata,\n pageContent: memoryVector.content,\n id: memoryVector.id,\n });\n return filter(doc);\n };\n const filteredMemoryVectors = this.memoryVectors.filter(filterFunction);\n return filteredMemoryVectors\n .map((vector, index) => ({\n similarity: this.similarity(query, vector.embedding),\n index,\n metadata: vector.metadata,\n content: vector.content,\n embedding: vector.embedding,\n id: vector.id,\n }))\n .sort((a, b) => (a.similarity > b.similarity ? -1 : 0))\n .slice(0, k);\n }\n\n /**\n * Method to perform a similarity search in the memory vector store. It\n * calculates the similarity between the query vector and each vector in\n * the store, sorts the results by similarity, and returns the top `k`\n * results along with their scores.\n * @param query Query vector to compare against the vectors in the store.\n * @param k Number of top results to return.\n * @param filter Optional filter function to apply to the vectors before performing the search.\n * @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score.\n */\n async similaritySearchVectorWithScore(\n query: number[],\n k: number,\n filter?: this[\"FilterType\"]\n ): Promise<[Document, number][]> {\n const searches = await this._queryVectors(query, k, filter);\n const result: [Document, number][] = searches.map((search) => [\n new Document({\n metadata: search.metadata,\n pageContent: search.content,\n id: search.id,\n }),\n search.similarity,\n ]);\n\n return result;\n }\n\n async maxMarginalRelevanceSearch(\n query: string,\n options: MaxMarginalRelevanceSearchOptions<this[\"FilterType\"]>\n ): Promise<DocumentInterface[]> {\n const queryEmbedding = await this.embeddings.embedQuery(query);\n\n const searches = await this._queryVectors(\n queryEmbedding,\n options.fetchK ?? 20,\n options.filter\n );\n\n const embeddingList = searches.map((searchResp) => searchResp.embedding);\n\n const mmrIndexes = maximalMarginalRelevance(\n queryEmbedding,\n embeddingList,\n options.lambda,\n options.k\n );\n\n return mmrIndexes.map(\n (idx) =>\n new Document({\n metadata: searches[idx].metadata,\n pageContent: searches[idx].content,\n id: searches[idx].id,\n })\n );\n }\n\n /**\n * Static method to create a `MemoryVectorStore` instance from an array of\n * texts. It creates a `Document` for each text and metadata pair, and\n * adds them to the store.\n * @param texts Array of texts to be added to the store.\n * @param metadatas Array or single object of metadata corresponding to the texts.\n * @param embeddings `Embeddings` instance used to generate embeddings for the texts.\n * @param dbConfig Optional `MemoryVectorStoreArgs` to configure the `MemoryVectorStore` instance.\n * @returns Promise that resolves with a new `MemoryVectorStore` instance.\n */\n static async fromTexts(\n texts: string[],\n metadatas: object[] | object,\n embeddings: EmbeddingsInterface,\n dbConfig?: MemoryVectorStoreArgs\n ): Promise<MemoryVectorStore> {\n const docs: Document[] = [];\n for (let i = 0; i < texts.length; i += 1) {\n const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;\n const newDoc = new Document({\n pageContent: texts[i],\n metadata,\n });\n docs.push(newDoc);\n }\n return MemoryVectorStore.fromDocuments(docs, embeddings, dbConfig);\n }\n\n /**\n * Static method to create a `MemoryVectorStore` instance from an array of\n * `Document` instances. It adds the documents to the store.\n * @param docs Array of `Document` instances to be added to the store.\n * @param embeddings `Embeddings` instance used to generate embeddings for the documents.\n * @param dbConfig Optional `MemoryVectorStoreArgs` to configure the `MemoryVectorStore` instance.\n * @returns Promise that resolves with a new `MemoryVectorStore` instance.\n */\n static async fromDocuments(\n docs: Document[],\n embeddings: EmbeddingsInterface,\n dbConfig?: MemoryVectorStoreArgs\n ): Promise<MemoryVectorStore> {\n const instance = new this(embeddings, dbConfig);\n await instance.addDocuments(docs);\n return instance;\n }\n\n /**\n * Static method to create a `MemoryVectorStore` instance from an existing\n * index. It creates a new `MemoryVectorStore` instance without adding any\n * documents or vectors.\n * @param embeddings `Embeddings` instance used to generate embeddings for the documents.\n * @param dbConfig Optional `MemoryVectorStoreArgs` to configure the `MemoryVectorStore` instance.\n * @returns Promise that resolves with a new `MemoryVectorStore` instance.\n */\n static async fromExistingIndex(\n embeddings: EmbeddingsInterface,\n dbConfig?: MemoryVectorStoreArgs\n ): Promise<MemoryVectorStore> {\n const instance = new this(embeddings, dbConfig);\n return instance;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6IA,IAAa,oBAAb,MAAa,0BAA0B,YAAY;CAGjD,gBAAgC,EAAE;CAElC;CAEA,mBAA2B;AACzB,SAAO;;CAGT,YACE,YACA,EAAE,YAAY,GAAG,SAAgC,EAAE,EACnD;AACA,QAAM,YAAY,KAAK;AAEvB,OAAK,aAAa,cAAc;;;;;;;;;CAUlC,MAAM,aAAa,WAAsC;EACvD,MAAM,QAAQ,UAAU,KAAK,EAAE,kBAAkB,YAAY;AAC7D,SAAO,KAAK,WACV,MAAM,KAAK,WAAW,eAAe,MAAM,EAC3C,UACD;;;;;;;;;;CAWH,MAAM,WAAW,SAAqB,WAAsC;EAC1E,MAAM,gBAAgB,QAAQ,KAAK,WAAW,SAAS;GACrD,SAAS,UAAU,KAAK;GACxB;GACA,UAAU,UAAU,KAAK;GACzB,IAAI,UAAU,KAAK;GACpB,EAAE;AAEH,OAAK,gBAAgB,KAAK,cAAc,OAAO,cAAc;;CAG/D,MAAgB,c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