@langchain/core 1.2.0-dev-1775763803878 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +130 -0
- package/README.md +1 -1
- package/agents.cjs +1 -0
- package/agents.d.cts +1 -0
- package/agents.d.ts +1 -0
- package/agents.js +1 -0
- package/caches.cjs +1 -0
- package/caches.d.cts +1 -0
- package/caches.d.ts +1 -0
- package/caches.js +1 -0
- package/callbacks/base.cjs +1 -0
- package/callbacks/base.d.cts +1 -0
- package/callbacks/base.d.ts +1 -0
- package/callbacks/base.js +1 -0
- package/callbacks/dispatch/web.cjs +1 -0
- package/callbacks/dispatch/web.d.cts +1 -0
- package/callbacks/dispatch/web.d.ts +1 -0
- package/callbacks/dispatch/web.js +1 -0
- package/callbacks/dispatch.cjs +1 -0
- package/callbacks/dispatch.d.cts +1 -0
- package/callbacks/dispatch.d.ts +1 -0
- package/callbacks/dispatch.js +1 -0
- package/callbacks/manager.cjs +1 -0
- package/callbacks/manager.d.cts +1 -0
- package/callbacks/manager.d.ts +1 -0
- package/callbacks/manager.js +1 -0
- package/callbacks/promises.cjs +1 -0
- package/callbacks/promises.d.cts +1 -0
- package/callbacks/promises.d.ts +1 -0
- package/callbacks/promises.js +1 -0
- package/chat_history.cjs +1 -0
- package/chat_history.d.cts +1 -0
- package/chat_history.d.ts +1 -0
- package/chat_history.js +1 -0
- package/context.cjs +1 -0
- package/context.d.cts +1 -0
- package/context.d.ts +1 -0
- package/context.js +1 -0
- package/dist/callbacks/base.cjs +7 -3
- package/dist/callbacks/base.cjs.map +1 -1
- package/dist/callbacks/base.d.cts +20 -1
- package/dist/callbacks/base.d.cts.map +1 -1
- package/dist/callbacks/base.d.ts +20 -1
- package/dist/callbacks/base.d.ts.map +1 -1
- package/dist/callbacks/base.js +7 -3
- package/dist/callbacks/base.js.map +1 -1
- package/dist/callbacks/dispatch/index.cjs.map +1 -1
- package/dist/callbacks/dispatch/index.js.map +1 -1
- package/dist/callbacks/manager.cjs +29 -7
- package/dist/callbacks/manager.cjs.map +1 -1
- package/dist/callbacks/manager.d.cts +4 -0
- package/dist/callbacks/manager.d.cts.map +1 -1
- package/dist/callbacks/manager.d.ts +4 -0
- package/dist/callbacks/manager.d.ts.map +1 -1
- package/dist/callbacks/manager.js +23 -1
- package/dist/callbacks/manager.js.map +1 -1
- package/dist/example_selectors/conditional.cjs.map +1 -1
- package/dist/example_selectors/conditional.js.map +1 -1
- package/dist/example_selectors/length_based.cjs.map +1 -1
- package/dist/example_selectors/length_based.js.map +1 -1
- package/dist/example_selectors/semantic_similarity.cjs.map +1 -1
- package/dist/example_selectors/semantic_similarity.js.map +1 -1
- package/dist/indexing/base.cjs +3 -4
- package/dist/indexing/base.cjs.map +1 -1
- package/dist/indexing/base.js +1 -1
- package/dist/indexing/base.js.map +1 -1
- package/dist/language_models/base.cjs +9 -1
- package/dist/language_models/base.cjs.map +1 -1
- package/dist/language_models/base.d.cts +5 -0
- package/dist/language_models/base.d.cts.map +1 -1
- package/dist/language_models/base.d.ts +5 -0
- package/dist/language_models/base.d.ts.map +1 -1
- package/dist/language_models/base.js +9 -1
- package/dist/language_models/base.js.map +1 -1
- package/dist/language_models/chat_models.cjs +71 -33
- package/dist/language_models/chat_models.cjs.map +1 -1
- package/dist/language_models/chat_models.d.cts +74 -3
- package/dist/language_models/chat_models.d.cts.map +1 -1
- package/dist/language_models/chat_models.d.ts +74 -3
- package/dist/language_models/chat_models.d.ts.map +1 -1
- package/dist/language_models/chat_models.js +72 -34
- package/dist/language_models/chat_models.js.map +1 -1
- package/dist/language_models/compat.cjs +255 -78
- package/dist/language_models/compat.cjs.map +1 -1
- package/dist/language_models/compat.d.cts +3 -17
- package/dist/language_models/compat.d.cts.map +1 -1
- package/dist/language_models/compat.d.ts +3 -17
- package/dist/language_models/compat.d.ts.map +1 -1
- package/dist/language_models/compat.js +256 -78
- package/dist/language_models/compat.js.map +1 -1
- package/dist/language_models/event.cjs.map +1 -1
- package/dist/language_models/event.d.cts +82 -90
- package/dist/language_models/event.d.cts.map +1 -1
- package/dist/language_models/event.d.ts +82 -90
- package/dist/language_models/event.d.ts.map +1 -1
- package/dist/language_models/event.js.map +1 -1
- package/dist/language_models/llms.cjs +18 -6
- package/dist/language_models/llms.cjs.map +1 -1
- package/dist/language_models/llms.d.cts.map +1 -1
- package/dist/language_models/llms.d.ts.map +1 -1
- package/dist/language_models/llms.js +18 -6
- package/dist/language_models/llms.js.map +1 -1
- package/dist/language_models/openai_completions_stream.cjs +308 -0
- package/dist/language_models/openai_completions_stream.cjs.map +1 -0
- package/dist/language_models/openai_completions_stream.d.cts +75 -0
- package/dist/language_models/openai_completions_stream.d.cts.map +1 -0
- package/dist/language_models/openai_completions_stream.d.ts +75 -0
- package/dist/language_models/openai_completions_stream.d.ts.map +1 -0
- package/dist/language_models/openai_completions_stream.js +301 -0
- package/dist/language_models/openai_completions_stream.js.map +1 -0
- package/dist/language_models/stream.cjs +216 -86
- package/dist/language_models/stream.cjs.map +1 -1
- package/dist/language_models/stream.d.cts +5 -28
- package/dist/language_models/stream.d.cts.map +1 -1
- package/dist/language_models/stream.d.ts +5 -28
- package/dist/language_models/stream.d.ts.map +1 -1
- package/dist/language_models/stream.js +216 -86
- package/dist/language_models/stream.js.map +1 -1
- package/dist/load/import_map.cjs +4 -0
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +4 -0
- package/dist/load/import_map.js.map +1 -1
- package/dist/load/index.cjs +19 -0
- package/dist/load/index.cjs.map +1 -1
- package/dist/load/index.d.cts +4 -0
- package/dist/load/index.d.cts.map +1 -1
- package/dist/load/index.d.ts +4 -0
- package/dist/load/index.d.ts.map +1 -1
- package/dist/load/index.js +19 -0
- package/dist/load/index.js.map +1 -1
- package/dist/load/map_keys.cjs +13 -7
- package/dist/load/map_keys.cjs.map +1 -1
- package/dist/load/map_keys.d.cts.map +1 -1
- package/dist/load/map_keys.d.ts.map +1 -1
- package/dist/load/map_keys.js +11 -2
- package/dist/load/map_keys.js.map +1 -1
- package/dist/memory.cjs.map +1 -1
- package/dist/memory.js.map +1 -1
- package/dist/messages/ai.cjs +12 -9
- package/dist/messages/ai.cjs.map +1 -1
- package/dist/messages/ai.d.cts.map +1 -1
- package/dist/messages/ai.d.ts.map +1 -1
- package/dist/messages/ai.js +12 -9
- package/dist/messages/ai.js.map +1 -1
- package/dist/messages/base.cjs +10 -0
- package/dist/messages/base.cjs.map +1 -1
- package/dist/messages/base.d.cts +9 -0
- package/dist/messages/base.d.cts.map +1 -1
- package/dist/messages/base.d.ts +9 -0
- package/dist/messages/base.d.ts.map +1 -1
- package/dist/messages/base.js +10 -0
- package/dist/messages/base.js.map +1 -1
- package/dist/messages/block_translators/anthropic.cjs.map +1 -1
- package/dist/messages/block_translators/anthropic.js.map +1 -1
- package/dist/messages/block_translators/bedrock_converse.cjs.map +1 -1
- package/dist/messages/block_translators/bedrock_converse.js.map +1 -1
- package/dist/messages/block_translators/google.cjs.map +1 -1
- package/dist/messages/block_translators/google.js.map +1 -1
- package/dist/messages/block_translators/google_vertexai.cjs.map +1 -1
- package/dist/messages/block_translators/google_vertexai.js.map +1 -1
- package/dist/messages/block_translators/index.cjs +2 -0
- package/dist/messages/block_translators/index.cjs.map +1 -1
- package/dist/messages/block_translators/index.js +2 -0
- package/dist/messages/block_translators/index.js.map +1 -1
- package/dist/messages/block_translators/openai.cjs.map +1 -1
- package/dist/messages/block_translators/openai.js.map +1 -1
- package/dist/messages/block_translators/openrouter.cjs +101 -0
- package/dist/messages/block_translators/openrouter.cjs.map +1 -0
- package/dist/messages/block_translators/openrouter.js +101 -0
- package/dist/messages/block_translators/openrouter.js.map +1 -0
- package/dist/messages/index.d.cts +2 -2
- package/dist/messages/index.d.ts +2 -2
- package/dist/messages/modifier.cjs +6 -0
- package/dist/messages/modifier.cjs.map +1 -1
- package/dist/messages/modifier.d.cts +9 -4
- package/dist/messages/modifier.d.cts.map +1 -1
- package/dist/messages/modifier.d.ts +9 -4
- package/dist/messages/modifier.d.ts.map +1 -1
- package/dist/messages/modifier.js +6 -0
- package/dist/messages/modifier.js.map +1 -1
- package/dist/messages/transformers.cjs.map +1 -1
- package/dist/messages/transformers.js.map +1 -1
- package/dist/messages/utils.cjs +16 -2
- package/dist/messages/utils.cjs.map +1 -1
- package/dist/messages/utils.d.cts +9 -1
- package/dist/messages/utils.d.cts.map +1 -1
- package/dist/messages/utils.d.ts +9 -1
- package/dist/messages/utils.d.ts.map +1 -1
- package/dist/messages/utils.js +16 -2
- package/dist/messages/utils.js.map +1 -1
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.cjs.map +1 -1
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.js.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.js.map +1 -1
- package/dist/output_parsers/standard_schema.cjs +3 -0
- package/dist/output_parsers/standard_schema.cjs.map +1 -1
- package/dist/output_parsers/standard_schema.d.cts +2 -0
- package/dist/output_parsers/standard_schema.d.cts.map +1 -1
- package/dist/output_parsers/standard_schema.d.ts +2 -0
- package/dist/output_parsers/standard_schema.d.ts.map +1 -1
- package/dist/output_parsers/standard_schema.js +3 -0
- package/dist/output_parsers/standard_schema.js.map +1 -1
- package/dist/output_parsers/structured.cjs +3 -0
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/output_parsers/structured.d.cts +2 -0
- package/dist/output_parsers/structured.d.cts.map +1 -1
- package/dist/output_parsers/structured.d.ts +2 -0
- package/dist/output_parsers/structured.d.ts.map +1 -1
- package/dist/output_parsers/structured.js +3 -0
- package/dist/output_parsers/structured.js.map +1 -1
- package/dist/output_parsers/xml.cjs.map +1 -1
- package/dist/output_parsers/xml.js.map +1 -1
- package/dist/prompts/base.cjs.map +1 -1
- package/dist/prompts/base.js.map +1 -1
- package/dist/prompts/chat.cjs.map +1 -1
- package/dist/prompts/chat.js.map +1 -1
- package/dist/prompts/few_shot.cjs.map +1 -1
- package/dist/prompts/few_shot.js.map +1 -1
- package/dist/prompts/image.cjs.map +1 -1
- package/dist/prompts/image.js.map +1 -1
- package/dist/prompts/prompt.cjs +1 -1
- package/dist/prompts/prompt.cjs.map +1 -1
- package/dist/prompts/prompt.d.cts +1 -1
- package/dist/prompts/prompt.d.ts +1 -1
- package/dist/prompts/prompt.js +1 -1
- package/dist/prompts/prompt.js.map +1 -1
- package/dist/prompts/string.cjs.map +1 -1
- package/dist/prompts/string.js.map +1 -1
- package/dist/prompts/template.cjs +1 -1
- package/dist/prompts/template.cjs.map +1 -1
- package/dist/prompts/template.js.map +1 -1
- package/dist/retrievers/index.cjs.map +1 -1
- package/dist/retrievers/index.js.map +1 -1
- package/dist/runnables/base.cjs +5 -2
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.d.cts +43 -0
- package/dist/runnables/base.d.cts.map +1 -1
- package/dist/runnables/base.d.ts +43 -0
- package/dist/runnables/base.d.ts.map +1 -1
- package/dist/runnables/base.js +4 -1
- package/dist/runnables/base.js.map +1 -1
- package/dist/runnables/branch.cjs.map +1 -1
- package/dist/runnables/branch.js.map +1 -1
- package/dist/runnables/config.cjs +16 -8
- package/dist/runnables/config.cjs.map +1 -1
- package/dist/runnables/config.d.cts.map +1 -1
- package/dist/runnables/config.d.ts.map +1 -1
- package/dist/runnables/config.js +16 -8
- package/dist/runnables/config.js.map +1 -1
- package/dist/runnables/graph.cjs +6 -6
- package/dist/runnables/graph.cjs.map +1 -1
- package/dist/runnables/graph.js +1 -1
- package/dist/runnables/graph.js.map +1 -1
- package/dist/runnables/graph_mermaid.cjs.map +1 -1
- package/dist/runnables/graph_mermaid.js.map +1 -1
- package/dist/runnables/history.cjs +3 -0
- package/dist/runnables/history.cjs.map +1 -1
- package/dist/runnables/history.d.cts +3 -0
- package/dist/runnables/history.d.cts.map +1 -1
- package/dist/runnables/history.d.ts +3 -0
- package/dist/runnables/history.d.ts.map +1 -1
- package/dist/runnables/history.js +3 -0
- package/dist/runnables/history.js.map +1 -1
- package/dist/runnables/router.cjs.map +1 -1
- package/dist/runnables/router.js.map +1 -1
- package/dist/runnables/utils.cjs.map +1 -1
- package/dist/runnables/utils.js.map +1 -1
- package/dist/singletons/async_local_storage/context.cjs.map +1 -1
- package/dist/singletons/async_local_storage/context.js.map +1 -1
- package/dist/singletons/async_local_storage/index.cjs.map +1 -1
- package/dist/singletons/async_local_storage/index.js.map +1 -1
- package/dist/singletons/callbacks.cjs +1 -1
- package/dist/testing/fake_model_builder.cjs +10 -9
- package/dist/testing/fake_model_builder.cjs.map +1 -1
- package/dist/testing/fake_model_builder.d.cts +1 -2
- package/dist/testing/fake_model_builder.d.cts.map +1 -1
- package/dist/testing/fake_model_builder.d.ts +1 -2
- package/dist/testing/fake_model_builder.d.ts.map +1 -1
- package/dist/testing/fake_model_builder.js +10 -9
- package/dist/testing/fake_model_builder.js.map +1 -1
- package/dist/testing/index.cjs +16 -0
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +3 -1
- package/dist/testing/index.d.ts +3 -1
- package/dist/testing/index.js +10 -1
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/matchers.cjs +3 -1
- package/dist/testing/matchers.cjs.map +1 -1
- package/dist/testing/matchers.d.cts +8 -4
- package/dist/testing/matchers.d.cts.map +1 -1
- package/dist/testing/matchers.d.ts +8 -4
- package/dist/testing/matchers.d.ts.map +1 -1
- package/dist/testing/matchers.js +3 -1
- package/dist/testing/matchers.js.map +1 -1
- package/dist/tools/index.cjs +4 -1
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.d.cts.map +1 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +4 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tracers/console.cjs +30 -4
- package/dist/tracers/console.cjs.map +1 -1
- package/dist/tracers/console.d.cts.map +1 -1
- package/dist/tracers/console.d.ts.map +1 -1
- package/dist/tracers/console.js +28 -1
- package/dist/tracers/console.js.map +1 -1
- package/dist/tracers/event_stream.cjs.map +1 -1
- package/dist/tracers/event_stream.js.map +1 -1
- package/dist/tracers/tracer_langchain.cjs +70 -2
- package/dist/tracers/tracer_langchain.cjs.map +1 -1
- package/dist/tracers/tracer_langchain.d.cts +26 -1
- package/dist/tracers/tracer_langchain.d.cts.map +1 -1
- package/dist/tracers/tracer_langchain.d.ts +26 -1
- package/dist/tracers/tracer_langchain.d.ts.map +1 -1
- package/dist/tracers/tracer_langchain.js +70 -3
- package/dist/tracers/tracer_langchain.js.map +1 -1
- package/dist/utils/async_caller.cjs +132 -8
- package/dist/utils/async_caller.cjs.map +1 -1
- package/dist/utils/async_caller.d.cts +9 -1
- package/dist/utils/async_caller.d.cts.map +1 -1
- package/dist/utils/async_caller.d.ts +9 -1
- package/dist/utils/async_caller.d.ts.map +1 -1
- package/dist/utils/async_caller.js +130 -8
- package/dist/utils/async_caller.js.map +1 -1
- package/dist/utils/callbacks.cjs.map +1 -1
- package/dist/utils/callbacks.js.map +1 -1
- package/dist/utils/context.cjs.map +1 -1
- package/dist/utils/context.js.map +1 -1
- package/dist/utils/env.cjs.map +1 -1
- package/dist/utils/env.d.cts.map +1 -1
- package/dist/utils/env.d.ts.map +1 -1
- package/dist/utils/env.js.map +1 -1
- package/dist/utils/event_source_parse.cjs +5 -12
- package/dist/utils/event_source_parse.cjs.map +1 -1
- package/dist/utils/event_source_parse.js +5 -12
- package/dist/utils/event_source_parse.js.map +1 -1
- package/dist/utils/fast-json-patch/src/core.cjs.map +1 -1
- package/dist/utils/fast-json-patch/src/core.js.map +1 -1
- package/dist/utils/json_schema.cjs.map +1 -1
- package/dist/utils/json_schema.js.map +1 -1
- package/dist/utils/p-retry/index.cjs +3 -1
- package/dist/utils/p-retry/index.cjs.map +1 -1
- package/dist/utils/p-retry/index.js +3 -1
- package/dist/utils/p-retry/index.js.map +1 -1
- package/dist/utils/sax-js/sax.cjs.map +1 -1
- package/dist/utils/sax-js/sax.js.map +1 -1
- package/dist/utils/ssrf.cjs.map +1 -1
- package/dist/utils/ssrf.js.map +1 -1
- package/dist/utils/stream.d.cts +2 -2
- package/dist/utils/stream.d.cts.map +1 -1
- package/dist/utils/stream.d.ts +2 -2
- package/dist/utils/stream.d.ts.map +1 -1
- package/dist/utils/testing/chat_models.cjs.map +1 -1
- package/dist/utils/testing/chat_models.js.map +1 -1
- package/dist/utils/testing/embeddings.cjs.map +1 -1
- package/dist/utils/testing/embeddings.js.map +1 -1
- package/dist/utils/testing/index.cjs +17 -1
- package/dist/utils/testing/index.cjs.map +1 -1
- package/dist/utils/testing/index.d.cts +3 -1
- package/dist/utils/testing/index.d.ts +3 -1
- package/dist/utils/testing/index.js +11 -2
- package/dist/utils/testing/index.js.map +1 -1
- package/dist/utils/testing/openai_stream_fixtures.cjs +160 -0
- package/dist/utils/testing/openai_stream_fixtures.cjs.map +1 -0
- package/dist/utils/testing/openai_stream_fixtures.d.cts +12 -0
- package/dist/utils/testing/openai_stream_fixtures.d.cts.map +1 -0
- package/dist/utils/testing/openai_stream_fixtures.d.ts +12 -0
- package/dist/utils/testing/openai_stream_fixtures.d.ts.map +1 -0
- package/dist/utils/testing/openai_stream_fixtures.js +155 -0
- package/dist/utils/testing/openai_stream_fixtures.js.map +1 -0
- package/dist/utils/testing/stream.cjs +136 -0
- package/dist/utils/testing/stream.cjs.map +1 -0
- package/dist/utils/testing/stream.d.cts +96 -0
- package/dist/utils/testing/stream.d.cts.map +1 -0
- package/dist/utils/testing/stream.d.ts +96 -0
- package/dist/utils/testing/stream.d.ts.map +1 -0
- package/dist/utils/testing/stream.js +136 -0
- package/dist/utils/testing/stream.js.map +1 -0
- package/dist/utils/testing/vectorstores.cjs.map +1 -1
- package/dist/utils/testing/vectorstores.js.map +1 -1
- package/dist/utils/types/zod.cjs.map +1 -1
- package/dist/utils/types/zod.js.map +1 -1
- package/dist/utils/uuid/index.cjs +58 -0
- package/dist/utils/uuid/index.cjs.map +1 -0
- package/dist/utils/uuid/index.d.cts +26 -0
- package/dist/utils/uuid/index.d.cts.map +1 -0
- package/dist/utils/uuid/index.d.ts +26 -0
- package/dist/utils/uuid/index.d.ts.map +1 -0
- package/dist/utils/uuid/index.js +41 -0
- package/dist/utils/uuid/index.js.map +1 -0
- package/dist/utils/uuid/max.cjs +6 -0
- package/dist/utils/uuid/max.cjs.map +1 -0
- package/dist/utils/uuid/max.js +6 -0
- package/dist/utils/uuid/max.js.map +1 -0
- package/dist/utils/uuid/nil.cjs +6 -0
- package/dist/utils/uuid/nil.cjs.map +1 -0
- package/dist/utils/uuid/nil.js +6 -0
- package/dist/utils/uuid/nil.js.map +1 -0
- package/dist/utils/uuid/parse.cjs +11 -0
- package/dist/utils/uuid/parse.cjs.map +1 -0
- package/dist/utils/uuid/parse.d.cts +7 -0
- package/dist/utils/uuid/parse.d.cts.map +1 -0
- package/dist/utils/uuid/parse.d.ts +7 -0
- package/dist/utils/uuid/parse.d.ts.map +1 -0
- package/dist/utils/uuid/parse.js +11 -0
- package/dist/utils/uuid/parse.js.map +1 -0
- package/dist/utils/uuid/regex.cjs +6 -0
- package/dist/utils/uuid/regex.cjs.map +1 -0
- package/dist/utils/uuid/regex.js +6 -0
- package/dist/utils/uuid/regex.js.map +1 -0
- package/dist/utils/uuid/rng.cjs +9 -0
- package/dist/utils/uuid/rng.cjs.map +1 -0
- package/dist/utils/uuid/rng.js +9 -0
- package/dist/utils/uuid/rng.js.map +1 -0
- package/dist/utils/uuid/sha1.cjs +71 -0
- package/dist/utils/uuid/sha1.cjs.map +1 -0
- package/dist/utils/uuid/sha1.js +71 -0
- package/dist/utils/uuid/sha1.js.map +1 -0
- package/dist/utils/uuid/stringify.cjs +21 -0
- package/dist/utils/uuid/stringify.cjs.map +1 -0
- package/dist/utils/uuid/stringify.d.cts +5 -0
- package/dist/utils/uuid/stringify.d.cts.map +1 -0
- package/dist/utils/uuid/stringify.d.ts +5 -0
- package/dist/utils/uuid/stringify.d.ts.map +1 -0
- package/dist/utils/uuid/stringify.js +20 -0
- package/dist/utils/uuid/stringify.js.map +1 -0
- package/dist/utils/uuid/types.d.cts +26 -0
- package/dist/utils/uuid/types.d.cts.map +1 -0
- package/dist/utils/uuid/types.d.ts +26 -0
- package/dist/utils/uuid/types.d.ts.map +1 -0
- package/dist/utils/uuid/v1.cjs +69 -0
- package/dist/utils/uuid/v1.cjs.map +1 -0
- package/dist/utils/uuid/v1.d.cts +8 -0
- package/dist/utils/uuid/v1.d.cts.map +1 -0
- package/dist/utils/uuid/v1.d.ts +8 -0
- package/dist/utils/uuid/v1.d.ts.map +1 -0
- package/dist/utils/uuid/v1.js +69 -0
- package/dist/utils/uuid/v1.js.map +1 -0
- package/dist/utils/uuid/v1ToV6.cjs +14 -0
- package/dist/utils/uuid/v1ToV6.cjs.map +1 -0
- package/dist/utils/uuid/v1ToV6.js +14 -0
- package/dist/utils/uuid/v1ToV6.js.map +1 -0
- package/dist/utils/uuid/v35.cjs +36 -0
- package/dist/utils/uuid/v35.cjs.map +1 -0
- package/dist/utils/uuid/v35.js +34 -0
- package/dist/utils/uuid/v35.js.map +1 -0
- package/dist/utils/uuid/v4.cjs +25 -0
- package/dist/utils/uuid/v4.cjs.map +1 -0
- package/dist/utils/uuid/v4.d.cts +8 -0
- package/dist/utils/uuid/v4.d.cts.map +1 -0
- package/dist/utils/uuid/v4.d.ts +8 -0
- package/dist/utils/uuid/v4.d.ts.map +1 -0
- package/dist/utils/uuid/v4.js +25 -0
- package/dist/utils/uuid/v4.js.map +1 -0
- package/dist/utils/uuid/v5.cjs +12 -0
- package/dist/utils/uuid/v5.cjs.map +1 -0
- package/dist/utils/uuid/v5.d.cts +14 -0
- package/dist/utils/uuid/v5.d.cts.map +1 -0
- package/dist/utils/uuid/v5.d.ts +14 -0
- package/dist/utils/uuid/v5.d.ts.map +1 -0
- package/dist/utils/uuid/v5.js +12 -0
- package/dist/utils/uuid/v5.js.map +1 -0
- package/dist/utils/uuid/v6.cjs +23 -0
- package/dist/utils/uuid/v6.cjs.map +1 -0
- package/dist/utils/uuid/v6.d.cts +8 -0
- package/dist/utils/uuid/v6.d.cts.map +1 -0
- package/dist/utils/uuid/v6.d.ts +8 -0
- package/dist/utils/uuid/v6.d.ts.map +1 -0
- package/dist/utils/uuid/v6.js +23 -0
- package/dist/utils/uuid/v6.js.map +1 -0
- package/dist/utils/uuid/v7.cjs +57 -0
- package/dist/utils/uuid/v7.cjs.map +1 -0
- package/dist/utils/uuid/v7.d.cts +8 -0
- package/dist/utils/uuid/v7.d.cts.map +1 -0
- package/dist/utils/uuid/v7.d.ts +8 -0
- package/dist/utils/uuid/v7.d.ts.map +1 -0
- package/dist/utils/uuid/v7.js +57 -0
- package/dist/utils/uuid/v7.js.map +1 -0
- package/dist/utils/uuid/validate.cjs +9 -0
- package/dist/utils/uuid/validate.cjs.map +1 -0
- package/dist/utils/uuid/validate.d.cts +5 -0
- package/dist/utils/uuid/validate.d.cts.map +1 -0
- package/dist/utils/uuid/validate.d.ts +5 -0
- package/dist/utils/uuid/validate.d.ts.map +1 -0
- package/dist/utils/uuid/validate.js +9 -0
- package/dist/utils/uuid/validate.js.map +1 -0
- package/dist/utils/uuid/version.cjs +10 -0
- package/dist/utils/uuid/version.cjs.map +1 -0
- package/dist/utils/uuid/version.d.cts +5 -0
- package/dist/utils/uuid/version.d.cts.map +1 -0
- package/dist/utils/uuid/version.d.ts +5 -0
- package/dist/utils/uuid/version.d.ts.map +1 -0
- package/dist/utils/uuid/version.js +10 -0
- package/dist/utils/uuid/version.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/nativeEnum.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/nativeEnum.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/pipeline.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/pipeline.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/set.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/set.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/string.cjs +26 -0
- package/dist/utils/zod-to-json-schema/parsers/string.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/string.js +26 -0
- package/dist/utils/zod-to-json-schema/parsers/string.js.map +1 -1
- package/dist/vectorstores.cjs.map +1 -1
- package/dist/vectorstores.js.map +1 -1
- package/document_loaders/base.cjs +1 -0
- package/document_loaders/base.d.cts +1 -0
- package/document_loaders/base.d.ts +1 -0
- package/document_loaders/base.js +1 -0
- package/document_loaders/langsmith.cjs +1 -0
- package/document_loaders/langsmith.d.cts +1 -0
- package/document_loaders/langsmith.d.ts +1 -0
- package/document_loaders/langsmith.js +1 -0
- package/documents.cjs +1 -0
- package/documents.d.cts +1 -0
- package/documents.d.ts +1 -0
- package/documents.js +1 -0
- package/embeddings.cjs +1 -0
- package/embeddings.d.cts +1 -0
- package/embeddings.d.ts +1 -0
- package/embeddings.js +1 -0
- package/errors.cjs +1 -0
- package/errors.d.cts +1 -0
- package/errors.d.ts +1 -0
- package/errors.js +1 -0
- package/example_selectors.cjs +1 -0
- package/example_selectors.d.cts +1 -0
- package/example_selectors.d.ts +1 -0
- package/example_selectors.js +1 -0
- package/indexing.cjs +1 -0
- package/indexing.d.cts +1 -0
- package/indexing.d.ts +1 -0
- package/indexing.js +1 -0
- package/language_models/base.cjs +1 -0
- package/language_models/base.d.cts +1 -0
- package/language_models/base.d.ts +1 -0
- package/language_models/base.js +1 -0
- package/language_models/chat_models.cjs +1 -0
- package/language_models/chat_models.d.cts +1 -0
- package/language_models/chat_models.d.ts +1 -0
- package/language_models/chat_models.js +1 -0
- package/language_models/compat.cjs +1 -0
- package/language_models/compat.d.cts +1 -0
- package/language_models/compat.d.ts +1 -0
- package/language_models/compat.js +1 -0
- package/language_models/event.cjs +1 -0
- package/language_models/event.d.cts +1 -0
- package/language_models/event.d.ts +1 -0
- package/language_models/event.js +1 -0
- package/language_models/llms.cjs +1 -0
- package/language_models/llms.d.cts +1 -0
- package/language_models/llms.d.ts +1 -0
- package/language_models/llms.js +1 -0
- package/language_models/openai_completions_stream.cjs +1 -0
- package/language_models/openai_completions_stream.d.cts +1 -0
- package/language_models/openai_completions_stream.d.ts +1 -0
- package/language_models/openai_completions_stream.js +1 -0
- package/language_models/profile.cjs +1 -0
- package/language_models/profile.d.cts +1 -0
- package/language_models/profile.d.ts +1 -0
- package/language_models/profile.js +1 -0
- package/language_models/stream.cjs +1 -0
- package/language_models/stream.d.cts +1 -0
- package/language_models/stream.d.ts +1 -0
- package/language_models/stream.js +1 -0
- package/language_models/structured_output.cjs +1 -0
- package/language_models/structured_output.d.cts +1 -0
- package/language_models/structured_output.d.ts +1 -0
- package/language_models/structured_output.js +1 -0
- package/load/serializable.cjs +1 -0
- package/load/serializable.d.cts +1 -0
- package/load/serializable.d.ts +1 -0
- package/load/serializable.js +1 -0
- package/load.cjs +1 -0
- package/load.d.cts +1 -0
- package/load.d.ts +1 -0
- package/load.js +1 -0
- package/memory.cjs +1 -0
- package/memory.d.cts +1 -0
- package/memory.d.ts +1 -0
- package/memory.js +1 -0
- package/messages/tool.cjs +1 -0
- package/messages/tool.d.cts +1 -0
- package/messages/tool.d.ts +1 -0
- package/messages/tool.js +1 -0
- package/messages.cjs +1 -0
- package/messages.d.cts +1 -0
- package/messages.d.ts +1 -0
- package/messages.js +1 -0
- package/output_parsers/openai_functions.cjs +1 -0
- package/output_parsers/openai_functions.d.cts +1 -0
- package/output_parsers/openai_functions.d.ts +1 -0
- package/output_parsers/openai_functions.js +1 -0
- package/output_parsers/openai_tools.cjs +1 -0
- package/output_parsers/openai_tools.d.cts +1 -0
- package/output_parsers/openai_tools.d.ts +1 -0
- package/output_parsers/openai_tools.js +1 -0
- package/output_parsers.cjs +1 -0
- package/output_parsers.d.cts +1 -0
- package/output_parsers.d.ts +1 -0
- package/output_parsers.js +1 -0
- package/outputs.cjs +1 -0
- package/outputs.d.cts +1 -0
- package/outputs.d.ts +1 -0
- package/outputs.js +1 -0
- package/package.json +34 -14
- package/prompt_values.cjs +1 -0
- package/prompt_values.d.cts +1 -0
- package/prompt_values.d.ts +1 -0
- package/prompt_values.js +1 -0
- package/prompts.cjs +1 -0
- package/prompts.d.cts +1 -0
- package/prompts.d.ts +1 -0
- package/prompts.js +1 -0
- package/retrievers/document_compressors.cjs +1 -0
- package/retrievers/document_compressors.d.cts +1 -0
- package/retrievers/document_compressors.d.ts +1 -0
- package/retrievers/document_compressors.js +1 -0
- package/retrievers.cjs +1 -0
- package/retrievers.d.cts +1 -0
- package/retrievers.d.ts +1 -0
- package/retrievers.js +1 -0
- package/runnables/graph.cjs +1 -0
- package/runnables/graph.d.cts +1 -0
- package/runnables/graph.d.ts +1 -0
- package/runnables/graph.js +1 -0
- package/runnables.cjs +1 -0
- package/runnables.d.cts +1 -0
- package/runnables.d.ts +1 -0
- package/runnables.js +1 -0
- package/singletons.cjs +1 -0
- package/singletons.d.cts +1 -0
- package/singletons.d.ts +1 -0
- package/singletons.js +1 -0
- package/stores.cjs +1 -0
- package/stores.d.cts +1 -0
- package/stores.d.ts +1 -0
- package/stores.js +1 -0
- package/structured_query.cjs +1 -0
- package/structured_query.d.cts +1 -0
- package/structured_query.d.ts +1 -0
- package/structured_query.js +1 -0
- package/testing.cjs +1 -0
- package/testing.d.cts +1 -0
- package/testing.d.ts +1 -0
- package/testing.js +1 -0
- package/tools.cjs +1 -0
- package/tools.d.cts +1 -0
- package/tools.d.ts +1 -0
- package/tools.js +1 -0
- package/tracers/base.cjs +1 -0
- package/tracers/base.d.cts +1 -0
- package/tracers/base.d.ts +1 -0
- package/tracers/base.js +1 -0
- package/tracers/console.cjs +1 -0
- package/tracers/console.d.cts +1 -0
- package/tracers/console.d.ts +1 -0
- package/tracers/console.js +1 -0
- package/tracers/log_stream.cjs +1 -0
- package/tracers/log_stream.d.cts +1 -0
- package/tracers/log_stream.d.ts +1 -0
- package/tracers/log_stream.js +1 -0
- package/tracers/run_collector.cjs +1 -0
- package/tracers/run_collector.d.cts +1 -0
- package/tracers/run_collector.d.ts +1 -0
- package/tracers/run_collector.js +1 -0
- package/tracers/tracer_langchain.cjs +1 -0
- package/tracers/tracer_langchain.d.cts +1 -0
- package/tracers/tracer_langchain.d.ts +1 -0
- package/tracers/tracer_langchain.js +1 -0
- package/types/stream.cjs +1 -0
- package/types/stream.d.cts +1 -0
- package/types/stream.d.ts +1 -0
- package/types/stream.js +1 -0
- package/utils/async_caller.cjs +1 -0
- package/utils/async_caller.d.cts +1 -0
- package/utils/async_caller.d.ts +1 -0
- package/utils/async_caller.js +1 -0
- package/utils/chunk_array.cjs +1 -0
- package/utils/chunk_array.d.cts +1 -0
- package/utils/chunk_array.d.ts +1 -0
- package/utils/chunk_array.js +1 -0
- package/utils/context.cjs +1 -0
- package/utils/context.d.cts +1 -0
- package/utils/context.d.ts +1 -0
- package/utils/context.js +1 -0
- package/utils/env.cjs +1 -0
- package/utils/env.d.cts +1 -0
- package/utils/env.d.ts +1 -0
- package/utils/env.js +1 -0
- package/utils/event_source_parse.cjs +1 -0
- package/utils/event_source_parse.d.cts +1 -0
- package/utils/event_source_parse.d.ts +1 -0
- package/utils/event_source_parse.js +1 -0
- package/utils/format.cjs +1 -0
- package/utils/format.d.cts +1 -0
- package/utils/format.d.ts +1 -0
- package/utils/format.js +1 -0
- package/utils/function_calling.cjs +1 -0
- package/utils/function_calling.d.cts +1 -0
- package/utils/function_calling.d.ts +1 -0
- package/utils/function_calling.js +1 -0
- package/utils/hash.cjs +1 -0
- package/utils/hash.d.cts +1 -0
- package/utils/hash.d.ts +1 -0
- package/utils/hash.js +1 -0
- package/utils/json_patch.cjs +1 -0
- package/utils/json_patch.d.cts +1 -0
- package/utils/json_patch.d.ts +1 -0
- package/utils/json_patch.js +1 -0
- package/utils/json_schema.cjs +1 -0
- package/utils/json_schema.d.cts +1 -0
- package/utils/json_schema.d.ts +1 -0
- package/utils/json_schema.js +1 -0
- package/utils/math.cjs +1 -0
- package/utils/math.d.cts +1 -0
- package/utils/math.d.ts +1 -0
- package/utils/math.js +1 -0
- package/utils/ssrf.cjs +1 -0
- package/utils/ssrf.d.cts +1 -0
- package/utils/ssrf.d.ts +1 -0
- package/utils/ssrf.js +1 -0
- package/utils/standard_schema.cjs +1 -0
- package/utils/standard_schema.d.cts +1 -0
- package/utils/standard_schema.d.ts +1 -0
- package/utils/standard_schema.js +1 -0
- package/utils/stream.cjs +1 -0
- package/utils/stream.d.cts +1 -0
- package/utils/stream.d.ts +1 -0
- package/utils/stream.js +1 -0
- package/utils/testing.cjs +1 -0
- package/utils/testing.d.cts +1 -0
- package/utils/testing.d.ts +1 -0
- package/utils/testing.js +1 -0
- package/utils/tiktoken.cjs +1 -0
- package/utils/tiktoken.d.cts +1 -0
- package/utils/tiktoken.d.ts +1 -0
- package/utils/tiktoken.js +1 -0
- package/utils/types.cjs +1 -0
- package/utils/types.d.cts +1 -0
- package/utils/types.d.ts +1 -0
- package/utils/types.js +1 -0
- package/utils/uuid.cjs +1 -0
- package/utils/uuid.d.cts +1 -0
- package/utils/uuid.d.ts +1 -0
- package/utils/uuid.js +1 -0
- package/vectorstores.cjs +1 -0
- package/vectorstores.d.cts +1 -0
- package/vectorstores.d.ts +1 -0
- package/vectorstores.js +1 -0
|
@@ -37,13 +37,6 @@ async function getBytes(stream, onChunk) {
|
|
|
37
37
|
].join("\n"));
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
|
-
var ControlChars = /* @__PURE__ */ function(ControlChars) {
|
|
41
|
-
ControlChars[ControlChars["NewLine"] = 10] = "NewLine";
|
|
42
|
-
ControlChars[ControlChars["CarriageReturn"] = 13] = "CarriageReturn";
|
|
43
|
-
ControlChars[ControlChars["Space"] = 32] = "Space";
|
|
44
|
-
ControlChars[ControlChars["Colon"] = 58] = "Colon";
|
|
45
|
-
return ControlChars;
|
|
46
|
-
}(ControlChars || {});
|
|
47
40
|
/**
|
|
48
41
|
* Parses arbitary byte chunks into EventSource line buffers.
|
|
49
42
|
* Each line should be of the format "field: value" and ends with \r, \n, or \r\n.
|
|
@@ -69,16 +62,16 @@ function getLines(onLine) {
|
|
|
69
62
|
let lineStart = 0;
|
|
70
63
|
while (position < bufLength) {
|
|
71
64
|
if (discardTrailingNewline) {
|
|
72
|
-
if (buffer[position] ===
|
|
65
|
+
if (buffer[position] === 10) lineStart = ++position;
|
|
73
66
|
discardTrailingNewline = false;
|
|
74
67
|
}
|
|
75
68
|
let lineEnd = -1;
|
|
76
69
|
for (; position < bufLength && lineEnd === -1; ++position) switch (buffer[position]) {
|
|
77
|
-
case
|
|
70
|
+
case 58:
|
|
78
71
|
if (fieldLength === -1) fieldLength = position - lineStart;
|
|
79
72
|
break;
|
|
80
|
-
case
|
|
81
|
-
case
|
|
73
|
+
case 13: discardTrailingNewline = true;
|
|
74
|
+
case 10:
|
|
82
75
|
lineEnd = position;
|
|
83
76
|
break;
|
|
84
77
|
}
|
|
@@ -117,7 +110,7 @@ function getMessages(onMessage, onId, onRetry) {
|
|
|
117
110
|
message = newMessage();
|
|
118
111
|
} else if (fieldLength > 0) {
|
|
119
112
|
const field = decoder.decode(line.subarray(0, fieldLength));
|
|
120
|
-
const valueOffset = fieldLength + (line[fieldLength + 1] ===
|
|
113
|
+
const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1);
|
|
121
114
|
const value = decoder.decode(line.subarray(valueOffset));
|
|
122
115
|
switch (field) {
|
|
123
116
|
case "data":
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event_source_parse.js","names":[],"sources":["../../src/utils/event_source_parse.ts"],"sourcesContent":["/* oxlint-disable prefer-template */\n/* oxlint-disable default-case */\n// Adapted from https://github.com/gfortaine/fetch-event-source/blob/main/src/parse.ts\n// due to a packaging issue in the original.\n// MIT License\nimport { IterableReadableStream } from \"./stream.js\";\n\nexport const EventStreamContentType = \"text/event-stream\";\n\n/**\n * Represents a message sent in an event stream\n * https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format\n */\nexport interface EventSourceMessage {\n /** The event ID to set the EventSource object's last event ID value. */\n id: string;\n /** A string identifying the type of event described. */\n event: string;\n /** The event data */\n data: string;\n /** The reconnection interval (in milliseconds) to wait before retrying the connection */\n retry?: number;\n}\n\n/**\n * Converts a ReadableStream into a callback pattern.\n * @param stream The input ReadableStream.\n * @param onChunk A function that will be called on each new byte chunk in the stream.\n * @returns {Promise<void>} A promise that will be resolved when the stream closes.\n */\nexport async function getBytes(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n stream: ReadableStream<Uint8Array> | AsyncIterable<any>,\n onChunk: (arr: Uint8Array, flush?: boolean) => void\n) {\n // TODO: Use Async iteration for both cases?\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (stream instanceof ReadableStream) {\n const reader = stream.getReader();\n // CHANGED: Introduced a \"flush\" mechanism to process potential pending messages when the stream ends.\n // This change is essential to ensure that we capture every last piece of information from streams,\n // such as those from Azure OpenAI, which may not terminate with a blank line. Without this\n // mechanism, we risk ignoring a possibly significant last message.\n // See https://github.com/langchain-ai/langchainjs/issues/1299 for details.\n while (true) {\n const result = await reader.read();\n if (result.done) {\n onChunk(new Uint8Array(), true);\n break;\n }\n onChunk(result.value);\n }\n } else {\n try {\n // Handle Node.js Readable streams with async iteration\n for await (const chunk of stream) {\n onChunk(new Uint8Array(chunk));\n }\n onChunk(new Uint8Array(), true);\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new Error(\n [\n \"Parsing event source stream failed.\",\n \"Ensure your implementation of fetch returns a web or Node readable stream.\",\n `Error: ${e.message}`,\n ].join(\"\\n\")\n );\n }\n }\n}\n\nconst enum ControlChars {\n NewLine = 10,\n CarriageReturn = 13,\n Space = 32,\n Colon = 58,\n}\n\n/**\n * Parses arbitary byte chunks into EventSource line buffers.\n * Each line should be of the format \"field: value\" and ends with \\r, \\n, or \\r\\n.\n * @param onLine A function that will be called on each new EventSource line.\n * @returns A function that should be called for each incoming byte chunk.\n */\nexport function getLines(\n onLine: (line: Uint8Array, fieldLength: number, flush?: boolean) => void\n) {\n let buffer: Uint8Array | undefined;\n let position: number; // current read position\n let fieldLength: number; // length of the `field` portion of the line\n let discardTrailingNewline = false;\n\n // return a function that can process each incoming byte chunk:\n return function onChunk(arr: Uint8Array, flush?: boolean) {\n if (flush) {\n onLine(arr, 0, true);\n return;\n }\n\n if (buffer === undefined) {\n buffer = arr;\n position = 0;\n fieldLength = -1;\n } else {\n // we're still parsing the old line. Append the new bytes into buffer:\n buffer = concat(buffer, arr);\n }\n\n const bufLength = buffer.length;\n let lineStart = 0; // index where the current line starts\n while (position < bufLength) {\n if (discardTrailingNewline) {\n if (buffer[position] === ControlChars.NewLine) {\n lineStart = ++position; // skip to next char\n }\n\n discardTrailingNewline = false;\n }\n\n // start looking forward till the end of line:\n let lineEnd = -1; // index of the \\r or \\n char\n for (; position < bufLength && lineEnd === -1; ++position) {\n switch (buffer[position]) {\n case ControlChars.Colon:\n if (fieldLength === -1) {\n // first colon in line\n fieldLength = position - lineStart;\n }\n break;\n // @ts-expect-error \\r case below should fallthrough to \\n:\n case ControlChars.CarriageReturn:\n discardTrailingNewline = true;\n // oxlint-disable-next-line no-fallthrough\n case ControlChars.NewLine:\n lineEnd = position;\n break;\n }\n }\n\n if (lineEnd === -1) {\n // We reached the end of the buffer but the line hasn't ended.\n // Wait for the next arr and then continue parsing:\n break;\n }\n\n // we've reached the line end, send it out:\n onLine(buffer.subarray(lineStart, lineEnd), fieldLength);\n lineStart = position; // we're now on the next line\n fieldLength = -1;\n }\n\n if (lineStart === bufLength) {\n buffer = undefined; // we've finished reading it\n } else if (lineStart !== 0) {\n // Create a new view into buffer beginning at lineStart so we don't\n // need to copy over the previous lines when we get the new arr:\n buffer = buffer.subarray(lineStart);\n position -= lineStart;\n }\n };\n}\n\n/**\n * Parses line buffers into EventSourceMessages.\n * @param onId A function that will be called on each `id` field.\n * @param onRetry A function that will be called on each `retry` field.\n * @param onMessage A function that will be called on each message.\n * @returns A function that should be called for each incoming line buffer.\n */\nexport function getMessages(\n onMessage?: (msg: EventSourceMessage) => void,\n onId?: (id: string) => void,\n onRetry?: (retry: number) => void\n) {\n let message = newMessage();\n const decoder = new TextDecoder();\n\n // return a function that can process each incoming line buffer:\n return function onLine(\n line: Uint8Array,\n fieldLength: number,\n flush?: boolean\n ) {\n if (flush) {\n if (!isEmpty(message)) {\n onMessage?.(message);\n message = newMessage();\n }\n return;\n }\n\n if (line.length === 0) {\n // empty line denotes end of message. Trigger the callback and start a new message:\n onMessage?.(message);\n message = newMessage();\n } else if (fieldLength > 0) {\n // exclude comments and lines with no values\n // line is of format \"<field>:<value>\" or \"<field>: <value>\"\n // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation\n const field = decoder.decode(line.subarray(0, fieldLength));\n const valueOffset =\n fieldLength + (line[fieldLength + 1] === ControlChars.Space ? 2 : 1);\n const value = decoder.decode(line.subarray(valueOffset));\n\n switch (field) {\n case \"data\":\n // if this message already has data, append the new value to the old.\n // otherwise, just set to the new value:\n message.data = message.data ? message.data + \"\\n\" + value : value; // otherwise,\n break;\n case \"event\":\n message.event = value;\n break;\n case \"id\":\n onId?.((message.id = value));\n break;\n case \"retry\": {\n const retry = parseInt(value, 10);\n if (!Number.isNaN(retry)) {\n // per spec, ignore non-integers\n onRetry?.((message.retry = retry));\n }\n break;\n }\n }\n }\n };\n}\n\nfunction concat(a: Uint8Array, b: Uint8Array) {\n const res = new Uint8Array(a.length + b.length);\n res.set(a);\n res.set(b, a.length);\n return res;\n}\n\nfunction newMessage(): EventSourceMessage {\n // data, event, and id must be initialized to empty strings:\n // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation\n // retry should be initialized to undefined so we return a consistent shape\n // to the js engine all the time: https://mathiasbynens.be/notes/shapes-ics#takeaways\n return {\n data: \"\",\n event: \"\",\n id: \"\",\n retry: undefined,\n };\n}\n\nexport function convertEventStreamToIterableReadableDataStream(\n stream: ReadableStream,\n onMetadataEvent?: (e: unknown) => unknown\n) {\n const dataStream = new ReadableStream({\n async start(controller) {\n const enqueueLine = getMessages((msg) => {\n if (msg.event === \"error\") {\n throw new Error(msg.data ?? \"Unspecified event streaming error.\");\n } else if (msg.event === \"metadata\") {\n onMetadataEvent?.(msg);\n } else {\n if (msg.data) controller.enqueue(msg.data);\n }\n });\n const onLine = (\n line: Uint8Array,\n fieldLength: number,\n flush?: boolean\n ) => {\n enqueueLine(line, fieldLength, flush);\n if (flush) controller.close();\n };\n await getBytes(stream, getLines(onLine));\n },\n });\n return IterableReadableStream.fromReadableStream(dataStream);\n}\n\nfunction isEmpty(message: EventSourceMessage): boolean {\n return (\n message.data === \"\" &&\n message.event === \"\" &&\n message.id === \"\" &&\n message.retry === undefined\n );\n}\n"],"mappings":";;;;;;;;;;AAOA,MAAa,yBAAyB;;;;;;;AAuBtC,eAAsB,SAEpB,QACA,SACA;AAGA,KAAI,kBAAkB,gBAAgB;EACpC,MAAM,SAAS,OAAO,WAAW;AAMjC,SAAO,MAAM;GACX,MAAM,SAAS,MAAM,OAAO,MAAM;AAClC,OAAI,OAAO,MAAM;AACf,YAAQ,IAAI,YAAY,EAAE,KAAK;AAC/B;;AAEF,WAAQ,OAAO,MAAM;;OAGvB,KAAI;AAEF,aAAW,MAAM,SAAS,OACxB,SAAQ,IAAI,WAAW,MAAM,CAAC;AAEhC,UAAQ,IAAI,YAAY,EAAE,KAAK;UAExB,GAAQ;AACf,QAAM,IAAI,MACR;GACE;GACA;GACA,UAAU,EAAE;GACb,CAAC,KAAK,KAAK,CACb;;;AAKP,IAAW,eAAX,yBAAA,cAAA;AACE,cAAA,aAAA,aAAA,MAAA;AACA,cAAA,aAAA,oBAAA,MAAA;AACA,cAAA,aAAA,WAAA,MAAA;AACA,cAAA,aAAA,WAAA,MAAA;;EAJS,gBAAA,EAAA,CAKV;;;;;;;AAQD,SAAgB,SACd,QACA;CACA,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,yBAAyB;AAG7B,QAAO,SAAS,QAAQ,KAAiB,OAAi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-template */\n/* oxlint-disable default-case */\n// Adapted from https://github.com/gfortaine/fetch-event-source/blob/main/src/parse.ts\n// due to a packaging issue in the original.\n// MIT License\nimport { IterableReadableStream } from \"./stream.js\";\n\nexport const EventStreamContentType = \"text/event-stream\";\n\n/**\n * Represents a message sent in an event stream\n * https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format\n */\nexport interface EventSourceMessage {\n /** The event ID to set the EventSource object's last event ID value. */\n id: string;\n /** A string identifying the type of event described. */\n event: string;\n /** The event data */\n data: string;\n /** The reconnection interval (in milliseconds) to wait before retrying the connection */\n retry?: number;\n}\n\n/**\n * Converts a ReadableStream into a callback pattern.\n * @param stream The input ReadableStream.\n * @param onChunk A function that will be called on each new byte chunk in the stream.\n * @returns {Promise<void>} A promise that will be resolved when the stream closes.\n */\nexport async function getBytes(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n stream: ReadableStream<Uint8Array> | AsyncIterable<any>,\n onChunk: (arr: Uint8Array, flush?: boolean) => void\n) {\n // TODO: Use Async iteration for both cases?\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (stream instanceof ReadableStream) {\n const reader = stream.getReader();\n // CHANGED: Introduced a \"flush\" mechanism to process potential pending messages when the stream ends.\n // This change is essential to ensure that we capture every last piece of information from streams,\n // such as those from Azure OpenAI, which may not terminate with a blank line. Without this\n // mechanism, we risk ignoring a possibly significant last message.\n // See https://github.com/langchain-ai/langchainjs/issues/1299 for details.\n while (true) {\n const result = await reader.read();\n if (result.done) {\n onChunk(new Uint8Array(), true);\n break;\n }\n onChunk(result.value);\n }\n } else {\n try {\n // Handle Node.js Readable streams with async iteration\n for await (const chunk of stream) {\n onChunk(new Uint8Array(chunk));\n }\n onChunk(new Uint8Array(), true);\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new Error(\n [\n \"Parsing event source stream failed.\",\n \"Ensure your implementation of fetch returns a web or Node readable stream.\",\n `Error: ${e.message}`,\n ].join(\"\\n\")\n );\n }\n }\n}\n\nconst enum ControlChars {\n NewLine = 10,\n CarriageReturn = 13,\n Space = 32,\n Colon = 58,\n}\n\n/**\n * Parses arbitary byte chunks into EventSource line buffers.\n * Each line should be of the format \"field: value\" and ends with \\r, \\n, or \\r\\n.\n * @param onLine A function that will be called on each new EventSource line.\n * @returns A function that should be called for each incoming byte chunk.\n */\nexport function getLines(\n onLine: (line: Uint8Array, fieldLength: number, flush?: boolean) => void\n) {\n let buffer: Uint8Array | undefined;\n let position: number; // current read position\n let fieldLength: number; // length of the `field` portion of the line\n let discardTrailingNewline = false;\n\n // return a function that can process each incoming byte chunk:\n return function onChunk(arr: Uint8Array, flush?: boolean) {\n if (flush) {\n onLine(arr, 0, true);\n return;\n }\n\n if (buffer === undefined) {\n buffer = arr;\n position = 0;\n fieldLength = -1;\n } else {\n // we're still parsing the old line. Append the new bytes into buffer:\n buffer = concat(buffer, arr);\n }\n\n const bufLength = buffer.length;\n let lineStart = 0; // index where the current line starts\n while (position < bufLength) {\n if (discardTrailingNewline) {\n if (buffer[position] === ControlChars.NewLine) {\n lineStart = ++position; // skip to next char\n }\n\n discardTrailingNewline = false;\n }\n\n // start looking forward till the end of line:\n let lineEnd = -1; // index of the \\r or \\n char\n for (; position < bufLength && lineEnd === -1; ++position) {\n switch (buffer[position]) {\n case ControlChars.Colon:\n if (fieldLength === -1) {\n // first colon in line\n fieldLength = position - lineStart;\n }\n break;\n // @ts-expect-error \\r case below should fallthrough to \\n:\n case ControlChars.CarriageReturn:\n discardTrailingNewline = true;\n // oxlint-disable-next-line no-fallthrough\n case ControlChars.NewLine:\n lineEnd = position;\n break;\n }\n }\n\n if (lineEnd === -1) {\n // We reached the end of the buffer but the line hasn't ended.\n // Wait for the next arr and then continue parsing:\n break;\n }\n\n // we've reached the line end, send it out:\n onLine(buffer.subarray(lineStart, lineEnd), fieldLength);\n lineStart = position; // we're now on the next line\n fieldLength = -1;\n }\n\n if (lineStart === bufLength) {\n buffer = undefined; // we've finished reading it\n } else if (lineStart !== 0) {\n // Create a new view into buffer beginning at lineStart so we don't\n // need to copy over the previous lines when we get the new arr:\n buffer = buffer.subarray(lineStart);\n position -= lineStart;\n }\n };\n}\n\n/**\n * Parses line buffers into EventSourceMessages.\n * @param onId A function that will be called on each `id` field.\n * @param onRetry A function that will be called on each `retry` field.\n * @param onMessage A function that will be called on each message.\n * @returns A function that should be called for each incoming line buffer.\n */\nexport function getMessages(\n onMessage?: (msg: EventSourceMessage) => void,\n onId?: (id: string) => void,\n onRetry?: (retry: number) => void\n) {\n let message = newMessage();\n const decoder = new TextDecoder();\n\n // return a function that can process each incoming line buffer:\n return function onLine(\n line: Uint8Array,\n fieldLength: number,\n flush?: boolean\n ) {\n if (flush) {\n if (!isEmpty(message)) {\n onMessage?.(message);\n message = newMessage();\n }\n return;\n }\n\n if (line.length === 0) {\n // empty line denotes end of message. Trigger the callback and start a new message:\n onMessage?.(message);\n message = newMessage();\n } else if (fieldLength > 0) {\n // exclude comments and lines with no values\n // line is of format \"<field>:<value>\" or \"<field>: <value>\"\n // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation\n const field = decoder.decode(line.subarray(0, fieldLength));\n const valueOffset =\n fieldLength + (line[fieldLength + 1] === ControlChars.Space ? 2 : 1);\n const value = decoder.decode(line.subarray(valueOffset));\n\n switch (field) {\n case \"data\":\n // if this message already has data, append the new value to the old.\n // otherwise, just set to the new value:\n message.data = message.data ? message.data + \"\\n\" + value : value; // otherwise,\n break;\n case \"event\":\n message.event = value;\n break;\n case \"id\":\n onId?.((message.id = value));\n break;\n case \"retry\": {\n const retry = parseInt(value, 10);\n if (!Number.isNaN(retry)) {\n // per spec, ignore non-integers\n onRetry?.((message.retry = retry));\n }\n break;\n }\n }\n }\n };\n}\n\nfunction concat(a: Uint8Array, b: Uint8Array) {\n const res = new Uint8Array(a.length + b.length);\n res.set(a);\n res.set(b, a.length);\n return res;\n}\n\nfunction newMessage(): EventSourceMessage {\n // data, event, and id must be initialized to empty strings:\n // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation\n // retry should be initialized to undefined so we return a consistent shape\n // to the js engine all the time: https://mathiasbynens.be/notes/shapes-ics#takeaways\n return {\n data: \"\",\n event: \"\",\n id: \"\",\n retry: undefined,\n };\n}\n\nexport function convertEventStreamToIterableReadableDataStream(\n stream: ReadableStream,\n onMetadataEvent?: (e: unknown) => unknown\n) {\n const dataStream = new ReadableStream({\n async start(controller) {\n const enqueueLine = getMessages((msg) => {\n if (msg.event === \"error\") {\n throw new Error(msg.data ?? \"Unspecified event streaming error.\");\n } else if (msg.event === \"metadata\") {\n onMetadataEvent?.(msg);\n } else {\n if (msg.data) controller.enqueue(msg.data);\n }\n });\n const onLine = (\n line: Uint8Array,\n fieldLength: number,\n flush?: boolean\n ) => {\n enqueueLine(line, fieldLength, flush);\n if (flush) controller.close();\n };\n await getBytes(stream, getLines(onLine));\n },\n });\n return IterableReadableStream.fromReadableStream(dataStream);\n}\n\nfunction isEmpty(message: EventSourceMessage): boolean {\n return (\n message.data === \"\" &&\n message.event === \"\" &&\n message.id === \"\" &&\n message.retry === undefined\n );\n}\n"],"mappings":";;;;;;;;;;AAOA,MAAa,yBAAyB;;;;;;;AAuBtC,eAAsB,SAEpB,QACA,SACA;AAGA,KAAI,kBAAkB,gBAAgB;EACpC,MAAM,SAAS,OAAO,WAAW;AAMjC,SAAO,MAAM;GACX,MAAM,SAAS,MAAM,OAAO,MAAM;AAClC,OAAI,OAAO,MAAM;AACf,YAAQ,IAAI,YAAY,EAAE,KAAK;AAC/B;;AAEF,WAAQ,OAAO,MAAM;;OAGvB,KAAI;AAEF,aAAW,MAAM,SAAS,OACxB,SAAQ,IAAI,WAAW,MAAM,CAAC;AAEhC,UAAQ,IAAI,YAAY,EAAE,KAAK;UAExB,GAAQ;AACf,QAAM,IAAI,MACR;GACE;GACA;GACA,UAAU,EAAE;GACb,CAAC,KAAK,KAAK,CACb;;;;;;;;;AAkBP,S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
|
|
|
1
|
-
{"version":3,"file":"core.cjs","names":["PatchError","_deepClone","isInteger","unescapePathComponent","hasUndefined"],"sources":["../../../../src/utils/fast-json-patch/src/core.ts"],"sourcesContent":["// @ts-nocheck\n\n// Inlined because of ESM import issues\n\n/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2013-2021 Joachim Wester\n * MIT license\n */\ndeclare var require: any;\n\nimport {\n PatchError,\n _deepClone,\n isInteger,\n unescapePathComponent,\n hasUndefined,\n} from \"./helpers.js\";\n\nexport const JsonPatchError = PatchError;\nexport const deepClone = _deepClone;\n\nexport type Operation =\n | AddOperation<any>\n | RemoveOperation\n | ReplaceOperation<any>\n | MoveOperation\n | CopyOperation\n | TestOperation<any>\n | GetOperation<any>;\n\nexport interface Validator<T> {\n (\n operation: Operation,\n index: number,\n document: T,\n existingPathFragment: string\n ): void;\n}\n\nexport interface OperationResult<T> {\n removed?: any;\n test?: boolean;\n newDocument: T;\n}\n\nexport interface BaseOperation {\n path: string;\n}\n\nexport interface AddOperation<T> extends BaseOperation {\n op: \"add\";\n value: T;\n}\n\nexport interface RemoveOperation extends BaseOperation {\n op: \"remove\";\n}\n\nexport interface ReplaceOperation<T> extends BaseOperation {\n op: \"replace\";\n value: T;\n}\n\nexport interface MoveOperation extends BaseOperation {\n op: \"move\";\n from: string;\n}\n\nexport interface CopyOperation extends BaseOperation {\n op: \"copy\";\n from: string;\n}\n\nexport interface TestOperation<T> extends BaseOperation {\n op: \"test\";\n value: T;\n}\n\nexport interface GetOperation<T> extends BaseOperation {\n op: \"_get\";\n value: T;\n}\nexport interface PatchResult<T> extends Array<OperationResult<T>> {\n newDocument: T;\n}\n\n/* We use a Javascript hash to store each\n function. Each hash entry (property) uses\n the operation identifiers specified in rfc6902.\n In this way, we can map each patch operation\n to its dedicated function in efficient way.\n */\n\n/* The operations applicable to an object */\nconst objOps = {\n add: function (obj, key, document) {\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons\"\n );\n }\n obj[key] = this.value;\n return { newDocument: document };\n },\n remove: function (obj, key, document) {\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons\"\n );\n }\n var removed = obj[key];\n delete obj[key];\n return { newDocument: document, removed };\n },\n replace: function (obj, key, document) {\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons\"\n );\n }\n var removed = obj[key];\n obj[key] = this.value;\n return { newDocument: document, removed };\n },\n move: function (obj, key, document) {\n /* in case move target overwrites an existing value,\n return the removed value, this can be taxing performance-wise,\n and is potentially unneeded */\n let removed = getValueByPointer(document, this.path);\n\n if (removed) {\n removed = _deepClone(removed);\n }\n\n const originalValue = applyOperation(document, {\n op: \"remove\",\n path: this.from,\n }).removed;\n\n applyOperation(document, {\n op: \"add\",\n path: this.path,\n value: originalValue,\n });\n\n return { newDocument: document, removed };\n },\n copy: function (obj, key, document) {\n const valueToCopy = getValueByPointer(document, this.from);\n // enforce copy by value so further operations don't affect source (see issue #177)\n applyOperation(document, {\n op: \"add\",\n path: this.path,\n value: _deepClone(valueToCopy),\n });\n return { newDocument: document };\n },\n test: function (obj, key, document) {\n return { newDocument: document, test: _areEquals(obj[key], this.value) };\n },\n _get: function (obj, key, document) {\n this.value = obj[key];\n return { newDocument: document };\n },\n};\n\n/* The operations applicable to an array. Many are the same as for the object */\nvar arrOps = {\n add: function (arr, i, document) {\n if (isInteger(i)) {\n arr.splice(i, 0, this.value);\n } else {\n // array props\n arr[i] = this.value;\n }\n // this may be needed when using '-' in an array\n return { newDocument: document, index: i };\n },\n remove: function (arr, i, document) {\n var removedList = arr.splice(i, 1);\n return { newDocument: document, removed: removedList[0] };\n },\n replace: function (arr, i, document) {\n var removed = arr[i];\n arr[i] = this.value;\n return { newDocument: document, removed };\n },\n move: objOps.move,\n copy: objOps.copy,\n test: objOps.test,\n _get: objOps._get,\n};\n\n/**\n * Retrieves a value from a JSON document by a JSON pointer.\n * Returns the value.\n *\n * @param document The document to get the value from\n * @param pointer an escaped JSON pointer\n * @return The retrieved value\n */\nexport function getValueByPointer(document: any, pointer: string): any {\n if (pointer == \"\") {\n return document;\n }\n var getOriginalDestination = <GetOperation<any>>{ op: \"_get\", path: pointer };\n applyOperation(document, getOriginalDestination);\n return getOriginalDestination.value;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the {newDocument, result} of the operation.\n * It modifies the `document` and `operation` objects - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return `{newDocument, result}` after the operation\n */\nexport function applyOperation<T>(\n document: T,\n operation: Operation,\n validateOperation: boolean | Validator<T> = false,\n mutateDocument: boolean = true,\n banPrototypeModifications: boolean = true,\n index: number = 0\n): OperationResult<T> {\n if (validateOperation) {\n if (typeof validateOperation == \"function\") {\n validateOperation(operation, 0, document, operation.path);\n } else {\n validator(operation, 0);\n }\n }\n /* ROOT OPERATIONS */\n if (operation.path === \"\") {\n let returnValue: OperationResult<T> = { newDocument: document };\n if (operation.op === \"add\") {\n returnValue.newDocument = operation.value;\n return returnValue;\n } else if (operation.op === \"replace\") {\n returnValue.newDocument = operation.value;\n returnValue.removed = document; //document we removed\n return returnValue;\n } else if (operation.op === \"move\" || operation.op === \"copy\") {\n // it's a move or copy to root\n returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field\n if (operation.op === \"move\") {\n // report removed item\n returnValue.removed = document;\n }\n return returnValue;\n } else if (operation.op === \"test\") {\n returnValue.test = _areEquals(document, operation.value);\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n returnValue.newDocument = document;\n return returnValue;\n } else if (operation.op === \"remove\") {\n // a remove on root\n returnValue.removed = document;\n returnValue.newDocument = null;\n return returnValue;\n } else if (operation.op === \"_get\") {\n operation.value = document;\n return returnValue;\n } else {\n /* bad operation */\n if (validateOperation) {\n throw new JsonPatchError(\n \"Operation `op` property is not one of operations defined in RFC-6902\",\n \"OPERATION_OP_INVALID\",\n index,\n operation,\n document\n );\n } else {\n return returnValue;\n }\n }\n } /* END ROOT OPERATIONS */ else {\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n const path = operation.path || \"\";\n const keys = path.split(\"/\");\n let obj = document;\n let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift\n let len = keys.length;\n let existingPathFragment = undefined;\n let key: string | number;\n let validateFunction;\n if (typeof validateOperation == \"function\") {\n validateFunction = validateOperation;\n } else {\n validateFunction = validator;\n }\n while (true) {\n key = keys[t];\n if (key && key.indexOf(\"~\") != -1) {\n key = unescapePathComponent(key);\n }\n\n if (\n banPrototypeModifications &&\n (key == \"__proto__\" ||\n (key == \"prototype\" && t > 0 && keys[t - 1] == \"constructor\"))\n ) {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README\"\n );\n }\n\n if (validateOperation) {\n if (existingPathFragment === undefined) {\n if (obj[key] === undefined) {\n existingPathFragment = keys.slice(0, t).join(\"/\");\n } else if (t == len - 1) {\n existingPathFragment = operation.path;\n }\n if (existingPathFragment !== undefined) {\n validateFunction(operation, 0, document, existingPathFragment);\n }\n }\n }\n t++;\n if (Array.isArray(obj)) {\n if (key === \"-\") {\n key = obj.length;\n } else {\n if (validateOperation && !isInteger(key)) {\n throw new JsonPatchError(\n \"Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index\",\n \"OPERATION_PATH_ILLEGAL_ARRAY_INDEX\",\n index,\n operation,\n document\n );\n } // only parse key when it's an integer for `arr.prop` to work\n else if (isInteger(key)) {\n key = ~~key;\n }\n }\n if (t >= len) {\n if (validateOperation && operation.op === \"add\" && key > obj.length) {\n throw new JsonPatchError(\n \"The specified index MUST NOT be greater than the number of elements in the array\",\n \"OPERATION_VALUE_OUT_OF_BOUNDS\",\n index,\n operation,\n document\n );\n }\n const returnValue = arrOps[operation.op].call(\n operation,\n obj,\n key,\n document\n ); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return returnValue;\n }\n } else {\n if (t >= len) {\n const returnValue = objOps[operation.op].call(\n operation,\n obj,\n key,\n document\n ); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return returnValue;\n }\n }\n obj = obj[key];\n // If we have more keys in the path, but the next value isn't a non-null object,\n // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again.\n if (validateOperation && t < len && (!obj || typeof obj !== \"object\")) {\n throw new JsonPatchError(\n \"Cannot perform operation at the desired path\",\n \"OPERATION_PATH_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n }\n }\n}\n\n/**\n * Apply a full JSON Patch array on a JSON document.\n * Returns the {newDocument, result} of the patch.\n * It modifies the `document` object and `patch` - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.\n *\n * @param document The document to patch\n * @param patch The patch to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return An array of `{newDocument, result}` after the patch\n */\nexport function applyPatch<T>(\n document: T,\n patch: ReadonlyArray<Operation>,\n validateOperation?: boolean | Validator<T>,\n mutateDocument: boolean = true,\n banPrototypeModifications: boolean = true\n): PatchResult<T> {\n if (validateOperation) {\n if (!Array.isArray(patch)) {\n throw new JsonPatchError(\n \"Patch sequence must be an array\",\n \"SEQUENCE_NOT_AN_ARRAY\"\n );\n }\n }\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n const results = new Array(patch.length) as PatchResult<T>;\n\n for (let i = 0, length = patch.length; i < length; i++) {\n // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true`\n results[i] = applyOperation(\n document,\n patch[i],\n validateOperation,\n true,\n banPrototypeModifications,\n i\n );\n document = results[i].newDocument; // in case root was replaced\n }\n results.newDocument = document;\n return results;\n}\n\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the updated document.\n * Suitable as a reducer.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @return The updated document\n */\nexport function applyReducer<T>(\n document: T,\n operation: Operation,\n index: number\n): T {\n const operationResult: OperationResult<T> = applyOperation(\n document,\n operation\n );\n if (operationResult.test === false) {\n // failed test\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return operationResult.newDocument;\n}\n\n/**\n * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.\n * @param {object} operation - operation object (patch)\n * @param {number} index - index of operation in the sequence\n * @param {object} [document] - object where the operation is supposed to be applied\n * @param {string} [existingPathFragment] - comes along with `document`\n */\nexport function validator(\n operation: Operation,\n index: number,\n document?: any,\n existingPathFragment?: string\n): void {\n if (\n typeof operation !== \"object\" ||\n operation === null ||\n Array.isArray(operation)\n ) {\n throw new JsonPatchError(\n \"Operation is not an object\",\n \"OPERATION_NOT_AN_OBJECT\",\n index,\n operation,\n document\n );\n } else if (!objOps[operation.op]) {\n throw new JsonPatchError(\n \"Operation `op` property is not one of operations defined in RFC-6902\",\n \"OPERATION_OP_INVALID\",\n index,\n operation,\n document\n );\n } else if (typeof operation.path !== \"string\") {\n throw new JsonPatchError(\n \"Operation `path` property is not a string\",\n \"OPERATION_PATH_INVALID\",\n index,\n operation,\n document\n );\n } else if (operation.path.indexOf(\"/\") !== 0 && operation.path.length > 0) {\n // paths that aren't empty string should start with \"/\"\n throw new JsonPatchError(\n 'Operation `path` property must start with \"/\"',\n \"OPERATION_PATH_INVALID\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"move\" || operation.op === \"copy\") &&\n typeof operation.from !== \"string\"\n ) {\n throw new JsonPatchError(\n \"Operation `from` property is not present (applicable in `move` and `copy` operations)\",\n \"OPERATION_FROM_REQUIRED\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"add\" ||\n operation.op === \"replace\" ||\n operation.op === \"test\") &&\n operation.value === undefined\n ) {\n throw new JsonPatchError(\n \"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\",\n \"OPERATION_VALUE_REQUIRED\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"add\" ||\n operation.op === \"replace\" ||\n operation.op === \"test\") &&\n hasUndefined(operation.value)\n ) {\n throw new JsonPatchError(\n \"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\",\n \"OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED\",\n index,\n operation,\n document\n );\n } else if (document) {\n if (operation.op == \"add\") {\n var pathLen = operation.path.split(\"/\").length;\n var existingPathLen = existingPathFragment.split(\"/\").length;\n if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {\n throw new JsonPatchError(\n \"Cannot perform an `add` operation at the desired path\",\n \"OPERATION_PATH_CANNOT_ADD\",\n index,\n operation,\n document\n );\n }\n } else if (\n operation.op === \"replace\" ||\n operation.op === \"remove\" ||\n <any>operation.op === \"_get\"\n ) {\n if (operation.path !== existingPathFragment) {\n throw new JsonPatchError(\n \"Cannot perform the operation at a path that does not exist\",\n \"OPERATION_PATH_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n } else if (operation.op === \"move\" || operation.op === \"copy\") {\n var existingValue: any = {\n op: \"_get\",\n path: operation.from,\n value: undefined,\n };\n var error = validate([existingValue], document);\n if (error && error.name === \"OPERATION_PATH_UNRESOLVABLE\") {\n throw new JsonPatchError(\n \"Cannot perform the operation from a path that does not exist\",\n \"OPERATION_FROM_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n }\n }\n}\n\n/**\n * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.\n * If error is encountered, returns a JsonPatchError object\n * @param sequence\n * @param document\n * @returns {JsonPatchError|undefined}\n */\nexport function validate<T>(\n sequence: ReadonlyArray<Operation>,\n document?: T,\n externalValidator?: Validator<T>\n): PatchError {\n try {\n if (!Array.isArray(sequence)) {\n throw new JsonPatchError(\n \"Patch sequence must be an array\",\n \"SEQUENCE_NOT_AN_ARRAY\"\n );\n }\n if (document) {\n //clone document and sequence so that we can safely try applying operations\n applyPatch(\n _deepClone(document),\n _deepClone(sequence),\n externalValidator || true\n );\n } else {\n externalValidator = externalValidator || validator;\n for (var i = 0; i < sequence.length; i++) {\n externalValidator(sequence[i], i, document, undefined);\n }\n }\n } catch (e) {\n if (e instanceof JsonPatchError) {\n return e;\n } else {\n throw e;\n }\n }\n}\n\n// based on https://github.com/epoberezkin/fast-deep-equal\n// MIT License\n\n// Copyright (c) 2017 Evgeny Poberezkin\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\nexport function _areEquals(a: any, b: any): boolean {\n if (a === b) return true;\n\n if (a && b && typeof a == \"object\" && typeof b == \"object\") {\n var arrA = Array.isArray(a),\n arrB = Array.isArray(b),\n i,\n length,\n key;\n\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0; ) if (!_areEquals(a[i], b[i])) return false;\n return true;\n }\n\n if (arrA != arrB) return false;\n\n var keys = Object.keys(a);\n length = keys.length;\n\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0; ) if (!b.hasOwnProperty(keys[i])) return false;\n\n for (i = length; i-- !== 0; ) {\n key = keys[i];\n if (!_areEquals(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n return a !== a && b !== b;\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,MAAa,iBAAiBA,gBAAAA;AAC9B,MAAa,YAAYC,gBAAAA;AA2EzB,MAAM,SAAS;CACb,KAAK,SAAU,KAAK,KAAK,UAAU;AACjC,MAAI,QAAQ,eAAe,QAAQ,cACjC,OAAM,IAAI,UACR,yFACD;AAEH,MAAI,OAAO,KAAK;AAChB,SAAO,EAAE,aAAa,UAAU;;CAElC,QAAQ,SAAU,KAAK,KAAK,UAAU;AACpC,MAAI,QAAQ,eAAe,QAAQ,cACjC,OAAM,IAAI,UACR,yFACD;EAEH,IAAI,UAAU,IAAI;AAClB,SAAO,IAAI;AACX,SAAO;GAAE,aAAa;GAAU;GAAS;;CAE3C,SAAS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I,SAEF,YACEH,gBAAAA,WAAW,SAAS,EACpBA,gBAAAA,WAAW,SAAS,EACpB,qBAAqB,KACtB;OACI;AACL,uBAAoB,qBAAqB;AACzC,QAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,IACnC,mBAAkB,SAAS,IAAI,GAAG,UAAU,KAAA,EAAU;;UAGnD,GAAG;AACV,MAAI,aAAa,eACf,QAAO;MAEP,OAAM;;;AA2BZ,SAAgB,WAAW,GAAQ,GAAiB;AAClD,KAAI,MAAM,EAAG,QAAO;AAEpB,KAAI,KAAK,KAAK,OAAO,KAAK,YAAY,OAAO,KAAK,UAAU;EAC1D,IAAI,OAAO,MAAM,QAAQ,EAAE,EACzB,OAAO,MAAM,QAAQ,EAAE,EACvB,GACA,QACA;AAEF,MAAI,QAAQ,MAAM;AAChB,YAAS,EAAE;AACX,OAAI,UAAU,EAAE,OAAQ,QAAO;AAC/B,QAAK,IAAI,QAAQ,QAAQ,GAAK,KAAI,CAAC,WAAW,EAAE,IAAI,EAAE,GAAG,CAAE,QAAO;AAClE,UAAO;;AAGT,MAAI,QAAQ,KAAM,QAAO;EAEzB,IAAI,OAAO,OAAO,KAAK,EAAE;AACzB,WAAS,KAAK;AAEd,MAAI,WAAW,OAAO,KAAK,EAAE,CAAC,OAAQ,QAAO;AAE7C,OAAK,IAAI,QAAQ,QAAQ,GAAK,KAAI,CAAC,EAAE,eAAe,KAAK,GAAG,CAAE,QAAO;AAErE,OAAK,IAAI,QAAQ,QAAQ,IAAK;AAC5B,SAAM,KAAK;AACX,OAAI,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,CAAE,QAAO;;AAG1C,SAAO;;AAGT,QAAO,MAAM,KAAK,MAAM"}
|
|
1
|
+
{"version":3,"file":"core.cjs","names":["PatchError","_deepClone","isInteger","unescapePathComponent","hasUndefined"],"sources":["../../../../src/utils/fast-json-patch/src/core.ts"],"sourcesContent":["// @ts-nocheck\n\n// Inlined because of ESM import issues\n\n/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2013-2021 Joachim Wester\n * MIT license\n */\ndeclare var require: any;\n\nimport {\n PatchError,\n _deepClone,\n isInteger,\n unescapePathComponent,\n hasUndefined,\n} from \"./helpers.js\";\n\nexport const JsonPatchError = PatchError;\nexport const deepClone = _deepClone;\n\nexport type Operation =\n | AddOperation<any>\n | RemoveOperation\n | ReplaceOperation<any>\n | MoveOperation\n | CopyOperation\n | TestOperation<any>\n | GetOperation<any>;\n\nexport interface Validator<T> {\n (\n operation: Operation,\n index: number,\n document: T,\n existingPathFragment: string\n ): void;\n}\n\nexport interface OperationResult<T> {\n removed?: any;\n test?: boolean;\n newDocument: T;\n}\n\nexport interface BaseOperation {\n path: string;\n}\n\nexport interface AddOperation<T> extends BaseOperation {\n op: \"add\";\n value: T;\n}\n\nexport interface RemoveOperation extends BaseOperation {\n op: \"remove\";\n}\n\nexport interface ReplaceOperation<T> extends BaseOperation {\n op: \"replace\";\n value: T;\n}\n\nexport interface MoveOperation extends BaseOperation {\n op: \"move\";\n from: string;\n}\n\nexport interface CopyOperation extends BaseOperation {\n op: \"copy\";\n from: string;\n}\n\nexport interface TestOperation<T> extends BaseOperation {\n op: \"test\";\n value: T;\n}\n\nexport interface GetOperation<T> extends BaseOperation {\n op: \"_get\";\n value: T;\n}\nexport interface PatchResult<T> extends Array<OperationResult<T>> {\n newDocument: T;\n}\n\n/* We use a Javascript hash to store each\n function. Each hash entry (property) uses\n the operation identifiers specified in rfc6902.\n In this way, we can map each patch operation\n to its dedicated function in efficient way.\n */\n\n/* The operations applicable to an object */\nconst objOps = {\n add: function (obj, key, document) {\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons\"\n );\n }\n obj[key] = this.value;\n return { newDocument: document };\n },\n remove: function (obj, key, document) {\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons\"\n );\n }\n var removed = obj[key];\n delete obj[key];\n return { newDocument: document, removed };\n },\n replace: function (obj, key, document) {\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons\"\n );\n }\n var removed = obj[key];\n obj[key] = this.value;\n return { newDocument: document, removed };\n },\n move: function (obj, key, document) {\n /* in case move target overwrites an existing value,\n return the removed value, this can be taxing performance-wise,\n and is potentially unneeded */\n let removed = getValueByPointer(document, this.path);\n\n if (removed) {\n removed = _deepClone(removed);\n }\n\n const originalValue = applyOperation(document, {\n op: \"remove\",\n path: this.from,\n }).removed;\n\n applyOperation(document, {\n op: \"add\",\n path: this.path,\n value: originalValue,\n });\n\n return { newDocument: document, removed };\n },\n copy: function (obj, key, document) {\n const valueToCopy = getValueByPointer(document, this.from);\n // enforce copy by value so further operations don't affect source (see issue #177)\n applyOperation(document, {\n op: \"add\",\n path: this.path,\n value: _deepClone(valueToCopy),\n });\n return { newDocument: document };\n },\n test: function (obj, key, document) {\n return { newDocument: document, test: _areEquals(obj[key], this.value) };\n },\n _get: function (obj, key, document) {\n this.value = obj[key];\n return { newDocument: document };\n },\n};\n\n/* The operations applicable to an array. Many are the same as for the object */\nvar arrOps = {\n add: function (arr, i, document) {\n if (isInteger(i)) {\n arr.splice(i, 0, this.value);\n } else {\n // array props\n arr[i] = this.value;\n }\n // this may be needed when using '-' in an array\n return { newDocument: document, index: i };\n },\n remove: function (arr, i, document) {\n var removedList = arr.splice(i, 1);\n return { newDocument: document, removed: removedList[0] };\n },\n replace: function (arr, i, document) {\n var removed = arr[i];\n arr[i] = this.value;\n return { newDocument: document, removed };\n },\n move: objOps.move,\n copy: objOps.copy,\n test: objOps.test,\n _get: objOps._get,\n};\n\n/**\n * Retrieves a value from a JSON document by a JSON pointer.\n * Returns the value.\n *\n * @param document The document to get the value from\n * @param pointer an escaped JSON pointer\n * @return The retrieved value\n */\nexport function getValueByPointer(document: any, pointer: string): any {\n if (pointer == \"\") {\n return document;\n }\n var getOriginalDestination = <GetOperation<any>>{ op: \"_get\", path: pointer };\n applyOperation(document, getOriginalDestination);\n return getOriginalDestination.value;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the {newDocument, result} of the operation.\n * It modifies the `document` and `operation` objects - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return `{newDocument, result}` after the operation\n */\nexport function applyOperation<T>(\n document: T,\n operation: Operation,\n validateOperation: boolean | Validator<T> = false,\n mutateDocument: boolean = true,\n banPrototypeModifications: boolean = true,\n index: number = 0\n): OperationResult<T> {\n if (validateOperation) {\n if (typeof validateOperation == \"function\") {\n validateOperation(operation, 0, document, operation.path);\n } else {\n validator(operation, 0);\n }\n }\n /* ROOT OPERATIONS */\n if (operation.path === \"\") {\n let returnValue: OperationResult<T> = { newDocument: document };\n if (operation.op === \"add\") {\n returnValue.newDocument = operation.value;\n return returnValue;\n } else if (operation.op === \"replace\") {\n returnValue.newDocument = operation.value;\n returnValue.removed = document; //document we removed\n return returnValue;\n } else if (operation.op === \"move\" || operation.op === \"copy\") {\n // it's a move or copy to root\n returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field\n if (operation.op === \"move\") {\n // report removed item\n returnValue.removed = document;\n }\n return returnValue;\n } else if (operation.op === \"test\") {\n returnValue.test = _areEquals(document, operation.value);\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n returnValue.newDocument = document;\n return returnValue;\n } else if (operation.op === \"remove\") {\n // a remove on root\n returnValue.removed = document;\n returnValue.newDocument = null;\n return returnValue;\n } else if (operation.op === \"_get\") {\n operation.value = document;\n return returnValue;\n } else {\n /* bad operation */\n if (validateOperation) {\n throw new JsonPatchError(\n \"Operation `op` property is not one of operations defined in RFC-6902\",\n \"OPERATION_OP_INVALID\",\n index,\n operation,\n document\n );\n } else {\n return returnValue;\n }\n }\n } /* END ROOT OPERATIONS */ else {\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n const path = operation.path || \"\";\n const keys = path.split(\"/\");\n let obj = document;\n let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift\n let len = keys.length;\n let existingPathFragment = undefined;\n let key: string | number;\n let validateFunction;\n if (typeof validateOperation == \"function\") {\n validateFunction = validateOperation;\n } else {\n validateFunction = validator;\n }\n while (true) {\n key = keys[t];\n if (key && key.indexOf(\"~\") != -1) {\n key = unescapePathComponent(key);\n }\n\n if (\n banPrototypeModifications &&\n (key == \"__proto__\" ||\n (key == \"prototype\" && t > 0 && keys[t - 1] == \"constructor\"))\n ) {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README\"\n );\n }\n\n if (validateOperation) {\n if (existingPathFragment === undefined) {\n if (obj[key] === undefined) {\n existingPathFragment = keys.slice(0, t).join(\"/\");\n } else if (t == len - 1) {\n existingPathFragment = operation.path;\n }\n if (existingPathFragment !== undefined) {\n validateFunction(operation, 0, document, existingPathFragment);\n }\n }\n }\n t++;\n if (Array.isArray(obj)) {\n if (key === \"-\") {\n key = obj.length;\n } else {\n if (validateOperation && !isInteger(key)) {\n throw new JsonPatchError(\n \"Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index\",\n \"OPERATION_PATH_ILLEGAL_ARRAY_INDEX\",\n index,\n operation,\n document\n );\n } // only parse key when it's an integer for `arr.prop` to work\n else if (isInteger(key)) {\n key = ~~key;\n }\n }\n if (t >= len) {\n if (validateOperation && operation.op === \"add\" && key > obj.length) {\n throw new JsonPatchError(\n \"The specified index MUST NOT be greater than the number of elements in the array\",\n \"OPERATION_VALUE_OUT_OF_BOUNDS\",\n index,\n operation,\n document\n );\n }\n const returnValue = arrOps[operation.op].call(\n operation,\n obj,\n key,\n document\n ); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return returnValue;\n }\n } else {\n if (t >= len) {\n const returnValue = objOps[operation.op].call(\n operation,\n obj,\n key,\n document\n ); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return returnValue;\n }\n }\n obj = obj[key];\n // If we have more keys in the path, but the next value isn't a non-null object,\n // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again.\n if (validateOperation && t < len && (!obj || typeof obj !== \"object\")) {\n throw new JsonPatchError(\n \"Cannot perform operation at the desired path\",\n \"OPERATION_PATH_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n }\n }\n}\n\n/**\n * Apply a full JSON Patch array on a JSON document.\n * Returns the {newDocument, result} of the patch.\n * It modifies the `document` object and `patch` - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.\n *\n * @param document The document to patch\n * @param patch The patch to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return An array of `{newDocument, result}` after the patch\n */\nexport function applyPatch<T>(\n document: T,\n patch: ReadonlyArray<Operation>,\n validateOperation?: boolean | Validator<T>,\n mutateDocument: boolean = true,\n banPrototypeModifications: boolean = true\n): PatchResult<T> {\n if (validateOperation) {\n if (!Array.isArray(patch)) {\n throw new JsonPatchError(\n \"Patch sequence must be an array\",\n \"SEQUENCE_NOT_AN_ARRAY\"\n );\n }\n }\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n const results = new Array(patch.length) as PatchResult<T>;\n\n for (let i = 0, length = patch.length; i < length; i++) {\n // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true`\n results[i] = applyOperation(\n document,\n patch[i],\n validateOperation,\n true,\n banPrototypeModifications,\n i\n );\n document = results[i].newDocument; // in case root was replaced\n }\n results.newDocument = document;\n return results;\n}\n\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the updated document.\n * Suitable as a reducer.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @return The updated document\n */\nexport function applyReducer<T>(\n document: T,\n operation: Operation,\n index: number\n): T {\n const operationResult: OperationResult<T> = applyOperation(\n document,\n operation\n );\n if (operationResult.test === false) {\n // failed test\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return operationResult.newDocument;\n}\n\n/**\n * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.\n * @param {object} operation - operation object (patch)\n * @param {number} index - index of operation in the sequence\n * @param {object} [document] - object where the operation is supposed to be applied\n * @param {string} [existingPathFragment] - comes along with `document`\n */\nexport function validator(\n operation: Operation,\n index: number,\n document?: any,\n existingPathFragment?: string\n): void {\n if (\n typeof operation !== \"object\" ||\n operation === null ||\n Array.isArray(operation)\n ) {\n throw new JsonPatchError(\n \"Operation is not an object\",\n \"OPERATION_NOT_AN_OBJECT\",\n index,\n operation,\n document\n );\n } else if (!objOps[operation.op]) {\n throw new JsonPatchError(\n \"Operation `op` property is not one of operations defined in RFC-6902\",\n \"OPERATION_OP_INVALID\",\n index,\n operation,\n document\n );\n } else if (typeof operation.path !== \"string\") {\n throw new JsonPatchError(\n \"Operation `path` property is not a string\",\n \"OPERATION_PATH_INVALID\",\n index,\n operation,\n document\n );\n } else if (operation.path.indexOf(\"/\") !== 0 && operation.path.length > 0) {\n // paths that aren't empty string should start with \"/\"\n throw new JsonPatchError(\n 'Operation `path` property must start with \"/\"',\n \"OPERATION_PATH_INVALID\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"move\" || operation.op === \"copy\") &&\n typeof operation.from !== \"string\"\n ) {\n throw new JsonPatchError(\n \"Operation `from` property is not present (applicable in `move` and `copy` operations)\",\n \"OPERATION_FROM_REQUIRED\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"add\" ||\n operation.op === \"replace\" ||\n operation.op === \"test\") &&\n operation.value === undefined\n ) {\n throw new JsonPatchError(\n \"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\",\n \"OPERATION_VALUE_REQUIRED\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"add\" ||\n operation.op === \"replace\" ||\n operation.op === \"test\") &&\n hasUndefined(operation.value)\n ) {\n throw new JsonPatchError(\n \"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\",\n \"OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED\",\n index,\n operation,\n document\n );\n } else if (document) {\n if (operation.op == \"add\") {\n var pathLen = operation.path.split(\"/\").length;\n var existingPathLen = existingPathFragment.split(\"/\").length;\n if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {\n throw new JsonPatchError(\n \"Cannot perform an `add` operation at the desired path\",\n \"OPERATION_PATH_CANNOT_ADD\",\n index,\n operation,\n document\n );\n }\n } else if (\n operation.op === \"replace\" ||\n operation.op === \"remove\" ||\n <any>operation.op === \"_get\"\n ) {\n if (operation.path !== existingPathFragment) {\n throw new JsonPatchError(\n \"Cannot perform the operation at a path that does not exist\",\n \"OPERATION_PATH_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n } else if (operation.op === \"move\" || operation.op === \"copy\") {\n var existingValue: any = {\n op: \"_get\",\n path: operation.from,\n value: undefined,\n };\n var error = validate([existingValue], document);\n if (error && error.name === \"OPERATION_PATH_UNRESOLVABLE\") {\n throw new JsonPatchError(\n \"Cannot perform the operation from a path that does not exist\",\n \"OPERATION_FROM_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n }\n }\n}\n\n/**\n * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.\n * If error is encountered, returns a JsonPatchError object\n * @param sequence\n * @param document\n * @returns {JsonPatchError|undefined}\n */\nexport function validate<T>(\n sequence: ReadonlyArray<Operation>,\n document?: T,\n externalValidator?: Validator<T>\n): PatchError {\n try {\n if (!Array.isArray(sequence)) {\n throw new JsonPatchError(\n \"Patch sequence must be an array\",\n \"SEQUENCE_NOT_AN_ARRAY\"\n );\n }\n if (document) {\n //clone document and sequence so that we can safely try applying operations\n applyPatch(\n _deepClone(document),\n _deepClone(sequence),\n externalValidator || true\n );\n } else {\n externalValidator = externalValidator || validator;\n for (var i = 0; i < sequence.length; i++) {\n externalValidator(sequence[i], i, document, undefined);\n }\n }\n } catch (e) {\n if (e instanceof JsonPatchError) {\n return e;\n } else {\n throw e;\n }\n }\n}\n\n// based on https://github.com/epoberezkin/fast-deep-equal\n// MIT License\n\n// Copyright (c) 2017 Evgeny Poberezkin\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\nexport function _areEquals(a: any, b: any): boolean {\n if (a === b) return true;\n\n if (a && b && typeof a == \"object\" && typeof b == \"object\") {\n var arrA = Array.isArray(a),\n arrB = Array.isArray(b),\n i,\n length,\n key;\n\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0; ) if (!_areEquals(a[i], b[i])) return false;\n return true;\n }\n\n if (arrA != arrB) return false;\n\n var keys = Object.keys(a);\n length = keys.length;\n\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0; ) if (!b.hasOwnProperty(keys[i])) return false;\n\n for (i = length; i-- !== 0; ) {\n key = keys[i];\n if (!_areEquals(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n return a !== a && b !== b;\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,MAAa,iBAAiBA,gBAAAA;AAC9B,MAAa,YAAYC,gBAAAA;AA2EzB,MAAM,SAAS;CACb,KAAK,SAAU,KAAK,KAAK,UAAU;AACjC,MAAI,QAAQ,eAAe,QAAQ,cACjC,OAAM,IAAI,UACR,yFACD;AAEH,MAAI,OAAO,KAAK;AAChB,SAAO,EAAE,aAAa,UAAU;;CAElC,QAAQ,SAAU,KAAK,KAAK,UAAU;AACpC,MAAI,QAAQ,eAAe,QAAQ,cACjC,OAAM,IAAI,UACR,yFACD;EAEH,IAAI,UAAU,IAAI;AAClB,SAAO,IAAI;AACX,SAAO;GAAE,aAAa;GAAU;GAAS;;CAE3C,SAAS,SAAU,KAAK,KAAK,UAAU;AACrC,MAAI,QAAQ,eAAe,QAAQ,cACjC,OAAM,IAAI,UACR,yFACD;EAEH,IAAI,UAAU,IAAI;AAClB,MAAI,OAAO,KAAK;AAChB,SAAO;GAAE,aAAa;GAAU;GAAS;;CAE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B,SAAS,IAAI,GAAG,UAAU,KAAA,EAAU;;UAGnD,GAAG;AACV,MAAI,aAAa,eACf,QAAO;MAEP,OAAM;;;AA2BZ,SAAgB,WAAW,GAAQ,GAAiB;AAClD,KAAI,MAAM,EAAG,QAAO;AAEpB,KAAI,KAAK,KAAK,OAAO,KAAK,YAAY,OAAO,KAAK,UAAU;EAC1D,IAAI,OAAO,MAAM,QAAQ,EAAE,EACzB,OAAO,MAAM,QAAQ,EAAE,EACvB,GACA,QACA;AAEF,MAAI,QAAQ,MAAM;AAChB,YAAS,EAAE;AACX,OAAI,UAAU,EAAE,OAAQ,QAAO;AAC/B,QAAK,IAAI,QAAQ,QAAQ,GAAK,KAAI,CAAC,WAAW,EAAE,IAAI,EAAE,GAAG,CAAE,QAAO;AAClE,UAAO;;AAGT,MAAI,QAAQ,KAAM,QAAO;EAEzB,IAAI,OAAO,OAAO,KAAK,EAAE;AACzB,WAAS,KAAK;AAEd,MAAI,WAAW,OAAO,KAAK,EAAE,CAAC,OAAQ,QAAO;AAE7C,OAAK,IAAI,QAAQ,QAAQ,GAAK,KAAI,CAAC,EAAE,eAAe,KAAK,GAAG,CAAE,QAAO;AAErE,OAAK,IAAI,QAAQ,QAAQ,IAAK;AAC5B,SAAM,KAAK;AACX,OAAI,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,CAAE,QAAO;;AAG1C,SAAO;;AAGT,QAAO,MAAM,KAAK,MAAM"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.js","names":[],"sources":["../../../../src/utils/fast-json-patch/src/core.ts"],"sourcesContent":["// @ts-nocheck\n\n// Inlined because of ESM import issues\n\n/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2013-2021 Joachim Wester\n * MIT license\n */\ndeclare var require: any;\n\nimport {\n PatchError,\n _deepClone,\n isInteger,\n unescapePathComponent,\n hasUndefined,\n} from \"./helpers.js\";\n\nexport const JsonPatchError = PatchError;\nexport const deepClone = _deepClone;\n\nexport type Operation =\n | AddOperation<any>\n | RemoveOperation\n | ReplaceOperation<any>\n | MoveOperation\n | CopyOperation\n | TestOperation<any>\n | GetOperation<any>;\n\nexport interface Validator<T> {\n (\n operation: Operation,\n index: number,\n document: T,\n existingPathFragment: string\n ): void;\n}\n\nexport interface OperationResult<T> {\n removed?: any;\n test?: boolean;\n newDocument: T;\n}\n\nexport interface BaseOperation {\n path: string;\n}\n\nexport interface AddOperation<T> extends BaseOperation {\n op: \"add\";\n value: T;\n}\n\nexport interface RemoveOperation extends BaseOperation {\n op: \"remove\";\n}\n\nexport interface ReplaceOperation<T> extends BaseOperation {\n op: \"replace\";\n value: T;\n}\n\nexport interface MoveOperation extends BaseOperation {\n op: \"move\";\n from: string;\n}\n\nexport interface CopyOperation extends BaseOperation {\n op: \"copy\";\n from: string;\n}\n\nexport interface TestOperation<T> extends BaseOperation {\n op: \"test\";\n value: T;\n}\n\nexport interface GetOperation<T> extends BaseOperation {\n op: \"_get\";\n value: T;\n}\nexport interface PatchResult<T> extends Array<OperationResult<T>> {\n newDocument: T;\n}\n\n/* We use a Javascript hash to store each\n function. Each hash entry (property) uses\n the operation identifiers specified in rfc6902.\n In this way, we can map each patch operation\n to its dedicated function in efficient way.\n */\n\n/* The operations applicable to an object */\nconst objOps = {\n add: function (obj, key, document) {\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons\"\n );\n }\n obj[key] = this.value;\n return { newDocument: document };\n },\n remove: function (obj, key, document) {\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons\"\n );\n }\n var removed = obj[key];\n delete obj[key];\n return { newDocument: document, removed };\n },\n replace: function (obj, key, document) {\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons\"\n );\n }\n var removed = obj[key];\n obj[key] = this.value;\n return { newDocument: document, removed };\n },\n move: function (obj, key, document) {\n /* in case move target overwrites an existing value,\n return the removed value, this can be taxing performance-wise,\n and is potentially unneeded */\n let removed = getValueByPointer(document, this.path);\n\n if (removed) {\n removed = _deepClone(removed);\n }\n\n const originalValue = applyOperation(document, {\n op: \"remove\",\n path: this.from,\n }).removed;\n\n applyOperation(document, {\n op: \"add\",\n path: this.path,\n value: originalValue,\n });\n\n return { newDocument: document, removed };\n },\n copy: function (obj, key, document) {\n const valueToCopy = getValueByPointer(document, this.from);\n // enforce copy by value so further operations don't affect source (see issue #177)\n applyOperation(document, {\n op: \"add\",\n path: this.path,\n value: _deepClone(valueToCopy),\n });\n return { newDocument: document };\n },\n test: function (obj, key, document) {\n return { newDocument: document, test: _areEquals(obj[key], this.value) };\n },\n _get: function (obj, key, document) {\n this.value = obj[key];\n return { newDocument: document };\n },\n};\n\n/* The operations applicable to an array. Many are the same as for the object */\nvar arrOps = {\n add: function (arr, i, document) {\n if (isInteger(i)) {\n arr.splice(i, 0, this.value);\n } else {\n // array props\n arr[i] = this.value;\n }\n // this may be needed when using '-' in an array\n return { newDocument: document, index: i };\n },\n remove: function (arr, i, document) {\n var removedList = arr.splice(i, 1);\n return { newDocument: document, removed: removedList[0] };\n },\n replace: function (arr, i, document) {\n var removed = arr[i];\n arr[i] = this.value;\n return { newDocument: document, removed };\n },\n move: objOps.move,\n copy: objOps.copy,\n test: objOps.test,\n _get: objOps._get,\n};\n\n/**\n * Retrieves a value from a JSON document by a JSON pointer.\n * Returns the value.\n *\n * @param document The document to get the value from\n * @param pointer an escaped JSON pointer\n * @return The retrieved value\n */\nexport function getValueByPointer(document: any, pointer: string): any {\n if (pointer == \"\") {\n return document;\n }\n var getOriginalDestination = <GetOperation<any>>{ op: \"_get\", path: pointer };\n applyOperation(document, getOriginalDestination);\n return getOriginalDestination.value;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the {newDocument, result} of the operation.\n * It modifies the `document` and `operation` objects - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return `{newDocument, result}` after the operation\n */\nexport function applyOperation<T>(\n document: T,\n operation: Operation,\n validateOperation: boolean | Validator<T> = false,\n mutateDocument: boolean = true,\n banPrototypeModifications: boolean = true,\n index: number = 0\n): OperationResult<T> {\n if (validateOperation) {\n if (typeof validateOperation == \"function\") {\n validateOperation(operation, 0, document, operation.path);\n } else {\n validator(operation, 0);\n }\n }\n /* ROOT OPERATIONS */\n if (operation.path === \"\") {\n let returnValue: OperationResult<T> = { newDocument: document };\n if (operation.op === \"add\") {\n returnValue.newDocument = operation.value;\n return returnValue;\n } else if (operation.op === \"replace\") {\n returnValue.newDocument = operation.value;\n returnValue.removed = document; //document we removed\n return returnValue;\n } else if (operation.op === \"move\" || operation.op === \"copy\") {\n // it's a move or copy to root\n returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field\n if (operation.op === \"move\") {\n // report removed item\n returnValue.removed = document;\n }\n return returnValue;\n } else if (operation.op === \"test\") {\n returnValue.test = _areEquals(document, operation.value);\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n returnValue.newDocument = document;\n return returnValue;\n } else if (operation.op === \"remove\") {\n // a remove on root\n returnValue.removed = document;\n returnValue.newDocument = null;\n return returnValue;\n } else if (operation.op === \"_get\") {\n operation.value = document;\n return returnValue;\n } else {\n /* bad operation */\n if (validateOperation) {\n throw new JsonPatchError(\n \"Operation `op` property is not one of operations defined in RFC-6902\",\n \"OPERATION_OP_INVALID\",\n index,\n operation,\n document\n );\n } else {\n return returnValue;\n }\n }\n } /* END ROOT OPERATIONS */ else {\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n const path = operation.path || \"\";\n const keys = path.split(\"/\");\n let obj = document;\n let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift\n let len = keys.length;\n let existingPathFragment = undefined;\n let key: string | number;\n let validateFunction;\n if (typeof validateOperation == \"function\") {\n validateFunction = validateOperation;\n } else {\n validateFunction = validator;\n }\n while (true) {\n key = keys[t];\n if (key && key.indexOf(\"~\") != -1) {\n key = unescapePathComponent(key);\n }\n\n if (\n banPrototypeModifications &&\n (key == \"__proto__\" ||\n (key == \"prototype\" && t > 0 && keys[t - 1] == \"constructor\"))\n ) {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README\"\n );\n }\n\n if (validateOperation) {\n if (existingPathFragment === undefined) {\n if (obj[key] === undefined) {\n existingPathFragment = keys.slice(0, t).join(\"/\");\n } else if (t == len - 1) {\n existingPathFragment = operation.path;\n }\n if (existingPathFragment !== undefined) {\n validateFunction(operation, 0, document, existingPathFragment);\n }\n }\n }\n t++;\n if (Array.isArray(obj)) {\n if (key === \"-\") {\n key = obj.length;\n } else {\n if (validateOperation && !isInteger(key)) {\n throw new JsonPatchError(\n \"Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index\",\n \"OPERATION_PATH_ILLEGAL_ARRAY_INDEX\",\n index,\n operation,\n document\n );\n } // only parse key when it's an integer for `arr.prop` to work\n else if (isInteger(key)) {\n key = ~~key;\n }\n }\n if (t >= len) {\n if (validateOperation && operation.op === \"add\" && key > obj.length) {\n throw new JsonPatchError(\n \"The specified index MUST NOT be greater than the number of elements in the array\",\n \"OPERATION_VALUE_OUT_OF_BOUNDS\",\n index,\n operation,\n document\n );\n }\n const returnValue = arrOps[operation.op].call(\n operation,\n obj,\n key,\n document\n ); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return returnValue;\n }\n } else {\n if (t >= len) {\n const returnValue = objOps[operation.op].call(\n operation,\n obj,\n key,\n document\n ); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return returnValue;\n }\n }\n obj = obj[key];\n // If we have more keys in the path, but the next value isn't a non-null object,\n // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again.\n if (validateOperation && t < len && (!obj || typeof obj !== \"object\")) {\n throw new JsonPatchError(\n \"Cannot perform operation at the desired path\",\n \"OPERATION_PATH_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n }\n }\n}\n\n/**\n * Apply a full JSON Patch array on a JSON document.\n * Returns the {newDocument, result} of the patch.\n * It modifies the `document` object and `patch` - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.\n *\n * @param document The document to patch\n * @param patch The patch to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return An array of `{newDocument, result}` after the patch\n */\nexport function applyPatch<T>(\n document: T,\n patch: ReadonlyArray<Operation>,\n validateOperation?: boolean | Validator<T>,\n mutateDocument: boolean = true,\n banPrototypeModifications: boolean = true\n): PatchResult<T> {\n if (validateOperation) {\n if (!Array.isArray(patch)) {\n throw new JsonPatchError(\n \"Patch sequence must be an array\",\n \"SEQUENCE_NOT_AN_ARRAY\"\n );\n }\n }\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n const results = new Array(patch.length) as PatchResult<T>;\n\n for (let i = 0, length = patch.length; i < length; i++) {\n // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true`\n results[i] = applyOperation(\n document,\n patch[i],\n validateOperation,\n true,\n banPrototypeModifications,\n i\n );\n document = results[i].newDocument; // in case root was replaced\n }\n results.newDocument = document;\n return results;\n}\n\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the updated document.\n * Suitable as a reducer.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @return The updated document\n */\nexport function applyReducer<T>(\n document: T,\n operation: Operation,\n index: number\n): T {\n const operationResult: OperationResult<T> = applyOperation(\n document,\n operation\n );\n if (operationResult.test === false) {\n // failed test\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return operationResult.newDocument;\n}\n\n/**\n * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.\n * @param {object} operation - operation object (patch)\n * @param {number} index - index of operation in the sequence\n * @param {object} [document] - object where the operation is supposed to be applied\n * @param {string} [existingPathFragment] - comes along with `document`\n */\nexport function validator(\n operation: Operation,\n index: number,\n document?: any,\n existingPathFragment?: string\n): void {\n if (\n typeof operation !== \"object\" ||\n operation === null ||\n Array.isArray(operation)\n ) {\n throw new JsonPatchError(\n \"Operation is not an object\",\n \"OPERATION_NOT_AN_OBJECT\",\n index,\n operation,\n document\n );\n } else if (!objOps[operation.op]) {\n throw new JsonPatchError(\n \"Operation `op` property is not one of operations defined in RFC-6902\",\n \"OPERATION_OP_INVALID\",\n index,\n operation,\n document\n );\n } else if (typeof operation.path !== \"string\") {\n throw new JsonPatchError(\n \"Operation `path` property is not a string\",\n \"OPERATION_PATH_INVALID\",\n index,\n operation,\n document\n );\n } else if (operation.path.indexOf(\"/\") !== 0 && operation.path.length > 0) {\n // paths that aren't empty string should start with \"/\"\n throw new JsonPatchError(\n 'Operation `path` property must start with \"/\"',\n \"OPERATION_PATH_INVALID\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"move\" || operation.op === \"copy\") &&\n typeof operation.from !== \"string\"\n ) {\n throw new JsonPatchError(\n \"Operation `from` property is not present (applicable in `move` and `copy` operations)\",\n \"OPERATION_FROM_REQUIRED\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"add\" ||\n operation.op === \"replace\" ||\n operation.op === \"test\") &&\n operation.value === undefined\n ) {\n throw new JsonPatchError(\n \"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\",\n \"OPERATION_VALUE_REQUIRED\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"add\" ||\n operation.op === \"replace\" ||\n operation.op === \"test\") &&\n hasUndefined(operation.value)\n ) {\n throw new JsonPatchError(\n \"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\",\n \"OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED\",\n index,\n operation,\n document\n );\n } else if (document) {\n if (operation.op == \"add\") {\n var pathLen = operation.path.split(\"/\").length;\n var existingPathLen = existingPathFragment.split(\"/\").length;\n if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {\n throw new JsonPatchError(\n \"Cannot perform an `add` operation at the desired path\",\n \"OPERATION_PATH_CANNOT_ADD\",\n index,\n operation,\n document\n );\n }\n } else if (\n operation.op === \"replace\" ||\n operation.op === \"remove\" ||\n <any>operation.op === \"_get\"\n ) {\n if (operation.path !== existingPathFragment) {\n throw new JsonPatchError(\n \"Cannot perform the operation at a path that does not exist\",\n \"OPERATION_PATH_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n } else if (operation.op === \"move\" || operation.op === \"copy\") {\n var existingValue: any = {\n op: \"_get\",\n path: operation.from,\n value: undefined,\n };\n var error = validate([existingValue], document);\n if (error && error.name === \"OPERATION_PATH_UNRESOLVABLE\") {\n throw new JsonPatchError(\n \"Cannot perform the operation from a path that does not exist\",\n \"OPERATION_FROM_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n }\n }\n}\n\n/**\n * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.\n * If error is encountered, returns a JsonPatchError object\n * @param sequence\n * @param document\n * @returns {JsonPatchError|undefined}\n */\nexport function validate<T>(\n sequence: ReadonlyArray<Operation>,\n document?: T,\n externalValidator?: Validator<T>\n): PatchError {\n try {\n if (!Array.isArray(sequence)) {\n throw new JsonPatchError(\n \"Patch sequence must be an array\",\n \"SEQUENCE_NOT_AN_ARRAY\"\n );\n }\n if (document) {\n //clone document and sequence so that we can safely try applying operations\n applyPatch(\n _deepClone(document),\n _deepClone(sequence),\n externalValidator || true\n );\n } else {\n externalValidator = externalValidator || validator;\n for (var i = 0; i < sequence.length; i++) {\n externalValidator(sequence[i], i, document, undefined);\n }\n }\n } catch (e) {\n if (e instanceof JsonPatchError) {\n return e;\n } else {\n throw e;\n }\n }\n}\n\n// based on https://github.com/epoberezkin/fast-deep-equal\n// MIT License\n\n// Copyright (c) 2017 Evgeny Poberezkin\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\nexport function _areEquals(a: any, b: any): boolean {\n if (a === b) return true;\n\n if (a && b && typeof a == \"object\" && typeof b == \"object\") {\n var arrA = Array.isArray(a),\n arrB = Array.isArray(b),\n i,\n length,\n key;\n\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0; ) if (!_areEquals(a[i], b[i])) return false;\n return true;\n }\n\n if (arrA != arrB) return false;\n\n var keys = Object.keys(a);\n length = keys.length;\n\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0; ) if (!b.hasOwnProperty(keys[i])) return false;\n\n for (i = length; i-- !== 0; ) {\n key = keys[i];\n if (!_areEquals(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n return a !== a && b !== b;\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,MAAa,iBAAiB;AAC9B,MAAa,YAAY;AA2EzB,MAAM,SAAS;CACb,KAAK,SAAU,KAAK,KAAK,UAAU;AACjC,MAAI,QAAQ,eAAe,QAAQ,cACjC,OAAM,IAAI,UACR,yFACD;AAEH,MAAI,OAAO,KAAK;AAChB,SAAO,EAAE,aAAa,UAAU;;CAElC,QAAQ,SAAU,KAAK,KAAK,UAAU;AACpC,MAAI,QAAQ,eAAe,QAAQ,cACjC,OAAM,IAAI,UACR,yFACD;EAEH,IAAI,UAAU,IAAI;AAClB,SAAO,IAAI;AACX,SAAO;GAAE,aAAa;GAAU;GAAS;;CAE3C,SAAS,SAAU,KAAK,KAAK,UAAU;AACrC,MAAI,QAAQ,eAAe,QAAQ,cACjC,OAAM,IAAI,UACR,yFACD;EAEH,IAAI,UAAU,IAAI;AAClB,MAAI,OAAO,KAAK;AAChB,SAAO;GAAE,aAAa;GAAU;GAAS;;CAE3C,MAAM,SAAU,KAAK,KAAK,UAAU;EAIlC,IAAI,UAAU,kBAAkB,UAAU,KAAK,KAAK;AAEpD,MAAI,QACF,WAAU,WAAW,QAAQ;EAG/B,MAAM,gBAAgB,eAAe,UAAU;GAC7C,IAAI;GACJ,MAAM,KAAK;GACZ,CAAC,CAAC;AAEH,iBA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I,QAAQ,MAAM;AAChB,YAAS,EAAE;AACX,OAAI,UAAU,EAAE,OAAQ,QAAO;AAC/B,QAAK,IAAI,QAAQ,QAAQ,GAAK,KAAI,CAAC,WAAW,EAAE,IAAI,EAAE,GAAG,CAAE,QAAO;AAClE,UAAO;;AAGT,MAAI,QAAQ,KAAM,QAAO;EAEzB,IAAI,OAAO,OAAO,KAAK,EAAE;AACzB,WAAS,KAAK;AAEd,MAAI,WAAW,OAAO,KAAK,EAAE,CAAC,OAAQ,QAAO;AAE7C,OAAK,IAAI,QAAQ,QAAQ,GAAK,KAAI,CAAC,EAAE,eAAe,KAAK,GAAG,CAAE,QAAO;AAErE,OAAK,IAAI,QAAQ,QAAQ,IAAK;AAC5B,SAAM,KAAK;AACX,OAAI,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,CAAE,QAAO;;AAG1C,SAAO;;AAGT,QAAO,MAAM,KAAK,MAAM"}
|
|
1
|
+
{"version":3,"file":"core.js","names":[],"sources":["../../../../src/utils/fast-json-patch/src/core.ts"],"sourcesContent":["// @ts-nocheck\n\n// Inlined because of ESM import issues\n\n/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2013-2021 Joachim Wester\n * MIT license\n */\ndeclare var require: any;\n\nimport {\n PatchError,\n _deepClone,\n isInteger,\n unescapePathComponent,\n hasUndefined,\n} from \"./helpers.js\";\n\nexport const JsonPatchError = PatchError;\nexport const deepClone = _deepClone;\n\nexport type Operation =\n | AddOperation<any>\n | RemoveOperation\n | ReplaceOperation<any>\n | MoveOperation\n | CopyOperation\n | TestOperation<any>\n | GetOperation<any>;\n\nexport interface Validator<T> {\n (\n operation: Operation,\n index: number,\n document: T,\n existingPathFragment: string\n ): void;\n}\n\nexport interface OperationResult<T> {\n removed?: any;\n test?: boolean;\n newDocument: T;\n}\n\nexport interface BaseOperation {\n path: string;\n}\n\nexport interface AddOperation<T> extends BaseOperation {\n op: \"add\";\n value: T;\n}\n\nexport interface RemoveOperation extends BaseOperation {\n op: \"remove\";\n}\n\nexport interface ReplaceOperation<T> extends BaseOperation {\n op: \"replace\";\n value: T;\n}\n\nexport interface MoveOperation extends BaseOperation {\n op: \"move\";\n from: string;\n}\n\nexport interface CopyOperation extends BaseOperation {\n op: \"copy\";\n from: string;\n}\n\nexport interface TestOperation<T> extends BaseOperation {\n op: \"test\";\n value: T;\n}\n\nexport interface GetOperation<T> extends BaseOperation {\n op: \"_get\";\n value: T;\n}\nexport interface PatchResult<T> extends Array<OperationResult<T>> {\n newDocument: T;\n}\n\n/* We use a Javascript hash to store each\n function. Each hash entry (property) uses\n the operation identifiers specified in rfc6902.\n In this way, we can map each patch operation\n to its dedicated function in efficient way.\n */\n\n/* The operations applicable to an object */\nconst objOps = {\n add: function (obj, key, document) {\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons\"\n );\n }\n obj[key] = this.value;\n return { newDocument: document };\n },\n remove: function (obj, key, document) {\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons\"\n );\n }\n var removed = obj[key];\n delete obj[key];\n return { newDocument: document, removed };\n },\n replace: function (obj, key, document) {\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons\"\n );\n }\n var removed = obj[key];\n obj[key] = this.value;\n return { newDocument: document, removed };\n },\n move: function (obj, key, document) {\n /* in case move target overwrites an existing value,\n return the removed value, this can be taxing performance-wise,\n and is potentially unneeded */\n let removed = getValueByPointer(document, this.path);\n\n if (removed) {\n removed = _deepClone(removed);\n }\n\n const originalValue = applyOperation(document, {\n op: \"remove\",\n path: this.from,\n }).removed;\n\n applyOperation(document, {\n op: \"add\",\n path: this.path,\n value: originalValue,\n });\n\n return { newDocument: document, removed };\n },\n copy: function (obj, key, document) {\n const valueToCopy = getValueByPointer(document, this.from);\n // enforce copy by value so further operations don't affect source (see issue #177)\n applyOperation(document, {\n op: \"add\",\n path: this.path,\n value: _deepClone(valueToCopy),\n });\n return { newDocument: document };\n },\n test: function (obj, key, document) {\n return { newDocument: document, test: _areEquals(obj[key], this.value) };\n },\n _get: function (obj, key, document) {\n this.value = obj[key];\n return { newDocument: document };\n },\n};\n\n/* The operations applicable to an array. Many are the same as for the object */\nvar arrOps = {\n add: function (arr, i, document) {\n if (isInteger(i)) {\n arr.splice(i, 0, this.value);\n } else {\n // array props\n arr[i] = this.value;\n }\n // this may be needed when using '-' in an array\n return { newDocument: document, index: i };\n },\n remove: function (arr, i, document) {\n var removedList = arr.splice(i, 1);\n return { newDocument: document, removed: removedList[0] };\n },\n replace: function (arr, i, document) {\n var removed = arr[i];\n arr[i] = this.value;\n return { newDocument: document, removed };\n },\n move: objOps.move,\n copy: objOps.copy,\n test: objOps.test,\n _get: objOps._get,\n};\n\n/**\n * Retrieves a value from a JSON document by a JSON pointer.\n * Returns the value.\n *\n * @param document The document to get the value from\n * @param pointer an escaped JSON pointer\n * @return The retrieved value\n */\nexport function getValueByPointer(document: any, pointer: string): any {\n if (pointer == \"\") {\n return document;\n }\n var getOriginalDestination = <GetOperation<any>>{ op: \"_get\", path: pointer };\n applyOperation(document, getOriginalDestination);\n return getOriginalDestination.value;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the {newDocument, result} of the operation.\n * It modifies the `document` and `operation` objects - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return `{newDocument, result}` after the operation\n */\nexport function applyOperation<T>(\n document: T,\n operation: Operation,\n validateOperation: boolean | Validator<T> = false,\n mutateDocument: boolean = true,\n banPrototypeModifications: boolean = true,\n index: number = 0\n): OperationResult<T> {\n if (validateOperation) {\n if (typeof validateOperation == \"function\") {\n validateOperation(operation, 0, document, operation.path);\n } else {\n validator(operation, 0);\n }\n }\n /* ROOT OPERATIONS */\n if (operation.path === \"\") {\n let returnValue: OperationResult<T> = { newDocument: document };\n if (operation.op === \"add\") {\n returnValue.newDocument = operation.value;\n return returnValue;\n } else if (operation.op === \"replace\") {\n returnValue.newDocument = operation.value;\n returnValue.removed = document; //document we removed\n return returnValue;\n } else if (operation.op === \"move\" || operation.op === \"copy\") {\n // it's a move or copy to root\n returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field\n if (operation.op === \"move\") {\n // report removed item\n returnValue.removed = document;\n }\n return returnValue;\n } else if (operation.op === \"test\") {\n returnValue.test = _areEquals(document, operation.value);\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n returnValue.newDocument = document;\n return returnValue;\n } else if (operation.op === \"remove\") {\n // a remove on root\n returnValue.removed = document;\n returnValue.newDocument = null;\n return returnValue;\n } else if (operation.op === \"_get\") {\n operation.value = document;\n return returnValue;\n } else {\n /* bad operation */\n if (validateOperation) {\n throw new JsonPatchError(\n \"Operation `op` property is not one of operations defined in RFC-6902\",\n \"OPERATION_OP_INVALID\",\n index,\n operation,\n document\n );\n } else {\n return returnValue;\n }\n }\n } /* END ROOT OPERATIONS */ else {\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n const path = operation.path || \"\";\n const keys = path.split(\"/\");\n let obj = document;\n let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift\n let len = keys.length;\n let existingPathFragment = undefined;\n let key: string | number;\n let validateFunction;\n if (typeof validateOperation == \"function\") {\n validateFunction = validateOperation;\n } else {\n validateFunction = validator;\n }\n while (true) {\n key = keys[t];\n if (key && key.indexOf(\"~\") != -1) {\n key = unescapePathComponent(key);\n }\n\n if (\n banPrototypeModifications &&\n (key == \"__proto__\" ||\n (key == \"prototype\" && t > 0 && keys[t - 1] == \"constructor\"))\n ) {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README\"\n );\n }\n\n if (validateOperation) {\n if (existingPathFragment === undefined) {\n if (obj[key] === undefined) {\n existingPathFragment = keys.slice(0, t).join(\"/\");\n } else if (t == len - 1) {\n existingPathFragment = operation.path;\n }\n if (existingPathFragment !== undefined) {\n validateFunction(operation, 0, document, existingPathFragment);\n }\n }\n }\n t++;\n if (Array.isArray(obj)) {\n if (key === \"-\") {\n key = obj.length;\n } else {\n if (validateOperation && !isInteger(key)) {\n throw new JsonPatchError(\n \"Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index\",\n \"OPERATION_PATH_ILLEGAL_ARRAY_INDEX\",\n index,\n operation,\n document\n );\n } // only parse key when it's an integer for `arr.prop` to work\n else if (isInteger(key)) {\n key = ~~key;\n }\n }\n if (t >= len) {\n if (validateOperation && operation.op === \"add\" && key > obj.length) {\n throw new JsonPatchError(\n \"The specified index MUST NOT be greater than the number of elements in the array\",\n \"OPERATION_VALUE_OUT_OF_BOUNDS\",\n index,\n operation,\n document\n );\n }\n const returnValue = arrOps[operation.op].call(\n operation,\n obj,\n key,\n document\n ); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return returnValue;\n }\n } else {\n if (t >= len) {\n const returnValue = objOps[operation.op].call(\n operation,\n obj,\n key,\n document\n ); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return returnValue;\n }\n }\n obj = obj[key];\n // If we have more keys in the path, but the next value isn't a non-null object,\n // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again.\n if (validateOperation && t < len && (!obj || typeof obj !== \"object\")) {\n throw new JsonPatchError(\n \"Cannot perform operation at the desired path\",\n \"OPERATION_PATH_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n }\n }\n}\n\n/**\n * Apply a full JSON Patch array on a JSON document.\n * Returns the {newDocument, result} of the patch.\n * It modifies the `document` object and `patch` - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.\n *\n * @param document The document to patch\n * @param patch The patch to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return An array of `{newDocument, result}` after the patch\n */\nexport function applyPatch<T>(\n document: T,\n patch: ReadonlyArray<Operation>,\n validateOperation?: boolean | Validator<T>,\n mutateDocument: boolean = true,\n banPrototypeModifications: boolean = true\n): PatchResult<T> {\n if (validateOperation) {\n if (!Array.isArray(patch)) {\n throw new JsonPatchError(\n \"Patch sequence must be an array\",\n \"SEQUENCE_NOT_AN_ARRAY\"\n );\n }\n }\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n const results = new Array(patch.length) as PatchResult<T>;\n\n for (let i = 0, length = patch.length; i < length; i++) {\n // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true`\n results[i] = applyOperation(\n document,\n patch[i],\n validateOperation,\n true,\n banPrototypeModifications,\n i\n );\n document = results[i].newDocument; // in case root was replaced\n }\n results.newDocument = document;\n return results;\n}\n\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the updated document.\n * Suitable as a reducer.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @return The updated document\n */\nexport function applyReducer<T>(\n document: T,\n operation: Operation,\n index: number\n): T {\n const operationResult: OperationResult<T> = applyOperation(\n document,\n operation\n );\n if (operationResult.test === false) {\n // failed test\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return operationResult.newDocument;\n}\n\n/**\n * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.\n * @param {object} operation - operation object (patch)\n * @param {number} index - index of operation in the sequence\n * @param {object} [document] - object where the operation is supposed to be applied\n * @param {string} [existingPathFragment] - comes along with `document`\n */\nexport function validator(\n operation: Operation,\n index: number,\n document?: any,\n existingPathFragment?: string\n): void {\n if (\n typeof operation !== \"object\" ||\n operation === null ||\n Array.isArray(operation)\n ) {\n throw new JsonPatchError(\n \"Operation is not an object\",\n \"OPERATION_NOT_AN_OBJECT\",\n index,\n operation,\n document\n );\n } else if (!objOps[operation.op]) {\n throw new JsonPatchError(\n \"Operation `op` property is not one of operations defined in RFC-6902\",\n \"OPERATION_OP_INVALID\",\n index,\n operation,\n document\n );\n } else if (typeof operation.path !== \"string\") {\n throw new JsonPatchError(\n \"Operation `path` property is not a string\",\n \"OPERATION_PATH_INVALID\",\n index,\n operation,\n document\n );\n } else if (operation.path.indexOf(\"/\") !== 0 && operation.path.length > 0) {\n // paths that aren't empty string should start with \"/\"\n throw new JsonPatchError(\n 'Operation `path` property must start with \"/\"',\n \"OPERATION_PATH_INVALID\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"move\" || operation.op === \"copy\") &&\n typeof operation.from !== \"string\"\n ) {\n throw new JsonPatchError(\n \"Operation `from` property is not present (applicable in `move` and `copy` operations)\",\n \"OPERATION_FROM_REQUIRED\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"add\" ||\n operation.op === \"replace\" ||\n operation.op === \"test\") &&\n operation.value === undefined\n ) {\n throw new JsonPatchError(\n \"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\",\n \"OPERATION_VALUE_REQUIRED\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"add\" ||\n operation.op === \"replace\" ||\n operation.op === \"test\") &&\n hasUndefined(operation.value)\n ) {\n throw new JsonPatchError(\n \"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\",\n \"OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED\",\n index,\n operation,\n document\n );\n } else if (document) {\n if (operation.op == \"add\") {\n var pathLen = operation.path.split(\"/\").length;\n var existingPathLen = existingPathFragment.split(\"/\").length;\n if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {\n throw new JsonPatchError(\n \"Cannot perform an `add` operation at the desired path\",\n \"OPERATION_PATH_CANNOT_ADD\",\n index,\n operation,\n document\n );\n }\n } else if (\n operation.op === \"replace\" ||\n operation.op === \"remove\" ||\n <any>operation.op === \"_get\"\n ) {\n if (operation.path !== existingPathFragment) {\n throw new JsonPatchError(\n \"Cannot perform the operation at a path that does not exist\",\n \"OPERATION_PATH_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n } else if (operation.op === \"move\" || operation.op === \"copy\") {\n var existingValue: any = {\n op: \"_get\",\n path: operation.from,\n value: undefined,\n };\n var error = validate([existingValue], document);\n if (error && error.name === \"OPERATION_PATH_UNRESOLVABLE\") {\n throw new JsonPatchError(\n \"Cannot perform the operation from a path that does not exist\",\n \"OPERATION_FROM_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n }\n }\n}\n\n/**\n * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.\n * If error is encountered, returns a JsonPatchError object\n * @param sequence\n * @param document\n * @returns {JsonPatchError|undefined}\n */\nexport function validate<T>(\n sequence: ReadonlyArray<Operation>,\n document?: T,\n externalValidator?: Validator<T>\n): PatchError {\n try {\n if (!Array.isArray(sequence)) {\n throw new JsonPatchError(\n \"Patch sequence must be an array\",\n \"SEQUENCE_NOT_AN_ARRAY\"\n );\n }\n if (document) {\n //clone document and sequence so that we can safely try applying operations\n applyPatch(\n _deepClone(document),\n _deepClone(sequence),\n externalValidator || true\n );\n } else {\n externalValidator = externalValidator || validator;\n for (var i = 0; i < sequence.length; i++) {\n externalValidator(sequence[i], i, document, undefined);\n }\n }\n } catch (e) {\n if (e instanceof JsonPatchError) {\n return e;\n } else {\n throw e;\n }\n }\n}\n\n// based on https://github.com/epoberezkin/fast-deep-equal\n// MIT License\n\n// Copyright (c) 2017 Evgeny Poberezkin\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\nexport function _areEquals(a: any, b: any): boolean {\n if (a === b) return true;\n\n if (a && b && typeof a == \"object\" && typeof b == \"object\") {\n var arrA = Array.isArray(a),\n arrB = Array.isArray(b),\n i,\n length,\n key;\n\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0; ) if (!_areEquals(a[i], b[i])) return false;\n return true;\n }\n\n if (arrA != arrB) return false;\n\n var keys = Object.keys(a);\n length = keys.length;\n\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0; ) if (!b.hasOwnProperty(keys[i])) return false;\n\n for (i = length; i-- !== 0; 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AI,QAAQ,QAAQ,GAAK,KAAI,CAAC,EAAE,eAAe,KAAK,GAAG,CAAE,QAAO;AAErE,OAAK,IAAI,QAAQ,QAAQ,IAAK;AAC5B,SAAM,KAAK;AACX,OAAI,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,CAAE,QAAO;;AAG1C,SAAO;;AAGT,QAAO,MAAM,KAAK,MAAM"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_schema.cjs","names":["isStandardJsonSchema","isZodSchemaV4","interopZodTransformInputSchema","isZodObjectV4","interopZodObjectStrict","isZodSchemaV3","zodToJsonSchema"],"sources":["../../src/utils/json_schema.ts"],"sourcesContent":["import { toJSONSchema, type $ZodType } from \"zod/v4/core\";\nimport { dereference, type Schema } from \"@cfworker/json-schema\";\nimport {\n isZodSchemaV3,\n isZodSchemaV4,\n InteropZodType,\n interopZodObjectStrict,\n isZodObjectV4,\n interopZodTransformInputSchema,\n} from \"./types/zod.js\";\nimport {\n type JsonSchema7Type as JSONSchema,\n zodToJsonSchema,\n} from \"./zod-to-json-schema/index.js\";\nimport { StandardJSONSchemaV1 } from \"@standard-schema/spec\";\nimport { isStandardJsonSchema } from \"./standard_schema.js\";\n\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n\nexport type ToJSONSchemaParams = NonNullable<\n Parameters<typeof toJSONSchema>[1]\n>;\n\n/**\n * WeakMap cache for Zod/Standard-Schema → JSON Schema conversions.\n *\n * Keyed on the schema object reference. Since Zod schemas are immutable and\n * the same `tool.schema` reference is passed on every LLM call, this\n * eliminates redundant serializations. For example, an agent with 6 tools\n * doing 15 steps across 3 parallel subagents would otherwise run 270\n * identical conversions per invocation.\n *\n * Only used when no custom `params` are passed (the common case for tool\n * binding). WeakMap ensures cached entries are GC'd when the schema goes\n * out of scope.\n *\n * @internal\n */\nconst _jsonSchemaCache = new WeakMap<object, JSONSchema>();\n\n/**\n * Converts a Standard JSON schema, Zod schema or JSON schema to a JSON schema.\n * Results are cached by schema reference when no custom params are passed.\n * @param schema - The schema to convert.\n * @param params - The parameters to pass to the toJSONSchema function.\n * @returns The converted schema.\n */\nexport function toJsonSchema(\n schema: StandardJSONSchemaV1 | InteropZodType | JSONSchema,\n params?: ToJSONSchemaParams\n): JSONSchema {\n // Cache when no custom params are passed (the default for tool binding).\n // Params can change the output (e.g., different target draft), so we\n // bypass the cache when they're provided.\n const canCache = !params && schema != null && typeof schema === \"object\";\n\n if (canCache) {\n const cached = _jsonSchemaCache.get(schema);\n if (cached) return cached;\n }\n\n let result: JSONSchema;\n\n if (isStandardJsonSchema(schema) && !isZodSchemaV4(schema)) {\n result = schema[\"~standard\"].jsonSchema.input({\n target: \"draft-07\",\n }) as JSONSchema;\n } else if (isZodSchemaV4(schema)) {\n const inputSchema = interopZodTransformInputSchema(schema, true);\n if (isZodObjectV4(inputSchema)) {\n const strictSchema = interopZodObjectStrict(inputSchema, true);\n result = toJSONSchema(strictSchema as unknown as $ZodType, params);\n } else {\n result = toJSONSchema(schema as unknown as $ZodType, params);\n }\n } else if (isZodSchemaV3(schema)) {\n result = zodToJsonSchema(schema as never);\n } else {\n result = schema as JSONSchema;\n }\n\n if (canCache && result != null && typeof result === \"object\") {\n _jsonSchemaCache.set(schema, result);\n }\n\n return result;\n}\n\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport function validatesOnlyStrings(schema: unknown): boolean {\n // Null, undefined, or empty schema\n if (\n !schema ||\n typeof schema !== \"object\" ||\n Object.keys(schema).length === 0 ||\n Array.isArray(schema)\n ) {\n return false; // Validates anything, not just strings\n }\n\n // Explicit type constraint\n if (\"type\" in schema) {\n if (typeof schema.type === \"string\") {\n return schema.type === \"string\";\n }\n\n if (Array.isArray(schema.type)) {\n // not sure why someone would do `\"type\": [\"string\"]` or especially `\"type\": [\"string\",\n // \"string\", \"string\", ...]` but we're not here to judge\n return schema.type.every((t) => t === \"string\");\n }\n return false; // Invalid or non-string type\n }\n\n // Enum with only string values\n if (\"enum\" in schema) {\n return (\n Array.isArray(schema.enum) &&\n schema.enum.length > 0 &&\n schema.enum.every((val) => typeof val === \"string\")\n );\n }\n\n // String constant\n if (\"const\" in schema) {\n return typeof schema.const === \"string\";\n }\n\n // Schema combinations\n if (\"allOf\" in schema && Array.isArray(schema.allOf)) {\n // If any subschema validates only strings, then the overall schema validates only strings\n return schema.allOf.some((subschema) => validatesOnlyStrings(subschema));\n }\n\n if (\n (\"anyOf\" in schema && Array.isArray(schema.anyOf)) ||\n (\"oneOf\" in schema && Array.isArray(schema.oneOf))\n ) {\n const subschemas = (\n \"anyOf\" in schema ? schema.anyOf : schema.oneOf\n ) as unknown[];\n\n // All subschemas must validate only strings\n return (\n subschemas.length > 0 &&\n subschemas.every((subschema) => validatesOnlyStrings(subschema))\n );\n }\n\n // We're not going to try on this one, it's too complex - we just assume if it has a \"not\" key and hasn't matched one of the above checks, it's not a string schema.\n if (\"not\" in schema) {\n return false; // The not case can validate non-strings\n }\n\n if (\"$ref\" in schema && typeof schema.$ref === \"string\") {\n const ref = schema.$ref as string;\n const resolved = dereference(schema as Schema);\n if (resolved[ref]) {\n return validatesOnlyStrings(resolved[ref]);\n }\n return false;\n }\n\n // ignore recursive refs and other cases where type is omitted for now\n // ignore other cases for now where type is omitted\n\n return false;\n}\n\n// Re-export of the types used throughout langchain for json schema serialization.\n// The plan is to eventually nix zod-to-json-schema altogether in place for\n// zod v4 / a more standardized way of serializing validated inputs, so its re-exported\n// here to remove the dependency on zod-to-json-schema in downstream packages until\n// a determination is made.\n\nexport {\n type JsonSchema7Type,\n type JsonSchema7Type as JSONSchema,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"./zod-to-json-schema/index.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,mCAAmB,IAAI,SAA6B;;;;;;;;AAS1D,SAAgB,aACd,QACA,QACY;CAIZ,MAAM,WAAW,CAAC,UAAU,UAAU,QAAQ,OAAO,WAAW;AAEhE,KAAI,UAAU;EACZ,MAAM,SAAS,iBAAiB,IAAI,OAAO;AAC3C,MAAI,OAAQ,QAAO;;CAGrB,IAAI;AAEJ,KAAIA,8BAAAA,qBAAqB,OAAO,IAAI,CAACC,YAAAA,cAAc,OAAO,CACxD,UAAS,OAAO,aAAa,WAAW,MAAM,EAC5C,QAAQ,YACT,CAAC;UACOA,YAAAA,cAAc,OAAO,EAAE;EAChC,MAAM,cAAcC,YAAAA,+BAA+B,QAAQ,KAAK;AAChE,MAAIC,YAAAA,cAAc,YAAY,CAE5B,WAAA,GAAA,YAAA,cADqBC,YAAAA,uBAAuB,aAAa,
|
|
1
|
+
{"version":3,"file":"json_schema.cjs","names":["isStandardJsonSchema","isZodSchemaV4","interopZodTransformInputSchema","isZodObjectV4","interopZodObjectStrict","isZodSchemaV3","zodToJsonSchema"],"sources":["../../src/utils/json_schema.ts"],"sourcesContent":["import { toJSONSchema, type $ZodType } from \"zod/v4/core\";\nimport { dereference, type Schema } from \"@cfworker/json-schema\";\nimport {\n isZodSchemaV3,\n isZodSchemaV4,\n InteropZodType,\n interopZodObjectStrict,\n isZodObjectV4,\n interopZodTransformInputSchema,\n} from \"./types/zod.js\";\nimport {\n type JsonSchema7Type as JSONSchema,\n zodToJsonSchema,\n} from \"./zod-to-json-schema/index.js\";\nimport { StandardJSONSchemaV1 } from \"@standard-schema/spec\";\nimport { isStandardJsonSchema } from \"./standard_schema.js\";\n\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n\nexport type ToJSONSchemaParams = NonNullable<\n Parameters<typeof toJSONSchema>[1]\n>;\n\n/**\n * WeakMap cache for Zod/Standard-Schema → JSON Schema conversions.\n *\n * Keyed on the schema object reference. Since Zod schemas are immutable and\n * the same `tool.schema` reference is passed on every LLM call, this\n * eliminates redundant serializations. For example, an agent with 6 tools\n * doing 15 steps across 3 parallel subagents would otherwise run 270\n * identical conversions per invocation.\n *\n * Only used when no custom `params` are passed (the common case for tool\n * binding). WeakMap ensures cached entries are GC'd when the schema goes\n * out of scope.\n *\n * @internal\n */\nconst _jsonSchemaCache = new WeakMap<object, JSONSchema>();\n\n/**\n * Converts a Standard JSON schema, Zod schema or JSON schema to a JSON schema.\n * Results are cached by schema reference when no custom params are passed.\n * @param schema - The schema to convert.\n * @param params - The parameters to pass to the toJSONSchema function.\n * @returns The converted schema.\n */\nexport function toJsonSchema(\n schema: StandardJSONSchemaV1 | InteropZodType | JSONSchema,\n params?: ToJSONSchemaParams\n): JSONSchema {\n // Cache when no custom params are passed (the default for tool binding).\n // Params can change the output (e.g., different target draft), so we\n // bypass the cache when they're provided.\n const canCache = !params && schema != null && typeof schema === \"object\";\n\n if (canCache) {\n const cached = _jsonSchemaCache.get(schema);\n if (cached) return cached;\n }\n\n let result: JSONSchema;\n\n if (isStandardJsonSchema(schema) && !isZodSchemaV4(schema)) {\n result = schema[\"~standard\"].jsonSchema.input({\n target: \"draft-07\",\n }) as JSONSchema;\n } else if (isZodSchemaV4(schema)) {\n const inputSchema = interopZodTransformInputSchema(schema, true);\n if (isZodObjectV4(inputSchema)) {\n const strictSchema = interopZodObjectStrict(inputSchema, true);\n result = toJSONSchema(strictSchema as unknown as $ZodType, params);\n } else {\n result = toJSONSchema(schema as unknown as $ZodType, params);\n }\n } else if (isZodSchemaV3(schema)) {\n result = zodToJsonSchema(schema as never);\n } else {\n result = schema as JSONSchema;\n }\n\n if (canCache && result != null && typeof result === \"object\") {\n _jsonSchemaCache.set(schema, result);\n }\n\n return result;\n}\n\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport function validatesOnlyStrings(schema: unknown): boolean {\n // Null, undefined, or empty schema\n if (\n !schema ||\n typeof schema !== \"object\" ||\n Object.keys(schema).length === 0 ||\n Array.isArray(schema)\n ) {\n return false; // Validates anything, not just strings\n }\n\n // Explicit type constraint\n if (\"type\" in schema) {\n if (typeof schema.type === \"string\") {\n return schema.type === \"string\";\n }\n\n if (Array.isArray(schema.type)) {\n // not sure why someone would do `\"type\": [\"string\"]` or especially `\"type\": [\"string\",\n // \"string\", \"string\", ...]` but we're not here to judge\n return schema.type.every((t) => t === \"string\");\n }\n return false; // Invalid or non-string type\n }\n\n // Enum with only string values\n if (\"enum\" in schema) {\n return (\n Array.isArray(schema.enum) &&\n schema.enum.length > 0 &&\n schema.enum.every((val) => typeof val === \"string\")\n );\n }\n\n // String constant\n if (\"const\" in schema) {\n return typeof schema.const === \"string\";\n }\n\n // Schema combinations\n if (\"allOf\" in schema && Array.isArray(schema.allOf)) {\n // If any subschema validates only strings, then the overall schema validates only strings\n return schema.allOf.some((subschema) => validatesOnlyStrings(subschema));\n }\n\n if (\n (\"anyOf\" in schema && Array.isArray(schema.anyOf)) ||\n (\"oneOf\" in schema && Array.isArray(schema.oneOf))\n ) {\n const subschemas = (\n \"anyOf\" in schema ? schema.anyOf : schema.oneOf\n ) as unknown[];\n\n // All subschemas must validate only strings\n return (\n subschemas.length > 0 &&\n subschemas.every((subschema) => validatesOnlyStrings(subschema))\n );\n }\n\n // We're not going to try on this one, it's too complex - we just assume if it has a \"not\" key and hasn't matched one of the above checks, it's not a string schema.\n if (\"not\" in schema) {\n return false; // The not case can validate non-strings\n }\n\n if (\"$ref\" in schema && typeof schema.$ref === \"string\") {\n const ref = schema.$ref as string;\n const resolved = dereference(schema as Schema);\n if (resolved[ref]) {\n return validatesOnlyStrings(resolved[ref]);\n }\n return false;\n }\n\n // ignore recursive refs and other cases where type is omitted for now\n // ignore other cases for now where type is omitted\n\n return false;\n}\n\n// Re-export of the types used throughout langchain for json schema serialization.\n// The plan is to eventually nix zod-to-json-schema altogether in place for\n// zod v4 / a more standardized way of serializing validated inputs, so its re-exported\n// here to remove the dependency on zod-to-json-schema in downstream packages until\n// a determination is made.\n\nexport {\n type JsonSchema7Type,\n type JsonSchema7Type as JSONSchema,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"./zod-to-json-schema/index.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,mCAAmB,IAAI,SAA6B;;;;;;;;AAS1D,SAAgB,aACd,QACA,QACY;CAIZ,MAAM,WAAW,CAAC,UAAU,UAAU,QAAQ,OAAO,WAAW;AAEhE,KAAI,UAAU;EACZ,MAAM,SAAS,iBAAiB,IAAI,OAAO;AAC3C,MAAI,OAAQ,QAAO;;CAGrB,IAAI;AAEJ,KAAIA,8BAAAA,qBAAqB,OAAO,IAAI,CAACC,YAAAA,cAAc,OAAO,CACxD,UAAS,OAAO,aAAa,WAAW,MAAM,EAC5C,QAAQ,YACT,CAAC;UACOA,YAAAA,cAAc,OAAO,EAAE;EAChC,MAAM,cAAcC,YAAAA,+BAA+B,QAAQ,KAAK;AAChE,MAAIC,YAAAA,cAAc,YAAY,CAE5B,WAAA,GAAA,YAAA,cADqBC,YAAAA,uBAAuB,aAAa,KACvB,EAAyB,OAAO;MAElE,WAAA,GAAA,YAAA,cAAsB,QAA+B,OAAO;YAErDC,YAAAA,cAAc,OAAO,CAC9B,UAASC,wBAAAA,gBAAgB,OAAgB;KAEzC,UAAS;AAGX,KAAI,YAAY,UAAU,QAAQ,OAAO,WAAW,SAClD,kBAAiB,IAAI,QAAQ,OAAO;AAGtC,QAAO;;;;;;;;;AAUT,SAAgB,qBAAqB,QAA0B;AAE7D,KACE,CAAC,UACD,OAAO,WAAW,YAClB,OAAO,KAAK,OAAO,CAAC,WAAW,KAC/B,MAAM,QAAQ,OAAO,CAErB,QAAO;AAIT,KAAI,UAAU,QAAQ;AACpB,MAAI,OAAO,OAAO,SAAS,SACzB,QAAO,OAAO,SAAS;AAGzB,MAAI,MAAM,QAAQ,OAAO,KAAK,CAG5B,QAAO,OAAO,KAAK,OAAO,MAAM,MAAM,SAAS;AAEjD,SAAO;;AAIT,KAAI,UAAU,OACZ,QACE,MAAM,QAAQ,OAAO,KAAK,IAC1B,OAAO,KAAK,SAAS,KACrB,OAAO,KAAK,OAAO,QAAQ,OAAO,QAAQ,SAAS;AAKvD,KAAI,WAAW,OACb,QAAO,OAAO,OAAO,UAAU;AAIjC,KAAI,WAAW,UAAU,MAAM,QAAQ,OAAO,MAAM,CAElD,QAAO,OAAO,MAAM,MAAM,cAAc,qBAAqB,UAAU,CAAC;AAG1E,KACG,WAAW,UAAU,MAAM,QAAQ,OAAO,MAAM,IAChD,WAAW,UAAU,MAAM,QAAQ,OAAO,MAAM,EACjD;EACA,MAAM,aACJ,WAAW,SAAS,OAAO,QAAQ,OAAO;AAI5C,SACE,WAAW,SAAS,KACpB,WAAW,OAAO,cAAc,qBAAqB,UAAU,CAAC;;AAKpE,KAAI,SAAS,OACX,QAAO;AAGT,KAAI,UAAU,UAAU,OAAO,OAAO,SAAS,UAAU;EACvD,MAAM,MAAM,OAAO;EACnB,MAAM,YAAA,GAAA,sBAAA,aAAuB,OAAiB;AAC9C,MAAI,SAAS,KACX,QAAO,qBAAqB,SAAS,KAAK;AAE5C,SAAO;;AAMT,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_schema.js","names":[],"sources":["../../src/utils/json_schema.ts"],"sourcesContent":["import { toJSONSchema, type $ZodType } from \"zod/v4/core\";\nimport { dereference, type Schema } from \"@cfworker/json-schema\";\nimport {\n isZodSchemaV3,\n isZodSchemaV4,\n InteropZodType,\n interopZodObjectStrict,\n isZodObjectV4,\n interopZodTransformInputSchema,\n} from \"./types/zod.js\";\nimport {\n type JsonSchema7Type as JSONSchema,\n zodToJsonSchema,\n} from \"./zod-to-json-schema/index.js\";\nimport { StandardJSONSchemaV1 } from \"@standard-schema/spec\";\nimport { isStandardJsonSchema } from \"./standard_schema.js\";\n\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n\nexport type ToJSONSchemaParams = NonNullable<\n Parameters<typeof toJSONSchema>[1]\n>;\n\n/**\n * WeakMap cache for Zod/Standard-Schema → JSON Schema conversions.\n *\n * Keyed on the schema object reference. Since Zod schemas are immutable and\n * the same `tool.schema` reference is passed on every LLM call, this\n * eliminates redundant serializations. For example, an agent with 6 tools\n * doing 15 steps across 3 parallel subagents would otherwise run 270\n * identical conversions per invocation.\n *\n * Only used when no custom `params` are passed (the common case for tool\n * binding). WeakMap ensures cached entries are GC'd when the schema goes\n * out of scope.\n *\n * @internal\n */\nconst _jsonSchemaCache = new WeakMap<object, JSONSchema>();\n\n/**\n * Converts a Standard JSON schema, Zod schema or JSON schema to a JSON schema.\n * Results are cached by schema reference when no custom params are passed.\n * @param schema - The schema to convert.\n * @param params - The parameters to pass to the toJSONSchema function.\n * @returns The converted schema.\n */\nexport function toJsonSchema(\n schema: StandardJSONSchemaV1 | InteropZodType | JSONSchema,\n params?: ToJSONSchemaParams\n): JSONSchema {\n // Cache when no custom params are passed (the default for tool binding).\n // Params can change the output (e.g., different target draft), so we\n // bypass the cache when they're provided.\n const canCache = !params && schema != null && typeof schema === \"object\";\n\n if (canCache) {\n const cached = _jsonSchemaCache.get(schema);\n if (cached) return cached;\n }\n\n let result: JSONSchema;\n\n if (isStandardJsonSchema(schema) && !isZodSchemaV4(schema)) {\n result = schema[\"~standard\"].jsonSchema.input({\n target: \"draft-07\",\n }) as JSONSchema;\n } else if (isZodSchemaV4(schema)) {\n const inputSchema = interopZodTransformInputSchema(schema, true);\n if (isZodObjectV4(inputSchema)) {\n const strictSchema = interopZodObjectStrict(inputSchema, true);\n result = toJSONSchema(strictSchema as unknown as $ZodType, params);\n } else {\n result = toJSONSchema(schema as unknown as $ZodType, params);\n }\n } else if (isZodSchemaV3(schema)) {\n result = zodToJsonSchema(schema as never);\n } else {\n result = schema as JSONSchema;\n }\n\n if (canCache && result != null && typeof result === \"object\") {\n _jsonSchemaCache.set(schema, result);\n }\n\n return result;\n}\n\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport function validatesOnlyStrings(schema: unknown): boolean {\n // Null, undefined, or empty schema\n if (\n !schema ||\n typeof schema !== \"object\" ||\n Object.keys(schema).length === 0 ||\n Array.isArray(schema)\n ) {\n return false; // Validates anything, not just strings\n }\n\n // Explicit type constraint\n if (\"type\" in schema) {\n if (typeof schema.type === \"string\") {\n return schema.type === \"string\";\n }\n\n if (Array.isArray(schema.type)) {\n // not sure why someone would do `\"type\": [\"string\"]` or especially `\"type\": [\"string\",\n // \"string\", \"string\", ...]` but we're not here to judge\n return schema.type.every((t) => t === \"string\");\n }\n return false; // Invalid or non-string type\n }\n\n // Enum with only string values\n if (\"enum\" in schema) {\n return (\n Array.isArray(schema.enum) &&\n schema.enum.length > 0 &&\n schema.enum.every((val) => typeof val === \"string\")\n );\n }\n\n // String constant\n if (\"const\" in schema) {\n return typeof schema.const === \"string\";\n }\n\n // Schema combinations\n if (\"allOf\" in schema && Array.isArray(schema.allOf)) {\n // If any subschema validates only strings, then the overall schema validates only strings\n return schema.allOf.some((subschema) => validatesOnlyStrings(subschema));\n }\n\n if (\n (\"anyOf\" in schema && Array.isArray(schema.anyOf)) ||\n (\"oneOf\" in schema && Array.isArray(schema.oneOf))\n ) {\n const subschemas = (\n \"anyOf\" in schema ? schema.anyOf : schema.oneOf\n ) as unknown[];\n\n // All subschemas must validate only strings\n return (\n subschemas.length > 0 &&\n subschemas.every((subschema) => validatesOnlyStrings(subschema))\n );\n }\n\n // We're not going to try on this one, it's too complex - we just assume if it has a \"not\" key and hasn't matched one of the above checks, it's not a string schema.\n if (\"not\" in schema) {\n return false; // The not case can validate non-strings\n }\n\n if (\"$ref\" in schema && typeof schema.$ref === \"string\") {\n const ref = schema.$ref as string;\n const resolved = dereference(schema as Schema);\n if (resolved[ref]) {\n return validatesOnlyStrings(resolved[ref]);\n }\n return false;\n }\n\n // ignore recursive refs and other cases where type is omitted for now\n // ignore other cases for now where type is omitted\n\n return false;\n}\n\n// Re-export of the types used throughout langchain for json schema serialization.\n// The plan is to eventually nix zod-to-json-schema altogether in place for\n// zod v4 / a more standardized way of serializing validated inputs, so its re-exported\n// here to remove the dependency on zod-to-json-schema in downstream packages until\n// a determination is made.\n\nexport {\n type JsonSchema7Type,\n type JsonSchema7Type as JSONSchema,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"./zod-to-json-schema/index.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,mCAAmB,IAAI,SAA6B;;;;;;;;AAS1D,SAAgB,aACd,QACA,QACY;CAIZ,MAAM,WAAW,CAAC,UAAU,UAAU,QAAQ,OAAO,WAAW;AAEhE,KAAI,UAAU;EACZ,MAAM,SAAS,iBAAiB,IAAI,OAAO;AAC3C,MAAI,OAAQ,QAAO;;CAGrB,IAAI;AAEJ,KAAI,qBAAqB,OAAO,IAAI,CAAC,cAAc,OAAO,CACxD,UAAS,OAAO,aAAa,WAAW,MAAM,EAC5C,QAAQ,YACT,CAAC;UACO,cAAc,OAAO,EAAE;EAChC,MAAM,cAAc,+BAA+B,QAAQ,KAAK;AAChE,MAAI,cAAc,YAAY,CAE5B,UAAS,aADY,uBAAuB,aAAa,
|
|
1
|
+
{"version":3,"file":"json_schema.js","names":[],"sources":["../../src/utils/json_schema.ts"],"sourcesContent":["import { toJSONSchema, type $ZodType } from \"zod/v4/core\";\nimport { dereference, type Schema } from \"@cfworker/json-schema\";\nimport {\n isZodSchemaV3,\n isZodSchemaV4,\n InteropZodType,\n interopZodObjectStrict,\n isZodObjectV4,\n interopZodTransformInputSchema,\n} from \"./types/zod.js\";\nimport {\n type JsonSchema7Type as JSONSchema,\n zodToJsonSchema,\n} from \"./zod-to-json-schema/index.js\";\nimport { StandardJSONSchemaV1 } from \"@standard-schema/spec\";\nimport { isStandardJsonSchema } from \"./standard_schema.js\";\n\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n\nexport type ToJSONSchemaParams = NonNullable<\n Parameters<typeof toJSONSchema>[1]\n>;\n\n/**\n * WeakMap cache for Zod/Standard-Schema → JSON Schema conversions.\n *\n * Keyed on the schema object reference. Since Zod schemas are immutable and\n * the same `tool.schema` reference is passed on every LLM call, this\n * eliminates redundant serializations. For example, an agent with 6 tools\n * doing 15 steps across 3 parallel subagents would otherwise run 270\n * identical conversions per invocation.\n *\n * Only used when no custom `params` are passed (the common case for tool\n * binding). WeakMap ensures cached entries are GC'd when the schema goes\n * out of scope.\n *\n * @internal\n */\nconst _jsonSchemaCache = new WeakMap<object, JSONSchema>();\n\n/**\n * Converts a Standard JSON schema, Zod schema or JSON schema to a JSON schema.\n * Results are cached by schema reference when no custom params are passed.\n * @param schema - The schema to convert.\n * @param params - The parameters to pass to the toJSONSchema function.\n * @returns The converted schema.\n */\nexport function toJsonSchema(\n schema: StandardJSONSchemaV1 | InteropZodType | JSONSchema,\n params?: ToJSONSchemaParams\n): JSONSchema {\n // Cache when no custom params are passed (the default for tool binding).\n // Params can change the output (e.g., different target draft), so we\n // bypass the cache when they're provided.\n const canCache = !params && schema != null && typeof schema === \"object\";\n\n if (canCache) {\n const cached = _jsonSchemaCache.get(schema);\n if (cached) return cached;\n }\n\n let result: JSONSchema;\n\n if (isStandardJsonSchema(schema) && !isZodSchemaV4(schema)) {\n result = schema[\"~standard\"].jsonSchema.input({\n target: \"draft-07\",\n }) as JSONSchema;\n } else if (isZodSchemaV4(schema)) {\n const inputSchema = interopZodTransformInputSchema(schema, true);\n if (isZodObjectV4(inputSchema)) {\n const strictSchema = interopZodObjectStrict(inputSchema, true);\n result = toJSONSchema(strictSchema as unknown as $ZodType, params);\n } else {\n result = toJSONSchema(schema as unknown as $ZodType, params);\n }\n } else if (isZodSchemaV3(schema)) {\n result = zodToJsonSchema(schema as never);\n } else {\n result = schema as JSONSchema;\n }\n\n if (canCache && result != null && typeof result === \"object\") {\n _jsonSchemaCache.set(schema, result);\n }\n\n return result;\n}\n\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport function validatesOnlyStrings(schema: unknown): boolean {\n // Null, undefined, or empty schema\n if (\n !schema ||\n typeof schema !== \"object\" ||\n Object.keys(schema).length === 0 ||\n Array.isArray(schema)\n ) {\n return false; // Validates anything, not just strings\n }\n\n // Explicit type constraint\n if (\"type\" in schema) {\n if (typeof schema.type === \"string\") {\n return schema.type === \"string\";\n }\n\n if (Array.isArray(schema.type)) {\n // not sure why someone would do `\"type\": [\"string\"]` or especially `\"type\": [\"string\",\n // \"string\", \"string\", ...]` but we're not here to judge\n return schema.type.every((t) => t === \"string\");\n }\n return false; // Invalid or non-string type\n }\n\n // Enum with only string values\n if (\"enum\" in schema) {\n return (\n Array.isArray(schema.enum) &&\n schema.enum.length > 0 &&\n schema.enum.every((val) => typeof val === \"string\")\n );\n }\n\n // String constant\n if (\"const\" in schema) {\n return typeof schema.const === \"string\";\n }\n\n // Schema combinations\n if (\"allOf\" in schema && Array.isArray(schema.allOf)) {\n // If any subschema validates only strings, then the overall schema validates only strings\n return schema.allOf.some((subschema) => validatesOnlyStrings(subschema));\n }\n\n if (\n (\"anyOf\" in schema && Array.isArray(schema.anyOf)) ||\n (\"oneOf\" in schema && Array.isArray(schema.oneOf))\n ) {\n const subschemas = (\n \"anyOf\" in schema ? schema.anyOf : schema.oneOf\n ) as unknown[];\n\n // All subschemas must validate only strings\n return (\n subschemas.length > 0 &&\n subschemas.every((subschema) => validatesOnlyStrings(subschema))\n );\n }\n\n // We're not going to try on this one, it's too complex - we just assume if it has a \"not\" key and hasn't matched one of the above checks, it's not a string schema.\n if (\"not\" in schema) {\n return false; // The not case can validate non-strings\n }\n\n if (\"$ref\" in schema && typeof schema.$ref === \"string\") {\n const ref = schema.$ref as string;\n const resolved = dereference(schema as Schema);\n if (resolved[ref]) {\n return validatesOnlyStrings(resolved[ref]);\n }\n return false;\n }\n\n // ignore recursive refs and other cases where type is omitted for now\n // ignore other cases for now where type is omitted\n\n return false;\n}\n\n// Re-export of the types used throughout langchain for json schema serialization.\n// The plan is to eventually nix zod-to-json-schema altogether in place for\n// zod v4 / a more standardized way of serializing validated inputs, so its re-exported\n// here to remove the dependency on zod-to-json-schema in downstream packages until\n// a determination is made.\n\nexport {\n type JsonSchema7Type,\n type JsonSchema7Type as JSONSchema,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"./zod-to-json-schema/index.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,mCAAmB,IAAI,SAA6B;;;;;;;;AAS1D,SAAgB,aACd,QACA,QACY;CAIZ,MAAM,WAAW,CAAC,UAAU,UAAU,QAAQ,OAAO,WAAW;AAEhE,KAAI,UAAU;EACZ,MAAM,SAAS,iBAAiB,IAAI,OAAO;AAC3C,MAAI,OAAQ,QAAO;;CAGrB,IAAI;AAEJ,KAAI,qBAAqB,OAAO,IAAI,CAAC,cAAc,OAAO,CACxD,UAAS,OAAO,aAAa,WAAW,MAAM,EAC5C,QAAQ,YACT,CAAC;UACO,cAAc,OAAO,EAAE;EAChC,MAAM,cAAc,+BAA+B,QAAQ,KAAK;AAChE,MAAI,cAAc,YAAY,CAE5B,UAAS,aADY,uBAAuB,aAAa,KACvB,EAAyB,OAAO;MAElE,UAAS,aAAa,QAA+B,OAAO;YAErD,cAAc,OAAO,CAC9B,UAAS,gBAAgB,OAAgB;KAEzC,UAAS;AAGX,KAAI,YAAY,UAAU,QAAQ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|
|
66
|
-
|
|
66
|
+
let delayTime = calculateDelay(retriesConsumed, options);
|
|
67
|
+
const retryAfterMs = typeof normalizedError.retryAfterMs === "number" && normalizedError.retryAfterMs >= 0 ? normalizedError.retryAfterMs : void 0;
|
|
68
|
+
if (retryAfterMs !== void 0) delayTime = Math.max(delayTime, retryAfterMs);
|
|
67
69
|
const finalDelay = Math.min(delayTime, remainingTime);
|
|
68
70
|
if (finalDelay > 0) await new Promise((resolve, reject) => {
|
|
69
71
|
const onAbort = () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["isNetworkError"],"sources":["../../../src/utils/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_,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iB;IACrB;IACA;IACA;IACA;IACA;IACD,CAAC,CAEF;;;AAMN,OAAM,IAAI,MAAM,sDAAsD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["isNetworkError"],"sources":["../../../src/utils/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 let delayTime = calculateDelay(retriesConsumed, options);\n const retryAfterMs =\n typeof normalizedError.retryAfterMs === \"number\" &&\n normalizedError.retryAfterMs >= 0\n ? normalizedError.retryAfterMs\n : undefined;\n\n if (retryAfterMs !== undefined) {\n delayTime = Math.max(delayTime, retryAfterMs);\n }\n\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;AACh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,gBAAgB;AAEhC,UAAO;WACA,OAAO;AACd,OACE,MAAM,iBAAiB;IACrB;IACA;IACA;IACA;IACA;IACD,CAAC,CAEF;;;AAMN,OAAM,IAAI,MAAM,sDAAsD"}
|
|
@@ -63,7 +63,9 @@ async function onAttemptFailure({ error, attemptNumber, retriesConsumed, startTi
|
|
|
63
63
|
options.signal?.throwIfAborted();
|
|
64
64
|
return false;
|
|
65
65
|
}
|
|
66
|
-
|
|
66
|
+
let delayTime = calculateDelay(retriesConsumed, options);
|
|
67
|
+
const retryAfterMs = typeof normalizedError.retryAfterMs === "number" && normalizedError.retryAfterMs >= 0 ? normalizedError.retryAfterMs : void 0;
|
|
68
|
+
if (retryAfterMs !== void 0) delayTime = Math.max(delayTime, retryAfterMs);
|
|
67
69
|
const finalDelay = Math.min(delayTime, remainingTime);
|
|
68
70
|
if (finalDelay > 0) await new Promise((resolve, reject) => {
|
|
69
71
|
const onAbort = () => {
|